Elizabeth's proactive approach involves introducing urinal toilet attachment , an ingenious concept that optimizes space and functionality.

highcharts.src.js 434KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975
  1. // ==ClosureCompiler==
  2. // @compilation_level SIMPLE_OPTIMIZATIONS
  3. /**
  4. * @license Highcharts JS v3.0.6 (2013-10-04)
  5. *
  6. * (c) 2009-2013 Torstein Hønsi
  7. *
  8. * License: www.highcharts.com/license
  9. */
  10. // JSLint options:
  11. /*global Highcharts, document, window, navigator, setInterval, clearInterval, clearTimeout, setTimeout, location, jQuery, $, console, each, grep */
  12. (function () {
  13. // encapsulated variables
  14. var UNDEFINED,
  15. doc = document,
  16. win = window,
  17. math = Math,
  18. mathRound = math.round,
  19. mathFloor = math.floor,
  20. mathCeil = math.ceil,
  21. mathMax = math.max,
  22. mathMin = math.min,
  23. mathAbs = math.abs,
  24. mathCos = math.cos,
  25. mathSin = math.sin,
  26. mathPI = math.PI,
  27. deg2rad = mathPI * 2 / 360,
  28. // some variables
  29. userAgent = navigator.userAgent,
  30. isOpera = win.opera,
  31. isIE = /msie/i.test(userAgent) && !isOpera,
  32. docMode8 = doc.documentMode === 8,
  33. isWebKit = /AppleWebKit/.test(userAgent),
  34. isFirefox = /Firefox/.test(userAgent),
  35. isTouchDevice = /(Mobile|Android|Windows Phone)/.test(userAgent),
  36. SVG_NS = 'http://www.w3.org/2000/svg',
  37. hasSVG = !!doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect,
  38. hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4, // issue #38
  39. useCanVG = !hasSVG && !isIE && !!doc.createElement('canvas').getContext,
  40. Renderer,
  41. hasTouch = doc.documentElement.ontouchstart !== UNDEFINED,
  42. symbolSizes = {},
  43. idCounter = 0,
  44. garbageBin,
  45. defaultOptions,
  46. dateFormat, // function
  47. globalAnimation,
  48. pathAnim,
  49. timeUnits,
  50. noop = function () {},
  51. charts = [],
  52. PRODUCT = 'Highcharts',
  53. VERSION = '3.0.6',
  54. // some constants for frequently used strings
  55. DIV = 'div',
  56. ABSOLUTE = 'absolute',
  57. RELATIVE = 'relative',
  58. HIDDEN = 'hidden',
  59. PREFIX = 'highcharts-',
  60. VISIBLE = 'visible',
  61. PX = 'px',
  62. NONE = 'none',
  63. M = 'M',
  64. L = 'L',
  65. /*
  66. * Empirical lowest possible opacities for TRACKER_FILL
  67. * IE6: 0.002
  68. * IE7: 0.002
  69. * IE8: 0.002
  70. * IE9: 0.00000000001 (unlimited)
  71. * IE10: 0.0001 (exporting only)
  72. * FF: 0.00000000001 (unlimited)
  73. * Chrome: 0.000001
  74. * Safari: 0.000001
  75. * Opera: 0.00000000001 (unlimited)
  76. */
  77. TRACKER_FILL = 'rgba(192,192,192,' + (hasSVG ? 0.0001 : 0.002) + ')', // invisible but clickable
  78. //TRACKER_FILL = 'rgba(192,192,192,0.5)',
  79. NORMAL_STATE = '',
  80. HOVER_STATE = 'hover',
  81. SELECT_STATE = 'select',
  82. MILLISECOND = 'millisecond',
  83. SECOND = 'second',
  84. MINUTE = 'minute',
  85. HOUR = 'hour',
  86. DAY = 'day',
  87. WEEK = 'week',
  88. MONTH = 'month',
  89. YEAR = 'year',
  90. // constants for attributes
  91. LINEAR_GRADIENT = 'linearGradient',
  92. STOPS = 'stops',
  93. STROKE_WIDTH = 'stroke-width',
  94. // time methods, changed based on whether or not UTC is used
  95. makeTime,
  96. getMinutes,
  97. getHours,
  98. getDay,
  99. getDate,
  100. getMonth,
  101. getFullYear,
  102. setMinutes,
  103. setHours,
  104. setDate,
  105. setMonth,
  106. setFullYear,
  107. // lookup over the types and the associated classes
  108. seriesTypes = {};
  109. // The Highcharts namespace
  110. win.Highcharts = win.Highcharts ? error(16, true) : {};
  111. /**
  112. * Extend an object with the members of another
  113. * @param {Object} a The object to be extended
  114. * @param {Object} b The object to add to the first one
  115. */
  116. function extend(a, b) {
  117. var n;
  118. if (!a) {
  119. a = {};
  120. }
  121. for (n in b) {
  122. a[n] = b[n];
  123. }
  124. return a;
  125. }
  126. /**
  127. * Deep merge two or more objects and return a third object.
  128. * Previously this function redirected to jQuery.extend(true), but this had two limitations.
  129. * First, it deep merged arrays, which lead to workarounds in Highcharts. Second,
  130. * it copied properties from extended prototypes.
  131. */
  132. function merge() {
  133. var i,
  134. len = arguments.length,
  135. ret = {},
  136. doCopy = function (copy, original) {
  137. var value, key;
  138. // An object is replacing a primitive
  139. if (typeof copy !== 'object') {
  140. copy = {};
  141. }
  142. for (key in original) {
  143. if (original.hasOwnProperty(key)) {
  144. value = original[key];
  145. // Copy the contents of objects, but not arrays or DOM nodes
  146. if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]'
  147. && typeof value.nodeType !== 'number') {
  148. copy[key] = doCopy(copy[key] || {}, value);
  149. // Primitives and arrays are copied over directly
  150. } else {
  151. copy[key] = original[key];
  152. }
  153. }
  154. }
  155. return copy;
  156. };
  157. // For each argument, extend the return
  158. for (i = 0; i < len; i++) {
  159. ret = doCopy(ret, arguments[i]);
  160. }
  161. return ret;
  162. }
  163. /**
  164. * Take an array and turn into a hash with even number arguments as keys and odd numbers as
  165. * values. Allows creating constants for commonly used style properties, attributes etc.
  166. * Avoid it in performance critical situations like looping
  167. */
  168. function hash() {
  169. var i = 0,
  170. args = arguments,
  171. length = args.length,
  172. obj = {};
  173. for (; i < length; i++) {
  174. obj[args[i++]] = args[i];
  175. }
  176. return obj;
  177. }
  178. /**
  179. * Shortcut for parseInt
  180. * @param {Object} s
  181. * @param {Number} mag Magnitude
  182. */
  183. function pInt(s, mag) {
  184. return parseInt(s, mag || 10);
  185. }
  186. /**
  187. * Check for string
  188. * @param {Object} s
  189. */
  190. function isString(s) {
  191. return typeof s === 'string';
  192. }
  193. /**
  194. * Check for object
  195. * @param {Object} obj
  196. */
  197. function isObject(obj) {
  198. return typeof obj === 'object';
  199. }
  200. /**
  201. * Check for array
  202. * @param {Object} obj
  203. */
  204. function isArray(obj) {
  205. return Object.prototype.toString.call(obj) === '[object Array]';
  206. }
  207. /**
  208. * Check for number
  209. * @param {Object} n
  210. */
  211. function isNumber(n) {
  212. return typeof n === 'number';
  213. }
  214. function log2lin(num) {
  215. return math.log(num) / math.LN10;
  216. }
  217. function lin2log(num) {
  218. return math.pow(10, num);
  219. }
  220. /**
  221. * Remove last occurence of an item from an array
  222. * @param {Array} arr
  223. * @param {Mixed} item
  224. */
  225. function erase(arr, item) {
  226. var i = arr.length;
  227. while (i--) {
  228. if (arr[i] === item) {
  229. arr.splice(i, 1);
  230. break;
  231. }
  232. }
  233. //return arr;
  234. }
  235. /**
  236. * Returns true if the object is not null or undefined. Like MooTools' $.defined.
  237. * @param {Object} obj
  238. */
  239. function defined(obj) {
  240. return obj !== UNDEFINED && obj !== null;
  241. }
  242. /**
  243. * Set or get an attribute or an object of attributes. Can't use jQuery attr because
  244. * it attempts to set expando properties on the SVG element, which is not allowed.
  245. *
  246. * @param {Object} elem The DOM element to receive the attribute(s)
  247. * @param {String|Object} prop The property or an abject of key-value pairs
  248. * @param {String} value The value if a single property is set
  249. */
  250. function attr(elem, prop, value) {
  251. var key,
  252. setAttribute = 'setAttribute',
  253. ret;
  254. // if the prop is a string
  255. if (isString(prop)) {
  256. // set the value
  257. if (defined(value)) {
  258. elem[setAttribute](prop, value);
  259. // get the value
  260. } else if (elem && elem.getAttribute) { // elem not defined when printing pie demo...
  261. ret = elem.getAttribute(prop);
  262. }
  263. // else if prop is defined, it is a hash of key/value pairs
  264. } else if (defined(prop) && isObject(prop)) {
  265. for (key in prop) {
  266. elem[setAttribute](key, prop[key]);
  267. }
  268. }
  269. return ret;
  270. }
  271. /**
  272. * Check if an element is an array, and if not, make it into an array. Like
  273. * MooTools' $.splat.
  274. */
  275. function splat(obj) {
  276. return isArray(obj) ? obj : [obj];
  277. }
  278. /**
  279. * Return the first value that is defined. Like MooTools' $.pick.
  280. */
  281. function pick() {
  282. var args = arguments,
  283. i,
  284. arg,
  285. length = args.length;
  286. for (i = 0; i < length; i++) {
  287. arg = args[i];
  288. if (typeof arg !== 'undefined' && arg !== null) {
  289. return arg;
  290. }
  291. }
  292. }
  293. /**
  294. * Set CSS on a given element
  295. * @param {Object} el
  296. * @param {Object} styles Style object with camel case property names
  297. */
  298. function css(el, styles) {
  299. if (isIE) {
  300. if (styles && styles.opacity !== UNDEFINED) {
  301. styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')';
  302. }
  303. }
  304. extend(el.style, styles);
  305. }
  306. /**
  307. * Utility function to create element with attributes and styles
  308. * @param {Object} tag
  309. * @param {Object} attribs
  310. * @param {Object} styles
  311. * @param {Object} parent
  312. * @param {Object} nopad
  313. */
  314. function createElement(tag, attribs, styles, parent, nopad) {
  315. var el = doc.createElement(tag);
  316. if (attribs) {
  317. extend(el, attribs);
  318. }
  319. if (nopad) {
  320. css(el, {padding: 0, border: NONE, margin: 0});
  321. }
  322. if (styles) {
  323. css(el, styles);
  324. }
  325. if (parent) {
  326. parent.appendChild(el);
  327. }
  328. return el;
  329. }
  330. /**
  331. * Extend a prototyped class by new members
  332. * @param {Object} parent
  333. * @param {Object} members
  334. */
  335. function extendClass(parent, members) {
  336. var object = function () {};
  337. object.prototype = new parent();
  338. extend(object.prototype, members);
  339. return object;
  340. }
  341. /**
  342. * Format a number and return a string based on input settings
  343. * @param {Number} number The input number to format
  344. * @param {Number} decimals The amount of decimals
  345. * @param {String} decPoint The decimal point, defaults to the one given in the lang options
  346. * @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options
  347. */
  348. function numberFormat(number, decimals, decPoint, thousandsSep) {
  349. var lang = defaultOptions.lang,
  350. // http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/
  351. n = +number || 0,
  352. c = decimals === -1 ?
  353. (n.toString().split('.')[1] || '').length : // preserve decimals
  354. (isNaN(decimals = mathAbs(decimals)) ? 2 : decimals),
  355. d = decPoint === undefined ? lang.decimalPoint : decPoint,
  356. t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep,
  357. s = n < 0 ? "-" : "",
  358. i = String(pInt(n = mathAbs(n).toFixed(c))),
  359. j = i.length > 3 ? i.length % 3 : 0;
  360. return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) +
  361. (c ? d + mathAbs(n - i).toFixed(c).slice(2) : "");
  362. }
  363. /**
  364. * Pad a string to a given length by adding 0 to the beginning
  365. * @param {Number} number
  366. * @param {Number} length
  367. */
  368. function pad(number, length) {
  369. // Create an array of the remaining length +1 and join it with 0's
  370. return new Array((length || 2) + 1 - String(number).length).join(0) + number;
  371. }
  372. /**
  373. * Wrap a method with extended functionality, preserving the original function
  374. * @param {Object} obj The context object that the method belongs to
  375. * @param {String} method The name of the method to extend
  376. * @param {Function} func A wrapper function callback. This function is called with the same arguments
  377. * as the original function, except that the original function is unshifted and passed as the first
  378. * argument.
  379. */
  380. function wrap(obj, method, func) {
  381. var proceed = obj[method];
  382. obj[method] = function () {
  383. var args = Array.prototype.slice.call(arguments);
  384. args.unshift(proceed);
  385. return func.apply(this, args);
  386. };
  387. }
  388. /**
  389. * Based on http://www.php.net/manual/en/function.strftime.php
  390. * @param {String} format
  391. * @param {Number} timestamp
  392. * @param {Boolean} capitalize
  393. */
  394. dateFormat = function (format, timestamp, capitalize) {
  395. if (!defined(timestamp) || isNaN(timestamp)) {
  396. return 'Invalid date';
  397. }
  398. format = pick(format, '%Y-%m-%d %H:%M:%S');
  399. var date = new Date(timestamp),
  400. key, // used in for constuct below
  401. // get the basic time values
  402. hours = date[getHours](),
  403. day = date[getDay](),
  404. dayOfMonth = date[getDate](),
  405. month = date[getMonth](),
  406. fullYear = date[getFullYear](),
  407. lang = defaultOptions.lang,
  408. langWeekdays = lang.weekdays,
  409. // List all format keys. Custom formats can be added from the outside.
  410. replacements = extend({
  411. // Day
  412. 'a': langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon'
  413. 'A': langWeekdays[day], // Long weekday, like 'Monday'
  414. 'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31
  415. 'e': dayOfMonth, // Day of the month, 1 through 31
  416. // Week (none implemented)
  417. //'W': weekNumber(),
  418. // Month
  419. 'b': lang.shortMonths[month], // Short month, like 'Jan'
  420. 'B': lang.months[month], // Long month, like 'January'
  421. 'm': pad(month + 1), // Two digit month number, 01 through 12
  422. // Year
  423. 'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009
  424. 'Y': fullYear, // Four digits year, like 2009
  425. // Time
  426. 'H': pad(hours), // Two digits hours in 24h format, 00 through 23
  427. 'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11
  428. 'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12
  429. 'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59
  430. 'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM
  431. 'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM
  432. 'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59
  433. 'L': pad(mathRound(timestamp % 1000), 3) // Milliseconds (naming from Ruby)
  434. }, Highcharts.dateFormats);
  435. // do the replaces
  436. for (key in replacements) {
  437. while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster
  438. format = format.replace('%' + key, typeof replacements[key] === 'function' ? replacements[key](timestamp) : replacements[key]);
  439. }
  440. }
  441. // Optionally capitalize the string and return
  442. return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format;
  443. };
  444. /**
  445. * Format a single variable. Similar to sprintf, without the % prefix.
  446. */
  447. function formatSingle(format, val) {
  448. var floatRegex = /f$/,
  449. decRegex = /\.([0-9])/,
  450. lang = defaultOptions.lang,
  451. decimals;
  452. if (floatRegex.test(format)) { // float
  453. decimals = format.match(decRegex);
  454. decimals = decimals ? decimals[1] : -1;
  455. val = numberFormat(
  456. val,
  457. decimals,
  458. lang.decimalPoint,
  459. format.indexOf(',') > -1 ? lang.thousandsSep : ''
  460. );
  461. } else {
  462. val = dateFormat(format, val);
  463. }
  464. return val;
  465. }
  466. /**
  467. * Format a string according to a subset of the rules of Python's String.format method.
  468. */
  469. function format(str, ctx) {
  470. var splitter = '{',
  471. isInside = false,
  472. segment,
  473. valueAndFormat,
  474. path,
  475. i,
  476. len,
  477. ret = [],
  478. val,
  479. index;
  480. while ((index = str.indexOf(splitter)) !== -1) {
  481. segment = str.slice(0, index);
  482. if (isInside) { // we're on the closing bracket looking back
  483. valueAndFormat = segment.split(':');
  484. path = valueAndFormat.shift().split('.'); // get first and leave format
  485. len = path.length;
  486. val = ctx;
  487. // Assign deeper paths
  488. for (i = 0; i < len; i++) {
  489. val = val[path[i]];
  490. }
  491. // Format the replacement
  492. if (valueAndFormat.length) {
  493. val = formatSingle(valueAndFormat.join(':'), val);
  494. }
  495. // Push the result and advance the cursor
  496. ret.push(val);
  497. } else {
  498. ret.push(segment);
  499. }
  500. str = str.slice(index + 1); // the rest
  501. isInside = !isInside; // toggle
  502. splitter = isInside ? '}' : '{'; // now look for next matching bracket
  503. }
  504. ret.push(str);
  505. return ret.join('');
  506. }
  507. /**
  508. * Get the magnitude of a number
  509. */
  510. function getMagnitude(num) {
  511. return math.pow(10, mathFloor(math.log(num) / math.LN10));
  512. }
  513. /**
  514. * Take an interval and normalize it to multiples of 1, 2, 2.5 and 5
  515. * @param {Number} interval
  516. * @param {Array} multiples
  517. * @param {Number} magnitude
  518. * @param {Object} options
  519. */
  520. function normalizeTickInterval(interval, multiples, magnitude, options) {
  521. var normalized, i;
  522. // round to a tenfold of 1, 2, 2.5 or 5
  523. magnitude = pick(magnitude, 1);
  524. normalized = interval / magnitude;
  525. // multiples for a linear scale
  526. if (!multiples) {
  527. multiples = [1, 2, 2.5, 5, 10];
  528. // the allowDecimals option
  529. if (options && options.allowDecimals === false) {
  530. if (magnitude === 1) {
  531. multiples = [1, 2, 5, 10];
  532. } else if (magnitude <= 0.1) {
  533. multiples = [1 / magnitude];
  534. }
  535. }
  536. }
  537. // normalize the interval to the nearest multiple
  538. for (i = 0; i < multiples.length; i++) {
  539. interval = multiples[i];
  540. if (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2) {
  541. break;
  542. }
  543. }
  544. // multiply back to the correct magnitude
  545. interval *= magnitude;
  546. return interval;
  547. }
  548. /**
  549. * Get a normalized tick interval for dates. Returns a configuration object with
  550. * unit range (interval), count and name. Used to prepare data for getTimeTicks.
  551. * Previously this logic was part of getTimeTicks, but as getTimeTicks now runs
  552. * of segments in stock charts, the normalizing logic was extracted in order to
  553. * prevent it for running over again for each segment having the same interval.
  554. * #662, #697.
  555. */
  556. function normalizeTimeTickInterval(tickInterval, unitsOption) {
  557. var units = unitsOption || [[
  558. MILLISECOND, // unit name
  559. [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples
  560. ], [
  561. SECOND,
  562. [1, 2, 5, 10, 15, 30]
  563. ], [
  564. MINUTE,
  565. [1, 2, 5, 10, 15, 30]
  566. ], [
  567. HOUR,
  568. [1, 2, 3, 4, 6, 8, 12]
  569. ], [
  570. DAY,
  571. [1, 2]
  572. ], [
  573. WEEK,
  574. [1, 2]
  575. ], [
  576. MONTH,
  577. [1, 2, 3, 4, 6]
  578. ], [
  579. YEAR,
  580. null
  581. ]],
  582. unit = units[units.length - 1], // default unit is years
  583. interval = timeUnits[unit[0]],
  584. multiples = unit[1],
  585. count,
  586. i;
  587. // loop through the units to find the one that best fits the tickInterval
  588. for (i = 0; i < units.length; i++) {
  589. unit = units[i];
  590. interval = timeUnits[unit[0]];
  591. multiples = unit[1];
  592. if (units[i + 1]) {
  593. // lessThan is in the middle between the highest multiple and the next unit.
  594. var lessThan = (interval * multiples[multiples.length - 1] +
  595. timeUnits[units[i + 1][0]]) / 2;
  596. // break and keep the current unit
  597. if (tickInterval <= lessThan) {
  598. break;
  599. }
  600. }
  601. }
  602. // prevent 2.5 years intervals, though 25, 250 etc. are allowed
  603. if (interval === timeUnits[YEAR] && tickInterval < 5 * interval) {
  604. multiples = [1, 2, 5];
  605. }
  606. // get the count
  607. count = normalizeTickInterval(
  608. tickInterval / interval,
  609. multiples,
  610. unit[0] === YEAR ? getMagnitude(tickInterval / interval) : 1 // #1913
  611. );
  612. return {
  613. unitRange: interval,
  614. count: count,
  615. unitName: unit[0]
  616. };
  617. }
  618. /**
  619. * Set the tick positions to a time unit that makes sense, for example
  620. * on the first of each month or on every Monday. Return an array
  621. * with the time positions. Used in datetime axes as well as for grouping
  622. * data on a datetime axis.
  623. *
  624. * @param {Object} normalizedInterval The interval in axis values (ms) and the count
  625. * @param {Number} min The minimum in axis values
  626. * @param {Number} max The maximum in axis values
  627. * @param {Number} startOfWeek
  628. */
  629. function getTimeTicks(normalizedInterval, min, max, startOfWeek) {
  630. var tickPositions = [],
  631. i,
  632. higherRanks = {},
  633. useUTC = defaultOptions.global.useUTC,
  634. minYear, // used in months and years as a basis for Date.UTC()
  635. minDate = new Date(min),
  636. interval = normalizedInterval.unitRange,
  637. count = normalizedInterval.count;
  638. if (defined(min)) { // #1300
  639. if (interval >= timeUnits[SECOND]) { // second
  640. minDate.setMilliseconds(0);
  641. minDate.setSeconds(interval >= timeUnits[MINUTE] ? 0 :
  642. count * mathFloor(minDate.getSeconds() / count));
  643. }
  644. if (interval >= timeUnits[MINUTE]) { // minute
  645. minDate[setMinutes](interval >= timeUnits[HOUR] ? 0 :
  646. count * mathFloor(minDate[getMinutes]() / count));
  647. }
  648. if (interval >= timeUnits[HOUR]) { // hour
  649. minDate[setHours](interval >= timeUnits[DAY] ? 0 :
  650. count * mathFloor(minDate[getHours]() / count));
  651. }
  652. if (interval >= timeUnits[DAY]) { // day
  653. minDate[setDate](interval >= timeUnits[MONTH] ? 1 :
  654. count * mathFloor(minDate[getDate]() / count));
  655. }
  656. if (interval >= timeUnits[MONTH]) { // month
  657. minDate[setMonth](interval >= timeUnits[YEAR] ? 0 :
  658. count * mathFloor(minDate[getMonth]() / count));
  659. minYear = minDate[getFullYear]();
  660. }
  661. if (interval >= timeUnits[YEAR]) { // year
  662. minYear -= minYear % count;
  663. minDate[setFullYear](minYear);
  664. }
  665. // week is a special case that runs outside the hierarchy
  666. if (interval === timeUnits[WEEK]) {
  667. // get start of current week, independent of count
  668. minDate[setDate](minDate[getDate]() - minDate[getDay]() +
  669. pick(startOfWeek, 1));
  670. }
  671. // get tick positions
  672. i = 1;
  673. minYear = minDate[getFullYear]();
  674. var time = minDate.getTime(),
  675. minMonth = minDate[getMonth](),
  676. minDateDate = minDate[getDate](),
  677. timezoneOffset = useUTC ?
  678. 0 :
  679. (24 * 3600 * 1000 + minDate.getTimezoneOffset() * 60 * 1000) % (24 * 3600 * 1000); // #950
  680. // iterate and add tick positions at appropriate values
  681. while (time < max) {
  682. tickPositions.push(time);
  683. // if the interval is years, use Date.UTC to increase years
  684. if (interval === timeUnits[YEAR]) {
  685. time = makeTime(minYear + i * count, 0);
  686. // if the interval is months, use Date.UTC to increase months
  687. } else if (interval === timeUnits[MONTH]) {
  688. time = makeTime(minYear, minMonth + i * count);
  689. // if we're using global time, the interval is not fixed as it jumps
  690. // one hour at the DST crossover
  691. } else if (!useUTC && (interval === timeUnits[DAY] || interval === timeUnits[WEEK])) {
  692. time = makeTime(minYear, minMonth, minDateDate +
  693. i * count * (interval === timeUnits[DAY] ? 1 : 7));
  694. // else, the interval is fixed and we use simple addition
  695. } else {
  696. time += interval * count;
  697. }
  698. i++;
  699. }
  700. // push the last time
  701. tickPositions.push(time);
  702. // mark new days if the time is dividible by day (#1649, #1760)
  703. each(grep(tickPositions, function (time) {
  704. return interval <= timeUnits[HOUR] && time % timeUnits[DAY] === timezoneOffset;
  705. }), function (time) {
  706. higherRanks[time] = DAY;
  707. });
  708. }
  709. // record information on the chosen unit - for dynamic label formatter
  710. tickPositions.info = extend(normalizedInterval, {
  711. higherRanks: higherRanks,
  712. totalRange: interval * count
  713. });
  714. return tickPositions;
  715. }
  716. /**
  717. * Helper class that contains variuos counters that are local to the chart.
  718. */
  719. function ChartCounters() {
  720. this.color = 0;
  721. this.symbol = 0;
  722. }
  723. ChartCounters.prototype = {
  724. /**
  725. * Wraps the color counter if it reaches the specified length.
  726. */
  727. wrapColor: function (length) {
  728. if (this.color >= length) {
  729. this.color = 0;
  730. }
  731. },
  732. /**
  733. * Wraps the symbol counter if it reaches the specified length.
  734. */
  735. wrapSymbol: function (length) {
  736. if (this.symbol >= length) {
  737. this.symbol = 0;
  738. }
  739. }
  740. };
  741. /**
  742. * Utility method that sorts an object array and keeping the order of equal items.
  743. * ECMA script standard does not specify the behaviour when items are equal.
  744. */
  745. function stableSort(arr, sortFunction) {
  746. var length = arr.length,
  747. sortValue,
  748. i;
  749. // Add index to each item
  750. for (i = 0; i < length; i++) {
  751. arr[i].ss_i = i; // stable sort index
  752. }
  753. arr.sort(function (a, b) {
  754. sortValue = sortFunction(a, b);
  755. return sortValue === 0 ? a.ss_i - b.ss_i : sortValue;
  756. });
  757. // Remove index from items
  758. for (i = 0; i < length; i++) {
  759. delete arr[i].ss_i; // stable sort index
  760. }
  761. }
  762. /**
  763. * Non-recursive method to find the lowest member of an array. Math.min raises a maximum
  764. * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
  765. * method is slightly slower, but safe.
  766. */
  767. function arrayMin(data) {
  768. var i = data.length,
  769. min = data[0];
  770. while (i--) {
  771. if (data[i] < min) {
  772. min = data[i];
  773. }
  774. }
  775. return min;
  776. }
  777. /**
  778. * Non-recursive method to find the lowest member of an array. Math.min raises a maximum
  779. * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
  780. * method is slightly slower, but safe.
  781. */
  782. function arrayMax(data) {
  783. var i = data.length,
  784. max = data[0];
  785. while (i--) {
  786. if (data[i] > max) {
  787. max = data[i];
  788. }
  789. }
  790. return max;
  791. }
  792. /**
  793. * Utility method that destroys any SVGElement or VMLElement that are properties on the given object.
  794. * It loops all properties and invokes destroy if there is a destroy method. The property is
  795. * then delete'ed.
  796. * @param {Object} The object to destroy properties on
  797. * @param {Object} Exception, do not destroy this property, only delete it.
  798. */
  799. function destroyObjectProperties(obj, except) {
  800. var n;
  801. for (n in obj) {
  802. // If the object is non-null and destroy is defined
  803. if (obj[n] && obj[n] !== except && obj[n].destroy) {
  804. // Invoke the destroy
  805. obj[n].destroy();
  806. }
  807. // Delete the property from the object.
  808. delete obj[n];
  809. }
  810. }
  811. /**
  812. * Discard an element by moving it to the bin and delete
  813. * @param {Object} The HTML node to discard
  814. */
  815. function discardElement(element) {
  816. // create a garbage bin element, not part of the DOM
  817. if (!garbageBin) {
  818. garbageBin = createElement(DIV);
  819. }
  820. // move the node and empty bin
  821. if (element) {
  822. garbageBin.appendChild(element);
  823. }
  824. garbageBin.innerHTML = '';
  825. }
  826. /**
  827. * Provide error messages for debugging, with links to online explanation
  828. */
  829. function error(code, stop) {
  830. var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code;
  831. if (stop) {
  832. throw msg;
  833. } else if (win.console) {
  834. console.log(msg);
  835. }
  836. }
  837. /**
  838. * Fix JS round off float errors
  839. * @param {Number} num
  840. */
  841. function correctFloat(num) {
  842. return parseFloat(
  843. num.toPrecision(14)
  844. );
  845. }
  846. /**
  847. * Set the global animation to either a given value, or fall back to the
  848. * given chart's animation option
  849. * @param {Object} animation
  850. * @param {Object} chart
  851. */
  852. function setAnimation(animation, chart) {
  853. globalAnimation = pick(animation, chart.animation);
  854. }
  855. /**
  856. * The time unit lookup
  857. */
  858. /*jslint white: true*/
  859. timeUnits = hash(
  860. MILLISECOND, 1,
  861. SECOND, 1000,
  862. MINUTE, 60000,
  863. HOUR, 3600000,
  864. DAY, 24 * 3600000,
  865. WEEK, 7 * 24 * 3600000,
  866. MONTH, 31 * 24 * 3600000,
  867. YEAR, 31556952000
  868. );
  869. /*jslint white: false*/
  870. /**
  871. * Path interpolation algorithm used across adapters
  872. */
  873. pathAnim = {
  874. /**
  875. * Prepare start and end values so that the path can be animated one to one
  876. */
  877. init: function (elem, fromD, toD) {
  878. fromD = fromD || '';
  879. var shift = elem.shift,
  880. bezier = fromD.indexOf('C') > -1,
  881. numParams = bezier ? 7 : 3,
  882. endLength,
  883. slice,
  884. i,
  885. start = fromD.split(' '),
  886. end = [].concat(toD), // copy
  887. startBaseLine,
  888. endBaseLine,
  889. sixify = function (arr) { // in splines make move points have six parameters like bezier curves
  890. i = arr.length;
  891. while (i--) {
  892. if (arr[i] === M) {
  893. arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]);
  894. }
  895. }
  896. };
  897. if (bezier) {
  898. sixify(start);
  899. sixify(end);
  900. }
  901. // pull out the base lines before padding
  902. if (elem.isArea) {
  903. startBaseLine = start.splice(start.length - 6, 6);
  904. endBaseLine = end.splice(end.length - 6, 6);
  905. }
  906. // if shifting points, prepend a dummy point to the end path
  907. if (shift <= end.length / numParams && start.length === end.length) {
  908. while (shift--) {
  909. end = [].concat(end).splice(0, numParams).concat(end);
  910. }
  911. }
  912. elem.shift = 0; // reset for following animations
  913. // copy and append last point until the length matches the end length
  914. if (start.length) {
  915. endLength = end.length;
  916. while (start.length < endLength) {
  917. //bezier && sixify(start);
  918. slice = [].concat(start).splice(start.length - numParams, numParams);
  919. if (bezier) { // disable first control point
  920. slice[numParams - 6] = slice[numParams - 2];
  921. slice[numParams - 5] = slice[numParams - 1];
  922. }
  923. start = start.concat(slice);
  924. }
  925. }
  926. if (startBaseLine) { // append the base lines for areas
  927. start = start.concat(startBaseLine);
  928. end = end.concat(endBaseLine);
  929. }
  930. return [start, end];
  931. },
  932. /**
  933. * Interpolate each value of the path and return the array
  934. */
  935. step: function (start, end, pos, complete) {
  936. var ret = [],
  937. i = start.length,
  938. startVal;
  939. if (pos === 1) { // land on the final path without adjustment points appended in the ends
  940. ret = complete;
  941. } else if (i === end.length && pos < 1) {
  942. while (i--) {
  943. startVal = parseFloat(start[i]);
  944. ret[i] =
  945. isNaN(startVal) ? // a letter instruction like M or L
  946. start[i] :
  947. pos * (parseFloat(end[i] - startVal)) + startVal;
  948. }
  949. } else { // if animation is finished or length not matching, land on right value
  950. ret = end;
  951. }
  952. return ret;
  953. }
  954. };
  955. (function ($) {
  956. /**
  957. * The default HighchartsAdapter for jQuery
  958. */
  959. win.HighchartsAdapter = win.HighchartsAdapter || ($ && {
  960. /**
  961. * Initialize the adapter by applying some extensions to jQuery
  962. */
  963. init: function (pathAnim) {
  964. // extend the animate function to allow SVG animations
  965. var Fx = $.fx,
  966. Step = Fx.step,
  967. dSetter,
  968. Tween = $.Tween,
  969. propHooks = Tween && Tween.propHooks,
  970. opacityHook = $.cssHooks.opacity;
  971. /*jslint unparam: true*//* allow unused param x in this function */
  972. $.extend($.easing, {
  973. easeOutQuad: function (x, t, b, c, d) {
  974. return -c * (t /= d) * (t - 2) + b;
  975. }
  976. });
  977. /*jslint unparam: false*/
  978. // extend some methods to check for elem.attr, which means it is a Highcharts SVG object
  979. $.each(['cur', '_default', 'width', 'height', 'opacity'], function (i, fn) {
  980. var obj = Step,
  981. base,
  982. elem;
  983. // Handle different parent objects
  984. if (fn === 'cur') {
  985. obj = Fx.prototype; // 'cur', the getter, relates to Fx.prototype
  986. } else if (fn === '_default' && Tween) { // jQuery 1.8 model
  987. obj = propHooks[fn];
  988. fn = 'set';
  989. }
  990. // Overwrite the method
  991. base = obj[fn];
  992. if (base) { // step.width and step.height don't exist in jQuery < 1.7
  993. // create the extended function replacement
  994. obj[fn] = function (fx) {
  995. // Fx.prototype.cur does not use fx argument
  996. fx = i ? fx : this;
  997. // Don't run animations on textual properties like align (#1821)
  998. if (fx.prop === 'align') {
  999. return;
  1000. }
  1001. // shortcut
  1002. elem = fx.elem;
  1003. // Fx.prototype.cur returns the current value. The other ones are setters
  1004. // and returning a value has no effect.
  1005. return elem.attr ? // is SVG element wrapper
  1006. elem.attr(fx.prop, fn === 'cur' ? UNDEFINED : fx.now) : // apply the SVG wrapper's method
  1007. base.apply(this, arguments); // use jQuery's built-in method
  1008. };
  1009. }
  1010. });
  1011. // Extend the opacity getter, needed for fading opacity with IE9 and jQuery 1.10+
  1012. wrap(opacityHook, 'get', function (proceed, elem, computed) {
  1013. return elem.attr ? (elem.opacity || 0) : proceed.call(this, elem, computed);
  1014. });
  1015. // Define the setter function for d (path definitions)
  1016. dSetter = function (fx) {
  1017. var elem = fx.elem,
  1018. ends;
  1019. // Normally start and end should be set in state == 0, but sometimes,
  1020. // for reasons unknown, this doesn't happen. Perhaps state == 0 is skipped
  1021. // in these cases
  1022. if (!fx.started) {
  1023. ends = pathAnim.init(elem, elem.d, elem.toD);
  1024. fx.start = ends[0];
  1025. fx.end = ends[1];
  1026. fx.started = true;
  1027. }
  1028. // interpolate each value of the path
  1029. elem.attr('d', pathAnim.step(fx.start, fx.end, fx.pos, elem.toD));
  1030. };
  1031. // jQuery 1.8 style
  1032. if (Tween) {
  1033. propHooks.d = {
  1034. set: dSetter
  1035. };
  1036. // pre 1.8
  1037. } else {
  1038. // animate paths
  1039. Step.d = dSetter;
  1040. }
  1041. /**
  1042. * Utility for iterating over an array. Parameters are reversed compared to jQuery.
  1043. * @param {Array} arr
  1044. * @param {Function} fn
  1045. */
  1046. this.each = Array.prototype.forEach ?
  1047. function (arr, fn) { // modern browsers
  1048. return Array.prototype.forEach.call(arr, fn);
  1049. } :
  1050. function (arr, fn) { // legacy
  1051. var i = 0,
  1052. len = arr.length;
  1053. for (; i < len; i++) {
  1054. if (fn.call(arr[i], arr[i], i, arr) === false) {
  1055. return i;
  1056. }
  1057. }
  1058. };
  1059. /**
  1060. * Register Highcharts as a plugin in the respective framework
  1061. */
  1062. $.fn.highcharts = function () {
  1063. var constr = 'Chart', // default constructor
  1064. args = arguments,
  1065. options,
  1066. ret,
  1067. chart;
  1068. if (isString(args[0])) {
  1069. constr = args[0];
  1070. args = Array.prototype.slice.call(args, 1);
  1071. }
  1072. options = args[0];
  1073. // Create the chart
  1074. if (options !== UNDEFINED) {
  1075. /*jslint unused:false*/
  1076. options.chart = options.chart || {};
  1077. options.chart.renderTo = this[0];
  1078. chart = new Highcharts[constr](options, args[1]);
  1079. ret = this;
  1080. /*jslint unused:true*/
  1081. }
  1082. // When called without parameters or with the return argument, get a predefined chart
  1083. if (options === UNDEFINED) {
  1084. ret = charts[attr(this[0], 'data-highcharts-chart')];
  1085. }
  1086. return ret;
  1087. };
  1088. },
  1089. /**
  1090. * Downloads a script and executes a callback when done.
  1091. * @param {String} scriptLocation
  1092. * @param {Function} callback
  1093. */
  1094. getScript: $.getScript,
  1095. /**
  1096. * Return the index of an item in an array, or -1 if not found
  1097. */
  1098. inArray: $.inArray,
  1099. /**
  1100. * A direct link to jQuery methods. MooTools and Prototype adapters must be implemented for each case of method.
  1101. * @param {Object} elem The HTML element
  1102. * @param {String} method Which method to run on the wrapped element
  1103. */
  1104. adapterRun: function (elem, method) {
  1105. return $(elem)[method]();
  1106. },
  1107. /**
  1108. * Filter an array
  1109. */
  1110. grep: $.grep,
  1111. /**
  1112. * Map an array
  1113. * @param {Array} arr
  1114. * @param {Function} fn
  1115. */
  1116. map: function (arr, fn) {
  1117. //return jQuery.map(arr, fn);
  1118. var results = [],
  1119. i = 0,
  1120. len = arr.length;
  1121. for (; i < len; i++) {
  1122. results[i] = fn.call(arr[i], arr[i], i, arr);
  1123. }
  1124. return results;
  1125. },
  1126. /**
  1127. * Get the position of an element relative to the top left of the page
  1128. */
  1129. offset: function (el) {
  1130. return $(el).offset();
  1131. },
  1132. /**
  1133. * Add an event listener
  1134. * @param {Object} el A HTML element or custom object
  1135. * @param {String} event The event type
  1136. * @param {Function} fn The event handler
  1137. */
  1138. addEvent: function (el, event, fn) {
  1139. $(el).bind(event, fn);
  1140. },
  1141. /**
  1142. * Remove event added with addEvent
  1143. * @param {Object} el The object
  1144. * @param {String} eventType The event type. Leave blank to remove all events.
  1145. * @param {Function} handler The function to remove
  1146. */
  1147. removeEvent: function (el, eventType, handler) {
  1148. // workaround for jQuery issue with unbinding custom events:
  1149. // http://forum.jQuery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jQuery-1-4-2
  1150. var func = doc.removeEventListener ? 'removeEventListener' : 'detachEvent';
  1151. if (doc[func] && el && !el[func]) {
  1152. el[func] = function () {};
  1153. }
  1154. $(el).unbind(eventType, handler);
  1155. },
  1156. /**
  1157. * Fire an event on a custom object
  1158. * @param {Object} el
  1159. * @param {String} type
  1160. * @param {Object} eventArguments
  1161. * @param {Function} defaultFunction
  1162. */
  1163. fireEvent: function (el, type, eventArguments, defaultFunction) {
  1164. var event = $.Event(type),
  1165. detachedType = 'detached' + type,
  1166. defaultPrevented;
  1167. // Remove warnings in Chrome when accessing layerX and layerY. Although Highcharts
  1168. // never uses these properties, Chrome includes them in the default click event and
  1169. // raises the warning when they are copied over in the extend statement below.
  1170. //
  1171. // To avoid problems in IE (see #1010) where we cannot delete the properties and avoid
  1172. // testing if they are there (warning in chrome) the only option is to test if running IE.
  1173. if (!isIE && eventArguments) {
  1174. delete eventArguments.layerX;
  1175. delete eventArguments.layerY;
  1176. }
  1177. extend(event, eventArguments);
  1178. // Prevent jQuery from triggering the object method that is named the
  1179. // same as the event. For example, if the event is 'select', jQuery
  1180. // attempts calling el.select and it goes into a loop.
  1181. if (el[type]) {
  1182. el[detachedType] = el[type];
  1183. el[type] = null;
  1184. }
  1185. // Wrap preventDefault and stopPropagation in try/catch blocks in
  1186. // order to prevent JS errors when cancelling events on non-DOM
  1187. // objects. #615.
  1188. /*jslint unparam: true*/
  1189. $.each(['preventDefault', 'stopPropagation'], function (i, fn) {
  1190. var base = event[fn];
  1191. event[fn] = function () {
  1192. try {
  1193. base.call(event);
  1194. } catch (e) {
  1195. if (fn === 'preventDefault') {
  1196. defaultPrevented = true;
  1197. }
  1198. }
  1199. };
  1200. });
  1201. /*jslint unparam: false*/
  1202. // trigger it
  1203. $(el).trigger(event);
  1204. // attach the method
  1205. if (el[detachedType]) {
  1206. el[type] = el[detachedType];
  1207. el[detachedType] = null;
  1208. }
  1209. if (defaultFunction && !event.isDefaultPrevented() && !defaultPrevented) {
  1210. defaultFunction(event);
  1211. }
  1212. },
  1213. /**
  1214. * Extension method needed for MooTools
  1215. */
  1216. washMouseEvent: function (e) {
  1217. var ret = e.originalEvent || e;
  1218. // computed by jQuery, needed by IE8
  1219. if (ret.pageX === UNDEFINED) { // #1236
  1220. ret.pageX = e.pageX;
  1221. ret.pageY = e.pageY;
  1222. }
  1223. return ret;
  1224. },
  1225. /**
  1226. * Animate a HTML element or SVG element wrapper
  1227. * @param {Object} el
  1228. * @param {Object} params
  1229. * @param {Object} options jQuery-like animation options: duration, easing, callback
  1230. */
  1231. animate: function (el, params, options) {
  1232. var $el = $(el);
  1233. if (!el.style) {
  1234. el.style = {}; // #1881
  1235. }
  1236. if (params.d) {
  1237. el.toD = params.d; // keep the array form for paths, used in $.fx.step.d
  1238. params.d = 1; // because in jQuery, animating to an array has a different meaning
  1239. }
  1240. $el.stop();
  1241. if (params.opacity !== UNDEFINED && el.attr) {
  1242. params.opacity += 'px'; // force jQuery to use same logic as width and height (#2161)
  1243. }
  1244. $el.animate(params, options);
  1245. },
  1246. /**
  1247. * Stop running animation
  1248. */
  1249. stop: function (el) {
  1250. $(el).stop();
  1251. }
  1252. });
  1253. }(win.jQuery));
  1254. // check for a custom HighchartsAdapter defined prior to this file
  1255. var globalAdapter = win.HighchartsAdapter,
  1256. adapter = globalAdapter || {};
  1257. // Initialize the adapter
  1258. if (globalAdapter) {
  1259. globalAdapter.init.call(globalAdapter, pathAnim);
  1260. }
  1261. // Utility functions. If the HighchartsAdapter is not defined, adapter is an empty object
  1262. // and all the utility functions will be null. In that case they are populated by the
  1263. // default adapters below.
  1264. var adapterRun = adapter.adapterRun,
  1265. getScript = adapter.getScript,
  1266. inArray = adapter.inArray,
  1267. each = adapter.each,
  1268. grep = adapter.grep,
  1269. offset = adapter.offset,
  1270. map = adapter.map,
  1271. addEvent = adapter.addEvent,
  1272. removeEvent = adapter.removeEvent,
  1273. fireEvent = adapter.fireEvent,
  1274. washMouseEvent = adapter.washMouseEvent,
  1275. animate = adapter.animate,
  1276. stop = adapter.stop;
  1277. /* ****************************************************************************
  1278. * Handle the options *
  1279. *****************************************************************************/
  1280. var
  1281. defaultLabelOptions = {
  1282. enabled: true,
  1283. // rotation: 0,
  1284. // align: 'center',
  1285. x: 0,
  1286. y: 15,
  1287. /*formatter: function () {
  1288. return this.value;
  1289. },*/
  1290. style: {
  1291. color: '#666',
  1292. cursor: 'default',
  1293. fontSize: '11px',
  1294. lineHeight: '14px'
  1295. }
  1296. };
  1297. defaultOptions = {
  1298. colors: ['#2f7ed8', '#0d233a', '#8bbc21', '#910000', '#1aadce', '#492970',
  1299. '#f28f43', '#77a1e5', '#c42525', '#a6c96a'],
  1300. symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'],
  1301. lang: {
  1302. loading: 'Loading...',
  1303. months: ['January', 'February', 'March', 'April', 'May', 'June', 'July',
  1304. 'August', 'September', 'October', 'November', 'December'],
  1305. shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  1306. weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  1307. decimalPoint: '.',
  1308. numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels
  1309. resetZoom: 'Reset zoom',
  1310. resetZoomTitle: 'Reset zoom level 1:1',
  1311. thousandsSep: ','
  1312. },
  1313. global: {
  1314. useUTC: true,
  1315. canvasToolsURL: 'http://code.highcharts.com/3.0.6/modules/canvas-tools.js',
  1316. VMLRadialGradientURL: 'http://code.highcharts.com/3.0.6/gfx/vml-radial-gradient.png'
  1317. },
  1318. chart: {
  1319. //animation: true,
  1320. //alignTicks: false,
  1321. //reflow: true,
  1322. //className: null,
  1323. //events: { load, selection },
  1324. //margin: [null],
  1325. //marginTop: null,
  1326. //marginRight: null,
  1327. //marginBottom: null,
  1328. //marginLeft: null,
  1329. borderColor: '#4572A7',
  1330. //borderWidth: 0,
  1331. borderRadius: 5,
  1332. defaultSeriesType: 'line',
  1333. ignoreHiddenSeries: true,
  1334. //inverted: false,
  1335. //shadow: false,
  1336. spacing: [10, 10, 15, 10],
  1337. //spacingTop: 10,
  1338. //spacingRight: 10,
  1339. //spacingBottom: 15,
  1340. //spacingLeft: 10,
  1341. style: {
  1342. fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font
  1343. fontSize: '12px'
  1344. },
  1345. backgroundColor: '#FFFFFF',
  1346. //plotBackgroundColor: null,
  1347. plotBorderColor: '#C0C0C0',
  1348. //plotBorderWidth: 0,
  1349. //plotShadow: false,
  1350. //zoomType: ''
  1351. resetZoomButton: {
  1352. theme: {
  1353. zIndex: 20
  1354. },
  1355. position: {
  1356. align: 'right',
  1357. x: -10,
  1358. //verticalAlign: 'top',
  1359. y: 10
  1360. }
  1361. // relativeTo: 'plot'
  1362. }
  1363. },
  1364. title: {
  1365. text: 'Chart title',
  1366. align: 'center',
  1367. // floating: false,
  1368. margin: 15,
  1369. // x: 0,
  1370. // verticalAlign: 'top',
  1371. // y: null,
  1372. style: {
  1373. color: '#274b6d',//#3E576F',
  1374. fontSize: '16px'
  1375. }
  1376. },
  1377. subtitle: {
  1378. text: '',
  1379. align: 'center',
  1380. // floating: false
  1381. // x: 0,
  1382. // verticalAlign: 'top',
  1383. // y: null,
  1384. style: {
  1385. color: '#4d759e'
  1386. }
  1387. },
  1388. plotOptions: {
  1389. line: { // base series options
  1390. allowPointSelect: false,
  1391. showCheckbox: false,
  1392. animation: {
  1393. duration: 1000
  1394. },
  1395. //connectNulls: false,
  1396. //cursor: 'default',
  1397. //clip: true,
  1398. //dashStyle: null,
  1399. //enableMouseTracking: true,
  1400. events: {},
  1401. //legendIndex: 0,
  1402. lineWidth: 2,
  1403. //shadow: false,
  1404. // stacking: null,
  1405. marker: {
  1406. enabled: true,
  1407. //symbol: null,
  1408. lineWidth: 0,
  1409. radius: 4,
  1410. lineColor: '#FFFFFF',
  1411. //fillColor: null,
  1412. states: { // states for a single point
  1413. hover: {
  1414. enabled: true
  1415. //radius: base + 2
  1416. },
  1417. select: {
  1418. fillColor: '#FFFFFF',
  1419. lineColor: '#000000',
  1420. lineWidth: 2
  1421. }
  1422. }
  1423. },
  1424. point: {
  1425. events: {}
  1426. },
  1427. dataLabels: merge(defaultLabelOptions, {
  1428. align: 'center',
  1429. enabled: false,
  1430. formatter: function () {
  1431. return this.y === null ? '' : numberFormat(this.y, -1);
  1432. },
  1433. verticalAlign: 'bottom', // above singular point
  1434. y: 0
  1435. // backgroundColor: undefined,
  1436. // borderColor: undefined,
  1437. // borderRadius: undefined,
  1438. // borderWidth: undefined,
  1439. // padding: 3,
  1440. // shadow: false
  1441. }),
  1442. cropThreshold: 300, // draw points outside the plot area when the number of points is less than this
  1443. pointRange: 0,
  1444. //pointStart: 0,
  1445. //pointInterval: 1,
  1446. showInLegend: true,
  1447. states: { // states for the entire series
  1448. hover: {
  1449. //enabled: false,
  1450. //lineWidth: base + 1,
  1451. marker: {
  1452. // lineWidth: base + 1,
  1453. // radius: base + 1
  1454. }
  1455. },
  1456. select: {
  1457. marker: {}
  1458. }
  1459. },
  1460. stickyTracking: true
  1461. //tooltip: {
  1462. //pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b>'
  1463. //valueDecimals: null,
  1464. //xDateFormat: '%A, %b %e, %Y',
  1465. //valuePrefix: '',
  1466. //ySuffix: ''
  1467. //}
  1468. // turboThreshold: 1000
  1469. // zIndex: null
  1470. }
  1471. },
  1472. labels: {
  1473. //items: [],
  1474. style: {
  1475. //font: defaultFont,
  1476. position: ABSOLUTE,
  1477. color: '#3E576F'
  1478. }
  1479. },
  1480. legend: {
  1481. enabled: true,
  1482. align: 'center',
  1483. //floating: false,
  1484. layout: 'horizontal',
  1485. labelFormatter: function () {
  1486. return this.name;
  1487. },
  1488. borderWidth: 1,
  1489. borderColor: '#909090',
  1490. borderRadius: 5,
  1491. navigation: {
  1492. // animation: true,
  1493. activeColor: '#274b6d',
  1494. // arrowSize: 12
  1495. inactiveColor: '#CCC'
  1496. // style: {} // text styles
  1497. },
  1498. // margin: 10,
  1499. // reversed: false,
  1500. shadow: false,
  1501. // backgroundColor: null,
  1502. /*style: {
  1503. padding: '5px'
  1504. },*/
  1505. itemStyle: {
  1506. cursor: 'pointer',
  1507. color: '#274b6d',
  1508. fontSize: '12px'
  1509. },
  1510. itemHoverStyle: {
  1511. //cursor: 'pointer', removed as of #601
  1512. color: '#000'
  1513. },
  1514. itemHiddenStyle: {
  1515. color: '#CCC'
  1516. },
  1517. itemCheckboxStyle: {
  1518. position: ABSOLUTE,
  1519. width: '13px', // for IE precision
  1520. height: '13px'
  1521. },
  1522. // itemWidth: undefined,
  1523. symbolWidth: 16,
  1524. symbolPadding: 5,
  1525. verticalAlign: 'bottom',
  1526. // width: undefined,
  1527. x: 0,
  1528. y: 0,
  1529. title: {
  1530. //text: null,
  1531. style: {
  1532. fontWeight: 'bold'
  1533. }
  1534. }
  1535. },
  1536. loading: {
  1537. // hideDuration: 100,
  1538. labelStyle: {
  1539. fontWeight: 'bold',
  1540. position: RELATIVE,
  1541. top: '1em'
  1542. },
  1543. // showDuration: 0,
  1544. style: {
  1545. position: ABSOLUTE,
  1546. backgroundColor: 'white',
  1547. opacity: 0.5,
  1548. textAlign: 'center'
  1549. }
  1550. },
  1551. tooltip: {
  1552. enabled: true,
  1553. animation: hasSVG,
  1554. //crosshairs: null,
  1555. backgroundColor: 'rgba(255, 255, 255, .85)',
  1556. borderWidth: 1,
  1557. borderRadius: 3,
  1558. dateTimeLabelFormats: {
  1559. millisecond: '%A, %b %e, %H:%M:%S.%L',
  1560. second: '%A, %b %e, %H:%M:%S',
  1561. minute: '%A, %b %e, %H:%M',
  1562. hour: '%A, %b %e, %H:%M',
  1563. day: '%A, %b %e, %Y',
  1564. week: 'Week from %A, %b %e, %Y',
  1565. month: '%B %Y',
  1566. year: '%Y'
  1567. },
  1568. //formatter: defaultFormatter,
  1569. headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>',
  1570. pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b><br/>',
  1571. shadow: true,
  1572. //shared: false,
  1573. snap: isTouchDevice ? 25 : 10,
  1574. style: {
  1575. color: '#333333',
  1576. cursor: 'default',
  1577. fontSize: '12px',
  1578. padding: '8px',
  1579. whiteSpace: 'nowrap'
  1580. }
  1581. //xDateFormat: '%A, %b %e, %Y',
  1582. //valueDecimals: null,
  1583. //valuePrefix: '',
  1584. //valueSuffix: ''
  1585. },
  1586. credits: {
  1587. enabled: true,
  1588. text: 'Highcharts.com',
  1589. href: 'http://www.highcharts.com',
  1590. position: {
  1591. align: 'right',
  1592. x: -10,
  1593. verticalAlign: 'bottom',
  1594. y: -5
  1595. },
  1596. style: {
  1597. cursor: 'pointer',
  1598. color: '#909090',
  1599. fontSize: '9px'
  1600. }
  1601. }
  1602. };
  1603. // Series defaults
  1604. var defaultPlotOptions = defaultOptions.plotOptions,
  1605. defaultSeriesOptions = defaultPlotOptions.line;
  1606. // set the default time methods
  1607. setTimeMethods();
  1608. /**
  1609. * Set the time methods globally based on the useUTC option. Time method can be either
  1610. * local time or UTC (default).
  1611. */
  1612. function setTimeMethods() {
  1613. var useUTC = defaultOptions.global.useUTC,
  1614. GET = useUTC ? 'getUTC' : 'get',
  1615. SET = useUTC ? 'setUTC' : 'set';
  1616. makeTime = useUTC ? Date.UTC : function (year, month, date, hours, minutes, seconds) {
  1617. return new Date(
  1618. year,
  1619. month,
  1620. pick(date, 1),
  1621. pick(hours, 0),
  1622. pick(minutes, 0),
  1623. pick(seconds, 0)
  1624. ).getTime();
  1625. };
  1626. getMinutes = GET + 'Minutes';
  1627. getHours = GET + 'Hours';
  1628. getDay = GET + 'Day';
  1629. getDate = GET + 'Date';
  1630. getMonth = GET + 'Month';
  1631. getFullYear = GET + 'FullYear';
  1632. setMinutes = SET + 'Minutes';
  1633. setHours = SET + 'Hours';
  1634. setDate = SET + 'Date';
  1635. setMonth = SET + 'Month';
  1636. setFullYear = SET + 'FullYear';
  1637. }
  1638. /**
  1639. * Merge the default options with custom options and return the new options structure
  1640. * @param {Object} options The new custom options
  1641. */
  1642. function setOptions(options) {
  1643. // Pull out axis options and apply them to the respective default axis options
  1644. /*defaultXAxisOptions = merge(defaultXAxisOptions, options.xAxis);
  1645. defaultYAxisOptions = merge(defaultYAxisOptions, options.yAxis);
  1646. options.xAxis = options.yAxis = UNDEFINED;*/
  1647. // Merge in the default options
  1648. defaultOptions = merge(defaultOptions, options);
  1649. // Apply UTC
  1650. setTimeMethods();
  1651. return defaultOptions;
  1652. }
  1653. /**
  1654. * Get the updated default options. Merely exposing defaultOptions for outside modules
  1655. * isn't enough because the setOptions method creates a new object.
  1656. */
  1657. function getOptions() {
  1658. return defaultOptions;
  1659. }
  1660. /**
  1661. * Handle color operations. The object methods are chainable.
  1662. * @param {String} input The input color in either rbga or hex format
  1663. */
  1664. var Color = function (input) {
  1665. // declare variables
  1666. var rgba = [], result, stops;
  1667. /**
  1668. * Parse the input color to rgba array
  1669. * @param {String} input
  1670. */
  1671. function init(input) {
  1672. // Gradients
  1673. if (input && input.stops) {
  1674. stops = map(input.stops, function (stop) {
  1675. return Color(stop[1]);
  1676. });
  1677. // Solid colors
  1678. } else {
  1679. // rgba
  1680. result = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/.exec(input);
  1681. if (result) {
  1682. rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)];
  1683. } else {
  1684. // hex
  1685. result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(input);
  1686. if (result) {
  1687. rgba = [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1];
  1688. } else {
  1689. // rgb
  1690. result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(input);
  1691. if (result) {
  1692. rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1];
  1693. }
  1694. }
  1695. }
  1696. }
  1697. }
  1698. /**
  1699. * Return the color a specified format
  1700. * @param {String} format
  1701. */
  1702. function get(format) {
  1703. var ret;
  1704. if (stops) {
  1705. ret = merge(input);
  1706. ret.stops = [].concat(ret.stops);
  1707. each(stops, function (stop, i) {
  1708. ret.stops[i] = [ret.stops[i][0], stop.get(format)];
  1709. });
  1710. // it's NaN if gradient colors on a column chart
  1711. } else if (rgba && !isNaN(rgba[0])) {
  1712. if (format === 'rgb') {
  1713. ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')';
  1714. } else if (format === 'a') {
  1715. ret = rgba[3];
  1716. } else {
  1717. ret = 'rgba(' + rgba.join(',') + ')';
  1718. }
  1719. } else {
  1720. ret = input;
  1721. }
  1722. return ret;
  1723. }
  1724. /**
  1725. * Brighten the color
  1726. * @param {Number} alpha
  1727. */
  1728. function brighten(alpha) {
  1729. if (stops) {
  1730. each(stops, function (stop) {
  1731. stop.brighten(alpha);
  1732. });
  1733. } else if (isNumber(alpha) && alpha !== 0) {
  1734. var i;
  1735. for (i = 0; i < 3; i++) {
  1736. rgba[i] += pInt(alpha * 255);
  1737. if (rgba[i] < 0) {
  1738. rgba[i] = 0;
  1739. }
  1740. if (rgba[i] > 255) {
  1741. rgba[i] = 255;
  1742. }
  1743. }
  1744. }
  1745. return this;
  1746. }
  1747. /**
  1748. * Set the color's opacity to a given alpha value
  1749. * @param {Number} alpha
  1750. */
  1751. function setOpacity(alpha) {
  1752. rgba[3] = alpha;
  1753. return this;
  1754. }
  1755. // initialize: parse the input
  1756. init(input);
  1757. // public methods
  1758. return {
  1759. get: get,
  1760. brighten: brighten,
  1761. rgba: rgba,
  1762. setOpacity: setOpacity
  1763. };
  1764. };
  1765. /**
  1766. * A wrapper object for SVG elements
  1767. */
  1768. function SVGElement() {}
  1769. SVGElement.prototype = {
  1770. /**
  1771. * Initialize the SVG renderer
  1772. * @param {Object} renderer
  1773. * @param {String} nodeName
  1774. */
  1775. init: function (renderer, nodeName) {
  1776. var wrapper = this;
  1777. wrapper.element = nodeName === 'span' ?
  1778. createElement(nodeName) :
  1779. doc.createElementNS(SVG_NS, nodeName);
  1780. wrapper.renderer = renderer;
  1781. /**
  1782. * A collection of attribute setters. These methods, if defined, are called right before a certain
  1783. * attribute is set on an element wrapper. Returning false prevents the default attribute
  1784. * setter to run. Returning a value causes the default setter to set that value. Used in
  1785. * Renderer.label.
  1786. */
  1787. wrapper.attrSetters = {};
  1788. },
  1789. /**
  1790. * Default base for animation
  1791. */
  1792. opacity: 1,
  1793. /**
  1794. * Animate a given attribute
  1795. * @param {Object} params
  1796. * @param {Number} options The same options as in jQuery animation
  1797. * @param {Function} complete Function to perform at the end of animation
  1798. */
  1799. animate: function (params, options, complete) {
  1800. var animOptions = pick(options, globalAnimation, true);
  1801. stop(this); // stop regardless of animation actually running, or reverting to .attr (#607)
  1802. if (animOptions) {
  1803. animOptions = merge(animOptions);
  1804. if (complete) { // allows using a callback with the global animation without overwriting it
  1805. animOptions.complete = complete;
  1806. }
  1807. animate(this, params, animOptions);
  1808. } else {
  1809. this.attr(params);
  1810. if (complete) {
  1811. complete();
  1812. }
  1813. }
  1814. },
  1815. /**
  1816. * Set or get a given attribute
  1817. * @param {Object|String} hash
  1818. * @param {Mixed|Undefined} val
  1819. */
  1820. attr: function (hash, val) {
  1821. var wrapper = this,
  1822. key,
  1823. value,
  1824. result,
  1825. i,
  1826. child,
  1827. element = wrapper.element,
  1828. nodeName = element.nodeName.toLowerCase(), // Android2 requires lower for "text"
  1829. renderer = wrapper.renderer,
  1830. skipAttr,
  1831. titleNode,
  1832. attrSetters = wrapper.attrSetters,
  1833. shadows = wrapper.shadows,
  1834. hasSetSymbolSize,
  1835. doTransform,
  1836. ret = wrapper;
  1837. // single key-value pair
  1838. if (isString(hash) && defined(val)) {
  1839. key = hash;
  1840. hash = {};
  1841. hash[key] = val;
  1842. }
  1843. // used as a getter: first argument is a string, second is undefined
  1844. if (isString(hash)) {
  1845. key = hash;
  1846. if (nodeName === 'circle') {
  1847. key = { x: 'cx', y: 'cy' }[key] || key;
  1848. } else if (key === 'strokeWidth') {
  1849. key = 'stroke-width';
  1850. }
  1851. ret = attr(element, key) || wrapper[key] || 0;
  1852. if (key !== 'd' && key !== 'visibility' && key !== 'fill') { // 'd' is string in animation step
  1853. ret = parseFloat(ret);
  1854. }
  1855. // setter
  1856. } else {
  1857. for (key in hash) {
  1858. skipAttr = false; // reset
  1859. value = hash[key];
  1860. // check for a specific attribute setter
  1861. result = attrSetters[key] && attrSetters[key].call(wrapper, value, key);
  1862. if (result !== false) {
  1863. if (result !== UNDEFINED) {
  1864. value = result; // the attribute setter has returned a new value to set
  1865. }
  1866. // paths
  1867. if (key === 'd') {
  1868. if (value && value.join) { // join path
  1869. value = value.join(' ');
  1870. }
  1871. if (/(NaN| {2}|^$)/.test(value)) {
  1872. value = 'M 0 0';
  1873. }
  1874. //wrapper.d = value; // shortcut for animations
  1875. // update child tspans x values
  1876. } else if (key === 'x' && nodeName === 'text') {
  1877. for (i = 0; i < element.childNodes.length; i++) {
  1878. child = element.childNodes[i];
  1879. // if the x values are equal, the tspan represents a linebreak
  1880. if (attr(child, 'x') === attr(element, 'x')) {
  1881. //child.setAttribute('x', value);
  1882. attr(child, 'x', value);
  1883. }
  1884. }
  1885. } else if (wrapper.rotation && (key === 'x' || key === 'y')) {
  1886. doTransform = true;
  1887. // apply gradients
  1888. } else if (key === 'fill') {
  1889. value = renderer.color(value, element, key);
  1890. // circle x and y
  1891. } else if (nodeName === 'circle' && (key === 'x' || key === 'y')) {
  1892. key = { x: 'cx', y: 'cy' }[key] || key;
  1893. // rectangle border radius
  1894. } else if (nodeName === 'rect' && key === 'r') {
  1895. attr(element, {
  1896. rx: value,
  1897. ry: value
  1898. });
  1899. skipAttr = true;
  1900. // translation and text rotation
  1901. } else if (key === 'translateX' || key === 'translateY' || key === 'rotation' ||
  1902. key === 'verticalAlign' || key === 'scaleX' || key === 'scaleY') {
  1903. doTransform = true;
  1904. skipAttr = true;
  1905. // apply opacity as subnode (required by legacy WebKit and Batik)
  1906. } else if (key === 'stroke') {
  1907. value = renderer.color(value, element, key);
  1908. // emulate VML's dashstyle implementation
  1909. } else if (key === 'dashstyle') {
  1910. key = 'stroke-dasharray';
  1911. value = value && value.toLowerCase();
  1912. if (value === 'solid') {
  1913. value = NONE;
  1914. } else if (value) {
  1915. value = value
  1916. .replace('shortdashdotdot', '3,1,1,1,1,1,')
  1917. .replace('shortdashdot', '3,1,1,1')
  1918. .replace('shortdot', '1,1,')
  1919. .replace('shortdash', '3,1,')
  1920. .replace('longdash', '8,3,')
  1921. .replace(/dot/g, '1,3,')
  1922. .replace('dash', '4,3,')
  1923. .replace(/,$/, '')
  1924. .split(','); // ending comma
  1925. i = value.length;
  1926. while (i--) {
  1927. value[i] = pInt(value[i]) * pick(hash['stroke-width'], wrapper['stroke-width']);
  1928. }
  1929. value = value.join(',');
  1930. }
  1931. // IE9/MooTools combo: MooTools returns objects instead of numbers and IE9 Beta 2
  1932. // is unable to cast them. Test again with final IE9.
  1933. } else if (key === 'width') {
  1934. value = pInt(value);
  1935. // Text alignment
  1936. } else if (key === 'align') {
  1937. key = 'text-anchor';
  1938. value = { left: 'start', center: 'middle', right: 'end' }[value];
  1939. // Title requires a subnode, #431
  1940. } else if (key === 'title') {
  1941. titleNode = element.getElementsByTagName('title')[0];
  1942. if (!titleNode) {
  1943. titleNode = doc.createElementNS(SVG_NS, 'title');
  1944. element.appendChild(titleNode);
  1945. }
  1946. titleNode.textContent = value;
  1947. }
  1948. // jQuery animate changes case
  1949. if (key === 'strokeWidth') {
  1950. key = 'stroke-width';
  1951. }
  1952. // In Chrome/Win < 6 as well as Batik, the stroke attribute can't be set when the stroke-
  1953. // width is 0. #1369
  1954. if (key === 'stroke-width' || key === 'stroke') {
  1955. wrapper[key] = value;
  1956. // Only apply the stroke attribute if the stroke width is defined and larger than 0
  1957. if (wrapper.stroke && wrapper['stroke-width']) {
  1958. attr(element, 'stroke', wrapper.stroke);
  1959. attr(element, 'stroke-width', wrapper['stroke-width']);
  1960. wrapper.hasStroke = true;
  1961. } else if (key === 'stroke-width' && value === 0 && wrapper.hasStroke) {
  1962. element.removeAttribute('stroke');
  1963. wrapper.hasStroke = false;
  1964. }
  1965. skipAttr = true;
  1966. }
  1967. // symbols
  1968. if (wrapper.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) {
  1969. if (!hasSetSymbolSize) {
  1970. wrapper.symbolAttr(hash);
  1971. hasSetSymbolSize = true;
  1972. }
  1973. skipAttr = true;
  1974. }
  1975. // let the shadow follow the main element
  1976. if (shadows && /^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(key)) {
  1977. i = shadows.length;
  1978. while (i--) {
  1979. attr(
  1980. shadows[i],
  1981. key,
  1982. key === 'height' ?
  1983. mathMax(value - (shadows[i].cutHeight || 0), 0) :
  1984. value
  1985. );
  1986. }
  1987. }
  1988. // validate heights
  1989. if ((key === 'width' || key === 'height') && nodeName === 'rect' && value < 0) {
  1990. value = 0;
  1991. }
  1992. // Record for animation and quick access without polling the DOM
  1993. wrapper[key] = value;
  1994. if (key === 'text') {
  1995. // Delete bBox memo when the text changes
  1996. if (value !== wrapper.textStr) {
  1997. delete wrapper.bBox;
  1998. }
  1999. wrapper.textStr = value;
  2000. if (wrapper.added) {
  2001. renderer.buildText(wrapper);
  2002. }
  2003. } else if (!skipAttr) {
  2004. attr(element, key, value);
  2005. }
  2006. }
  2007. }
  2008. // Update transform. Do this outside the loop to prevent redundant updating for batch setting
  2009. // of attributes.
  2010. if (doTransform) {
  2011. wrapper.updateTransform();
  2012. }
  2013. }
  2014. return ret;
  2015. },
  2016. /**
  2017. * Add a class name to an element
  2018. */
  2019. addClass: function (className) {
  2020. var element = this.element,
  2021. currentClassName = attr(element, 'class') || '';
  2022. if (currentClassName.indexOf(className) === -1) {
  2023. attr(element, 'class', currentClassName + ' ' + className);
  2024. }
  2025. return this;
  2026. },
  2027. /* hasClass and removeClass are not (yet) needed
  2028. hasClass: function (className) {
  2029. return attr(this.element, 'class').indexOf(className) !== -1;
  2030. },
  2031. removeClass: function (className) {
  2032. attr(this.element, 'class', attr(this.element, 'class').replace(className, ''));
  2033. return this;
  2034. },
  2035. */
  2036. /**
  2037. * If one of the symbol size affecting parameters are changed,
  2038. * check all the others only once for each call to an element's
  2039. * .attr() method
  2040. * @param {Object} hash
  2041. */
  2042. symbolAttr: function (hash) {
  2043. var wrapper = this;
  2044. each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function (key) {
  2045. wrapper[key] = pick(hash[key], wrapper[key]);
  2046. });
  2047. wrapper.attr({
  2048. d: wrapper.renderer.symbols[wrapper.symbolName](
  2049. wrapper.x,
  2050. wrapper.y,
  2051. wrapper.width,
  2052. wrapper.height,
  2053. wrapper
  2054. )
  2055. });
  2056. },
  2057. /**
  2058. * Apply a clipping path to this object
  2059. * @param {String} id
  2060. */
  2061. clip: function (clipRect) {
  2062. return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : NONE);
  2063. },
  2064. /**
  2065. * Calculate the coordinates needed for drawing a rectangle crisply and return the
  2066. * calculated attributes
  2067. * @param {Number} strokeWidth
  2068. * @param {Number} x
  2069. * @param {Number} y
  2070. * @param {Number} width
  2071. * @param {Number} height
  2072. */
  2073. crisp: function (strokeWidth, x, y, width, height) {
  2074. var wrapper = this,
  2075. key,
  2076. attribs = {},
  2077. values = {},
  2078. normalizer;
  2079. strokeWidth = strokeWidth || wrapper.strokeWidth || (wrapper.attr && wrapper.attr('stroke-width')) || 0;
  2080. normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors
  2081. // normalize for crisp edges
  2082. values.x = mathFloor(x || wrapper.x || 0) + normalizer;
  2083. values.y = mathFloor(y || wrapper.y || 0) + normalizer;
  2084. values.width = mathFloor((width || wrapper.width || 0) - 2 * normalizer);
  2085. values.height = mathFloor((height || wrapper.height || 0) - 2 * normalizer);
  2086. values.strokeWidth = strokeWidth;
  2087. for (key in values) {
  2088. if (wrapper[key] !== values[key]) { // only set attribute if changed
  2089. wrapper[key] = attribs[key] = values[key];
  2090. }
  2091. }
  2092. return attribs;
  2093. },
  2094. /**
  2095. * Set styles for the element
  2096. * @param {Object} styles
  2097. */
  2098. css: function (styles) {
  2099. /*jslint unparam: true*//* allow unused param a in the regexp function below */
  2100. var elemWrapper = this,
  2101. elem = elemWrapper.element,
  2102. textWidth = styles && styles.width && elem.nodeName.toLowerCase() === 'text',
  2103. n,
  2104. serializedCss = '',
  2105. hyphenate = function (a, b) { return '-' + b.toLowerCase(); };
  2106. /*jslint unparam: false*/
  2107. // convert legacy
  2108. if (styles && styles.color) {
  2109. styles.fill = styles.color;
  2110. }
  2111. // Merge the new styles with the old ones
  2112. styles = extend(
  2113. elemWrapper.styles,
  2114. styles
  2115. );
  2116. // store object
  2117. elemWrapper.styles = styles;
  2118. // Don't handle line wrap on canvas
  2119. if (useCanVG && textWidth) {
  2120. delete styles.width;
  2121. }
  2122. // serialize and set style attribute
  2123. if (isIE && !hasSVG) { // legacy IE doesn't support setting style attribute
  2124. if (textWidth) {
  2125. delete styles.width;
  2126. }
  2127. css(elemWrapper.element, styles);
  2128. } else {
  2129. for (n in styles) {
  2130. serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';';
  2131. }
  2132. attr(elem, 'style', serializedCss); // #1881
  2133. }
  2134. // re-build text
  2135. if (textWidth && elemWrapper.added) {
  2136. elemWrapper.renderer.buildText(elemWrapper);
  2137. }
  2138. return elemWrapper;
  2139. },
  2140. /**
  2141. * Add an event listener
  2142. * @param {String} eventType
  2143. * @param {Function} handler
  2144. */
  2145. on: function (eventType, handler) {
  2146. var svgElement = this,
  2147. element = svgElement.element;
  2148. // touch
  2149. if (hasTouch && eventType === 'click') {
  2150. element.ontouchstart = function (e) {
  2151. svgElement.touchEventFired = Date.now();
  2152. e.preventDefault();
  2153. handler.call(element, e);
  2154. };
  2155. element.onclick = function (e) {
  2156. if (userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { // #2269
  2157. handler.call(element, e);
  2158. }
  2159. };
  2160. } else {
  2161. // simplest possible event model for internal use
  2162. element['on' + eventType] = handler;
  2163. }
  2164. return this;
  2165. },
  2166. /**
  2167. * Set the coordinates needed to draw a consistent radial gradient across
  2168. * pie slices regardless of positioning inside the chart. The format is
  2169. * [centerX, centerY, diameter] in pixels.
  2170. */
  2171. setRadialReference: function (coordinates) {
  2172. this.element.radialReference = coordinates;
  2173. return this;
  2174. },
  2175. /**
  2176. * Move an object and its children by x and y values
  2177. * @param {Number} x
  2178. * @param {Number} y
  2179. */
  2180. translate: function (x, y) {
  2181. return this.attr({
  2182. translateX: x,
  2183. translateY: y
  2184. });
  2185. },
  2186. /**
  2187. * Invert a group, rotate and flip
  2188. */
  2189. invert: function () {
  2190. var wrapper = this;
  2191. wrapper.inverted = true;
  2192. wrapper.updateTransform();
  2193. return wrapper;
  2194. },
  2195. /**
  2196. * Apply CSS to HTML elements. This is used in text within SVG rendering and
  2197. * by the VML renderer
  2198. */
  2199. htmlCss: function (styles) {
  2200. var wrapper = this,
  2201. element = wrapper.element,
  2202. textWidth = styles && element.tagName === 'SPAN' && styles.width;
  2203. if (textWidth) {
  2204. delete styles.width;
  2205. wrapper.textWidth = textWidth;
  2206. wrapper.updateTransform();
  2207. }
  2208. wrapper.styles = extend(wrapper.styles, styles);
  2209. css(wrapper.element, styles);
  2210. return wrapper;
  2211. },
  2212. /**
  2213. * VML and useHTML method for calculating the bounding box based on offsets
  2214. * @param {Boolean} refresh Whether to force a fresh value from the DOM or to
  2215. * use the cached value
  2216. *
  2217. * @return {Object} A hash containing values for x, y, width and height
  2218. */
  2219. htmlGetBBox: function () {
  2220. var wrapper = this,
  2221. element = wrapper.element,
  2222. bBox = wrapper.bBox;
  2223. // faking getBBox in exported SVG in legacy IE
  2224. if (!bBox) {
  2225. // faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?)
  2226. if (element.nodeName === 'text') {
  2227. element.style.position = ABSOLUTE;
  2228. }
  2229. bBox = wrapper.bBox = {
  2230. x: element.offsetLeft,
  2231. y: element.offsetTop,
  2232. width: element.offsetWidth,
  2233. height: element.offsetHeight
  2234. };
  2235. }
  2236. return bBox;
  2237. },
  2238. /**
  2239. * VML override private method to update elements based on internal
  2240. * properties based on SVG transform
  2241. */
  2242. htmlUpdateTransform: function () {
  2243. // aligning non added elements is expensive
  2244. if (!this.added) {
  2245. this.alignOnAdd = true;
  2246. return;
  2247. }
  2248. var wrapper = this,
  2249. renderer = wrapper.renderer,
  2250. elem = wrapper.element,
  2251. translateX = wrapper.translateX || 0,
  2252. translateY = wrapper.translateY || 0,
  2253. x = wrapper.x || 0,
  2254. y = wrapper.y || 0,
  2255. align = wrapper.textAlign || 'left',
  2256. alignCorrection = { left: 0, center: 0.5, right: 1 }[align],
  2257. nonLeft = align && align !== 'left',
  2258. shadows = wrapper.shadows;
  2259. // apply translate
  2260. css(elem, {
  2261. marginLeft: translateX,
  2262. marginTop: translateY
  2263. });
  2264. if (shadows) { // used in labels/tooltip
  2265. each(shadows, function (shadow) {
  2266. css(shadow, {
  2267. marginLeft: translateX + 1,
  2268. marginTop: translateY + 1
  2269. });
  2270. });
  2271. }
  2272. // apply inversion
  2273. if (wrapper.inverted) { // wrapper is a group
  2274. each(elem.childNodes, function (child) {
  2275. renderer.invertChild(child, elem);
  2276. });
  2277. }
  2278. if (elem.tagName === 'SPAN') {
  2279. var width, height,
  2280. rotation = wrapper.rotation,
  2281. baseline,
  2282. radians = 0,
  2283. costheta = 1,
  2284. sintheta = 0,
  2285. quad,
  2286. textWidth = pInt(wrapper.textWidth),
  2287. xCorr = wrapper.xCorr || 0,
  2288. yCorr = wrapper.yCorr || 0,
  2289. currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth].join(',');
  2290. if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed
  2291. if (defined(rotation)) {
  2292. radians = rotation * deg2rad; // deg to rad
  2293. costheta = mathCos(radians);
  2294. sintheta = mathSin(radians);
  2295. wrapper.setSpanRotation(rotation, sintheta, costheta);
  2296. }
  2297. width = pick(wrapper.elemWidth, elem.offsetWidth);
  2298. height = pick(wrapper.elemHeight, elem.offsetHeight);
  2299. // update textWidth
  2300. if (width > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254
  2301. css(elem, {
  2302. width: textWidth + PX,
  2303. display: 'block',
  2304. whiteSpace: 'normal'
  2305. });
  2306. width = textWidth;
  2307. }
  2308. // correct x and y
  2309. baseline = renderer.fontMetrics(elem.style.fontSize).b;
  2310. xCorr = costheta < 0 && -width;
  2311. yCorr = sintheta < 0 && -height;
  2312. // correct for baseline and corners spilling out after rotation
  2313. quad = costheta * sintheta < 0;
  2314. xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection);
  2315. yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1);
  2316. // correct for the length/height of the text
  2317. if (nonLeft) {
  2318. xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1);
  2319. if (rotation) {
  2320. yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1);
  2321. }
  2322. css(elem, {
  2323. textAlign: align
  2324. });
  2325. }
  2326. // record correction
  2327. wrapper.xCorr = xCorr;
  2328. wrapper.yCorr = yCorr;
  2329. }
  2330. // apply position with correction
  2331. css(elem, {
  2332. left: (x + xCorr) + PX,
  2333. top: (y + yCorr) + PX
  2334. });
  2335. // force reflow in webkit to apply the left and top on useHTML element (#1249)
  2336. if (isWebKit) {
  2337. height = elem.offsetHeight; // assigned to height for JSLint purpose
  2338. }
  2339. // record current text transform
  2340. wrapper.cTT = currentTextTransform;
  2341. }
  2342. },
  2343. /**
  2344. * Set the rotation of an individual HTML span
  2345. */
  2346. setSpanRotation: function (rotation) {
  2347. var rotationStyle = {},
  2348. cssTransformKey = isIE ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : '';
  2349. rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)';
  2350. css(this.element, rotationStyle);
  2351. },
  2352. /**
  2353. * Private method to update the transform attribute based on internal
  2354. * properties
  2355. */
  2356. updateTransform: function () {
  2357. var wrapper = this,
  2358. translateX = wrapper.translateX || 0,
  2359. translateY = wrapper.translateY || 0,
  2360. scaleX = wrapper.scaleX,
  2361. scaleY = wrapper.scaleY,
  2362. inverted = wrapper.inverted,
  2363. rotation = wrapper.rotation,
  2364. transform;
  2365. // flipping affects translate as adjustment for flipping around the group's axis
  2366. if (inverted) {
  2367. translateX += wrapper.attr('width');
  2368. translateY += wrapper.attr('height');
  2369. }
  2370. // Apply translate. Nearly all transformed elements have translation, so instead
  2371. // of checking for translate = 0, do it always (#1767, #1846).
  2372. transform = ['translate(' + translateX + ',' + translateY + ')'];
  2373. // apply rotation
  2374. if (inverted) {
  2375. transform.push('rotate(90) scale(-1,1)');
  2376. } else if (rotation) { // text rotation
  2377. transform.push('rotate(' + rotation + ' ' + (wrapper.x || 0) + ' ' + (wrapper.y || 0) + ')');
  2378. }
  2379. // apply scale
  2380. if (defined(scaleX) || defined(scaleY)) {
  2381. transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')');
  2382. }
  2383. if (transform.length) {
  2384. attr(wrapper.element, 'transform', transform.join(' '));
  2385. }
  2386. },
  2387. /**
  2388. * Bring the element to the front
  2389. */
  2390. toFront: function () {
  2391. var element = this.element;
  2392. element.parentNode.appendChild(element);
  2393. return this;
  2394. },
  2395. /**
  2396. * Break down alignment options like align, verticalAlign, x and y
  2397. * to x and y relative to the chart.
  2398. *
  2399. * @param {Object} alignOptions
  2400. * @param {Boolean} alignByTranslate
  2401. * @param {String[Object} box The box to align to, needs a width and height. When the
  2402. * box is a string, it refers to an object in the Renderer. For example, when
  2403. * box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height
  2404. * x and y properties.
  2405. *
  2406. */
  2407. align: function (alignOptions, alignByTranslate, box) {
  2408. var align,
  2409. vAlign,
  2410. x,
  2411. y,
  2412. attribs = {},
  2413. alignTo,
  2414. renderer = this.renderer,
  2415. alignedObjects = renderer.alignedObjects;
  2416. // First call on instanciate
  2417. if (alignOptions) {
  2418. this.alignOptions = alignOptions;
  2419. this.alignByTranslate = alignByTranslate;
  2420. if (!box || isString(box)) { // boxes other than renderer handle this internally
  2421. this.alignTo = alignTo = box || 'renderer';
  2422. erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize
  2423. alignedObjects.push(this);
  2424. box = null; // reassign it below
  2425. }
  2426. // When called on resize, no arguments are supplied
  2427. } else {
  2428. alignOptions = this.alignOptions;
  2429. alignByTranslate = this.alignByTranslate;
  2430. alignTo = this.alignTo;
  2431. }
  2432. box = pick(box, renderer[alignTo], renderer);
  2433. // Assign variables
  2434. align = alignOptions.align;
  2435. vAlign = alignOptions.verticalAlign;
  2436. x = (box.x || 0) + (alignOptions.x || 0); // default: left align
  2437. y = (box.y || 0) + (alignOptions.y || 0); // default: top align
  2438. // Align
  2439. if (align === 'right' || align === 'center') {
  2440. x += (box.width - (alignOptions.width || 0)) /
  2441. { right: 1, center: 2 }[align];
  2442. }
  2443. attribs[alignByTranslate ? 'translateX' : 'x'] = mathRound(x);
  2444. // Vertical align
  2445. if (vAlign === 'bottom' || vAlign === 'middle') {
  2446. y += (box.height - (alignOptions.height || 0)) /
  2447. ({ bottom: 1, middle: 2 }[vAlign] || 1);
  2448. }
  2449. attribs[alignByTranslate ? 'translateY' : 'y'] = mathRound(y);
  2450. // Animate only if already placed
  2451. this[this.placed ? 'animate' : 'attr'](attribs);
  2452. this.placed = true;
  2453. this.alignAttr = attribs;
  2454. return this;
  2455. },
  2456. /**
  2457. * Get the bounding box (width, height, x and y) for the element
  2458. */
  2459. getBBox: function () {
  2460. var wrapper = this,
  2461. bBox = wrapper.bBox,
  2462. renderer = wrapper.renderer,
  2463. width,
  2464. height,
  2465. rotation = wrapper.rotation,
  2466. element = wrapper.element,
  2467. styles = wrapper.styles,
  2468. rad = rotation * deg2rad;
  2469. if (!bBox) {
  2470. // SVG elements
  2471. if (element.namespaceURI === SVG_NS || renderer.forExport) {
  2472. try { // Fails in Firefox if the container has display: none.
  2473. bBox = element.getBBox ?
  2474. // SVG: use extend because IE9 is not allowed to change width and height in case
  2475. // of rotation (below)
  2476. extend({}, element.getBBox()) :
  2477. // Canvas renderer and legacy IE in export mode
  2478. {
  2479. width: element.offsetWidth,
  2480. height: element.offsetHeight
  2481. };
  2482. } catch (e) {}
  2483. // If the bBox is not set, the try-catch block above failed. The other condition
  2484. // is for Opera that returns a width of -Infinity on hidden elements.
  2485. if (!bBox || bBox.width < 0) {
  2486. bBox = { width: 0, height: 0 };
  2487. }
  2488. // VML Renderer or useHTML within SVG
  2489. } else {
  2490. bBox = wrapper.htmlGetBBox();
  2491. }
  2492. // True SVG elements as well as HTML elements in modern browsers using the .useHTML option
  2493. // need to compensated for rotation
  2494. if (renderer.isSVG) {
  2495. width = bBox.width;
  2496. height = bBox.height;
  2497. // Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669)
  2498. if (isIE && styles && styles.fontSize === '11px' && height.toPrecision(3) === '22.7') {
  2499. bBox.height = height = 14;
  2500. }
  2501. // Adjust for rotated text
  2502. if (rotation) {
  2503. bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad));
  2504. bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad));
  2505. }
  2506. }
  2507. wrapper.bBox = bBox;
  2508. }
  2509. return bBox;
  2510. },
  2511. /**
  2512. * Show the element
  2513. */
  2514. show: function () {
  2515. return this.attr({ visibility: VISIBLE });
  2516. },
  2517. /**
  2518. * Hide the element
  2519. */
  2520. hide: function () {
  2521. return this.attr({ visibility: HIDDEN });
  2522. },
  2523. fadeOut: function (duration) {
  2524. var elemWrapper = this;
  2525. elemWrapper.animate({
  2526. opacity: 0
  2527. }, {
  2528. duration: duration || 150,
  2529. complete: function () {
  2530. elemWrapper.hide();
  2531. }
  2532. });
  2533. },
  2534. /**
  2535. * Add the element
  2536. * @param {Object|Undefined} parent Can be an element, an element wrapper or undefined
  2537. * to append the element to the renderer.box.
  2538. */
  2539. add: function (parent) {
  2540. var renderer = this.renderer,
  2541. parentWrapper = parent || renderer,
  2542. parentNode = parentWrapper.element || renderer.box,
  2543. childNodes = parentNode.childNodes,
  2544. element = this.element,
  2545. zIndex = attr(element, 'zIndex'),
  2546. otherElement,
  2547. otherZIndex,
  2548. i,
  2549. inserted;
  2550. if (parent) {
  2551. this.parentGroup = parent;
  2552. }
  2553. // mark as inverted
  2554. this.parentInverted = parent && parent.inverted;
  2555. // build formatted text
  2556. if (this.textStr !== undefined) {
  2557. renderer.buildText(this);
  2558. }
  2559. // mark the container as having z indexed children
  2560. if (zIndex) {
  2561. parentWrapper.handleZ = true;
  2562. zIndex = pInt(zIndex);
  2563. }
  2564. // insert according to this and other elements' zIndex
  2565. if (parentWrapper.handleZ) { // this element or any of its siblings has a z index
  2566. for (i = 0; i < childNodes.length; i++) {
  2567. otherElement = childNodes[i];
  2568. otherZIndex = attr(otherElement, 'zIndex');
  2569. if (otherElement !== element && (
  2570. // insert before the first element with a higher zIndex
  2571. pInt(otherZIndex) > zIndex ||
  2572. // if no zIndex given, insert before the first element with a zIndex
  2573. (!defined(zIndex) && defined(otherZIndex))
  2574. )) {
  2575. parentNode.insertBefore(element, otherElement);
  2576. inserted = true;
  2577. break;
  2578. }
  2579. }
  2580. }
  2581. // default: append at the end
  2582. if (!inserted) {
  2583. parentNode.appendChild(element);
  2584. }
  2585. // mark as added
  2586. this.added = true;
  2587. // fire an event for internal hooks
  2588. fireEvent(this, 'add');
  2589. return this;
  2590. },
  2591. /**
  2592. * Removes a child either by removeChild or move to garbageBin.
  2593. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not.
  2594. */
  2595. safeRemoveChild: function (element) {
  2596. var parentNode = element.parentNode;
  2597. if (parentNode) {
  2598. parentNode.removeChild(element);
  2599. }
  2600. },
  2601. /**
  2602. * Destroy the element and element wrapper
  2603. */
  2604. destroy: function () {
  2605. var wrapper = this,
  2606. element = wrapper.element || {},
  2607. shadows = wrapper.shadows,
  2608. parentToClean = wrapper.renderer.isSVG && element.nodeName === 'SPAN' && element.parentNode,
  2609. grandParent,
  2610. key,
  2611. i;
  2612. // remove events
  2613. element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null;
  2614. stop(wrapper); // stop running animations
  2615. if (wrapper.clipPath) {
  2616. wrapper.clipPath = wrapper.clipPath.destroy();
  2617. }
  2618. // Destroy stops in case this is a gradient object
  2619. if (wrapper.stops) {
  2620. for (i = 0; i < wrapper.stops.length; i++) {
  2621. wrapper.stops[i] = wrapper.stops[i].destroy();
  2622. }
  2623. wrapper.stops = null;
  2624. }
  2625. // remove element
  2626. wrapper.safeRemoveChild(element);
  2627. // destroy shadows
  2628. if (shadows) {
  2629. each(shadows, function (shadow) {
  2630. wrapper.safeRemoveChild(shadow);
  2631. });
  2632. }
  2633. // In case of useHTML, clean up empty containers emulating SVG groups (#1960).
  2634. while (parentToClean && parentToClean.childNodes.length === 0) {
  2635. grandParent = parentToClean.parentNode;
  2636. wrapper.safeRemoveChild(parentToClean);
  2637. parentToClean = grandParent;
  2638. }
  2639. // remove from alignObjects
  2640. if (wrapper.alignTo) {
  2641. erase(wrapper.renderer.alignedObjects, wrapper);
  2642. }
  2643. for (key in wrapper) {
  2644. delete wrapper[key];
  2645. }
  2646. return null;
  2647. },
  2648. /**
  2649. * Add a shadow to the element. Must be done after the element is added to the DOM
  2650. * @param {Boolean|Object} shadowOptions
  2651. */
  2652. shadow: function (shadowOptions, group, cutOff) {
  2653. var shadows = [],
  2654. i,
  2655. shadow,
  2656. element = this.element,
  2657. strokeWidth,
  2658. shadowWidth,
  2659. shadowElementOpacity,
  2660. // compensate for inverted plot area
  2661. transform;
  2662. if (shadowOptions) {
  2663. shadowWidth = pick(shadowOptions.width, 3);
  2664. shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth;
  2665. transform = this.parentInverted ?
  2666. '(-1,-1)' :
  2667. '(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')';
  2668. for (i = 1; i <= shadowWidth; i++) {
  2669. shadow = element.cloneNode(0);
  2670. strokeWidth = (shadowWidth * 2) + 1 - (2 * i);
  2671. attr(shadow, {
  2672. 'isShadow': 'true',
  2673. 'stroke': shadowOptions.color || 'black',
  2674. 'stroke-opacity': shadowElementOpacity * i,
  2675. 'stroke-width': strokeWidth,
  2676. 'transform': 'translate' + transform,
  2677. 'fill': NONE
  2678. });
  2679. if (cutOff) {
  2680. attr(shadow, 'height', mathMax(attr(shadow, 'height') - strokeWidth, 0));
  2681. shadow.cutHeight = strokeWidth;
  2682. }
  2683. if (group) {
  2684. group.element.appendChild(shadow);
  2685. } else {
  2686. element.parentNode.insertBefore(shadow, element);
  2687. }
  2688. shadows.push(shadow);
  2689. }
  2690. this.shadows = shadows;
  2691. }
  2692. return this;
  2693. }
  2694. };
  2695. /**
  2696. * The default SVG renderer
  2697. */
  2698. var SVGRenderer = function () {
  2699. this.init.apply(this, arguments);
  2700. };
  2701. SVGRenderer.prototype = {
  2702. Element: SVGElement,
  2703. /**
  2704. * Initialize the SVGRenderer
  2705. * @param {Object} container
  2706. * @param {Number} width
  2707. * @param {Number} height
  2708. * @param {Boolean} forExport
  2709. */
  2710. init: function (container, width, height, forExport) {
  2711. var renderer = this,
  2712. loc = location,
  2713. boxWrapper,
  2714. element,
  2715. desc;
  2716. boxWrapper = renderer.createElement('svg')
  2717. .attr({
  2718. version: '1.1'
  2719. });
  2720. element = boxWrapper.element;
  2721. container.appendChild(element);
  2722. // For browsers other than IE, add the namespace attribute (#1978)
  2723. if (container.innerHTML.indexOf('xmlns') === -1) {
  2724. attr(element, 'xmlns', SVG_NS);
  2725. }
  2726. // object properties
  2727. renderer.isSVG = true;
  2728. renderer.box = element;
  2729. renderer.boxWrapper = boxWrapper;
  2730. renderer.alignedObjects = [];
  2731. // Page url used for internal references. #24, #672, #1070
  2732. renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ?
  2733. loc.href
  2734. .replace(/#.*?$/, '') // remove the hash
  2735. .replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes
  2736. .replace(/ /g, '%20') : // replace spaces (needed for Safari only)
  2737. '';
  2738. // Add description
  2739. desc = this.createElement('desc').add();
  2740. desc.element.appendChild(doc.createTextNode('Created with ' + PRODUCT + ' ' + VERSION));
  2741. renderer.defs = this.createElement('defs').add();
  2742. renderer.forExport = forExport;
  2743. renderer.gradients = {}; // Object where gradient SvgElements are stored
  2744. renderer.setSize(width, height, false);
  2745. // Issue 110 workaround:
  2746. // In Firefox, if a div is positioned by percentage, its pixel position may land
  2747. // between pixels. The container itself doesn't display this, but an SVG element
  2748. // inside this container will be drawn at subpixel precision. In order to draw
  2749. // sharp lines, this must be compensated for. This doesn't seem to work inside
  2750. // iframes though (like in jsFiddle).
  2751. var subPixelFix, rect;
  2752. if (isFirefox && container.getBoundingClientRect) {
  2753. renderer.subPixelFix = subPixelFix = function () {
  2754. css(container, { left: 0, top: 0 });
  2755. rect = container.getBoundingClientRect();
  2756. css(container, {
  2757. left: (mathCeil(rect.left) - rect.left) + PX,
  2758. top: (mathCeil(rect.top) - rect.top) + PX
  2759. });
  2760. };
  2761. // run the fix now
  2762. subPixelFix();
  2763. // run it on resize
  2764. addEvent(win, 'resize', subPixelFix);
  2765. }
  2766. },
  2767. /**
  2768. * Detect whether the renderer is hidden. This happens when one of the parent elements
  2769. * has display: none. #608.
  2770. */
  2771. isHidden: function () {
  2772. return !this.boxWrapper.getBBox().width;
  2773. },
  2774. /**
  2775. * Destroys the renderer and its allocated members.
  2776. */
  2777. destroy: function () {
  2778. var renderer = this,
  2779. rendererDefs = renderer.defs;
  2780. renderer.box = null;
  2781. renderer.boxWrapper = renderer.boxWrapper.destroy();
  2782. // Call destroy on all gradient elements
  2783. destroyObjectProperties(renderer.gradients || {});
  2784. renderer.gradients = null;
  2785. // Defs are null in VMLRenderer
  2786. // Otherwise, destroy them here.
  2787. if (rendererDefs) {
  2788. renderer.defs = rendererDefs.destroy();
  2789. }
  2790. // Remove sub pixel fix handler
  2791. // We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed
  2792. // See issue #982
  2793. if (renderer.subPixelFix) {
  2794. removeEvent(win, 'resize', renderer.subPixelFix);
  2795. }
  2796. renderer.alignedObjects = null;
  2797. return null;
  2798. },
  2799. /**
  2800. * Create a wrapper for an SVG element
  2801. * @param {Object} nodeName
  2802. */
  2803. createElement: function (nodeName) {
  2804. var wrapper = new this.Element();
  2805. wrapper.init(this, nodeName);
  2806. return wrapper;
  2807. },
  2808. /**
  2809. * Dummy function for use in canvas renderer
  2810. */
  2811. draw: function () {},
  2812. /**
  2813. * Parse a simple HTML string into SVG tspans
  2814. *
  2815. * @param {Object} textNode The parent text SVG node
  2816. */
  2817. buildText: function (wrapper) {
  2818. var textNode = wrapper.element,
  2819. renderer = this,
  2820. forExport = renderer.forExport,
  2821. lines = pick(wrapper.textStr, '').toString()
  2822. .replace(/<(b|strong)>/g, '<span style="font-weight:bold">')
  2823. .replace(/<(i|em)>/g, '<span style="font-style:italic">')
  2824. .replace(/<a/g, '<span')
  2825. .replace(/<\/(b|strong|i|em|a)>/g, '</span>')
  2826. .split(/<br.*?>/g),
  2827. childNodes = textNode.childNodes,
  2828. styleRegex = /style="([^"]+)"/,
  2829. hrefRegex = /href="(http[^"]+)"/,
  2830. parentX = attr(textNode, 'x'),
  2831. textStyles = wrapper.styles,
  2832. width = textStyles && textStyles.width && pInt(textStyles.width),
  2833. textLineHeight = textStyles && textStyles.lineHeight,
  2834. i = childNodes.length;
  2835. /// remove old text
  2836. while (i--) {
  2837. textNode.removeChild(childNodes[i]);
  2838. }
  2839. if (width && !wrapper.added) {
  2840. this.box.appendChild(textNode); // attach it to the DOM to read offset width
  2841. }
  2842. // remove empty line at end
  2843. if (lines[lines.length - 1] === '') {
  2844. lines.pop();
  2845. }
  2846. // build the lines
  2847. each(lines, function (line, lineNo) {
  2848. var spans, spanNo = 0;
  2849. line = line.replace(/<span/g, '|||<span').replace(/<\/span>/g, '</span>|||');
  2850. spans = line.split('|||');
  2851. each(spans, function (span) {
  2852. if (span !== '' || spans.length === 1) {
  2853. var attributes = {},
  2854. tspan = doc.createElementNS(SVG_NS, 'tspan'),
  2855. spanStyle; // #390
  2856. if (styleRegex.test(span)) {
  2857. spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2');
  2858. attr(tspan, 'style', spanStyle);
  2859. }
  2860. if (hrefRegex.test(span) && !forExport) { // Not for export - #1529
  2861. attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"');
  2862. css(tspan, { cursor: 'pointer' });
  2863. }
  2864. span = (span.replace(/<(.|\n)*?>/g, '') || ' ')
  2865. .replace(/&lt;/g, '<')
  2866. .replace(/&gt;/g, '>');
  2867. // Nested tags aren't supported, and cause crash in Safari (#1596)
  2868. if (span !== ' ') {
  2869. // add the text node
  2870. tspan.appendChild(doc.createTextNode(span));
  2871. if (!spanNo) { // first span in a line, align it to the left
  2872. attributes.x = parentX;
  2873. } else {
  2874. attributes.dx = 0; // #16
  2875. }
  2876. // add attributes
  2877. attr(tspan, attributes);
  2878. // first span on subsequent line, add the line height
  2879. if (!spanNo && lineNo) {
  2880. // allow getting the right offset height in exporting in IE
  2881. if (!hasSVG && forExport) {
  2882. css(tspan, { display: 'block' });
  2883. }
  2884. // Set the line height based on the font size of either
  2885. // the text element or the tspan element
  2886. attr(
  2887. tspan,
  2888. 'dy',
  2889. textLineHeight || renderer.fontMetrics(
  2890. /px$/.test(tspan.style.fontSize) ?
  2891. tspan.style.fontSize :
  2892. textStyles.fontSize
  2893. ).h,
  2894. // Safari 6.0.2 - too optimized for its own good (#1539)
  2895. // TODO: revisit this with future versions of Safari
  2896. isWebKit && tspan.offsetHeight
  2897. );
  2898. }
  2899. // Append it
  2900. textNode.appendChild(tspan);
  2901. spanNo++;
  2902. // check width and apply soft breaks
  2903. if (width) {
  2904. var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273
  2905. tooLong,
  2906. actualWidth,
  2907. clipHeight = wrapper._clipHeight,
  2908. rest = [],
  2909. dy = pInt(textLineHeight || 16),
  2910. softLineNo = 1,
  2911. bBox;
  2912. while (words.length || rest.length) {
  2913. delete wrapper.bBox; // delete cache
  2914. bBox = wrapper.getBBox();
  2915. actualWidth = bBox.width;
  2916. tooLong = actualWidth > width;
  2917. if (!tooLong || words.length === 1) { // new line needed
  2918. words = rest;
  2919. rest = [];
  2920. if (words.length) {
  2921. softLineNo++;
  2922. if (clipHeight && softLineNo * dy > clipHeight) {
  2923. words = ['...'];
  2924. wrapper.attr('title', wrapper.textStr);
  2925. } else {
  2926. tspan = doc.createElementNS(SVG_NS, 'tspan');
  2927. attr(tspan, {
  2928. dy: dy,
  2929. x: parentX
  2930. });
  2931. if (spanStyle) { // #390
  2932. attr(tspan, 'style', spanStyle);
  2933. }
  2934. textNode.appendChild(tspan);
  2935. if (actualWidth > width) { // a single word is pressing it out
  2936. width = actualWidth;
  2937. }
  2938. }
  2939. }
  2940. } else { // append to existing line tspan
  2941. tspan.removeChild(tspan.firstChild);
  2942. rest.unshift(words.pop());
  2943. }
  2944. if (words.length) {
  2945. tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-')));
  2946. }
  2947. }
  2948. }
  2949. }
  2950. }
  2951. });
  2952. });
  2953. },
  2954. /**
  2955. * Create a button with preset states
  2956. * @param {String} text
  2957. * @param {Number} x
  2958. * @param {Number} y
  2959. * @param {Function} callback
  2960. * @param {Object} normalState
  2961. * @param {Object} hoverState
  2962. * @param {Object} pressedState
  2963. */
  2964. button: function (text, x, y, callback, normalState, hoverState, pressedState, disabledState) {
  2965. var label = this.label(text, x, y, null, null, null, null, null, 'button'),
  2966. curState = 0,
  2967. stateOptions,
  2968. stateStyle,
  2969. normalStyle,
  2970. hoverStyle,
  2971. pressedStyle,
  2972. disabledStyle,
  2973. STYLE = 'style',
  2974. verticalGradient = { x1: 0, y1: 0, x2: 0, y2: 1 };
  2975. // Normal state - prepare the attributes
  2976. normalState = merge({
  2977. 'stroke-width': 1,
  2978. stroke: '#CCCCCC',
  2979. fill: {
  2980. linearGradient: verticalGradient,
  2981. stops: [
  2982. [0, '#FEFEFE'],
  2983. [1, '#F6F6F6']
  2984. ]
  2985. },
  2986. r: 2,
  2987. padding: 5,
  2988. style: {
  2989. color: 'black'
  2990. }
  2991. }, normalState);
  2992. normalStyle = normalState[STYLE];
  2993. delete normalState[STYLE];
  2994. // Hover state
  2995. hoverState = merge(normalState, {
  2996. stroke: '#68A',
  2997. fill: {
  2998. linearGradient: verticalGradient,
  2999. stops: [
  3000. [0, '#FFF'],
  3001. [1, '#ACF']
  3002. ]
  3003. }
  3004. }, hoverState);
  3005. hoverStyle = hoverState[STYLE];
  3006. delete hoverState[STYLE];
  3007. // Pressed state
  3008. pressedState = merge(normalState, {
  3009. stroke: '#68A',
  3010. fill: {
  3011. linearGradient: verticalGradient,
  3012. stops: [
  3013. [0, '#9BD'],
  3014. [1, '#CDF']
  3015. ]
  3016. }
  3017. }, pressedState);
  3018. pressedStyle = pressedState[STYLE];
  3019. delete pressedState[STYLE];
  3020. // Disabled state
  3021. disabledState = merge(normalState, {
  3022. style: {
  3023. color: '#CCC'
  3024. }
  3025. }, disabledState);
  3026. disabledStyle = disabledState[STYLE];
  3027. delete disabledState[STYLE];
  3028. // Add the events. IE9 and IE10 need mouseover and mouseout to funciton (#667).
  3029. addEvent(label.element, isIE ? 'mouseover' : 'mouseenter', function () {
  3030. if (curState !== 3) {
  3031. label.attr(hoverState)
  3032. .css(hoverStyle);
  3033. }
  3034. });
  3035. addEvent(label.element, isIE ? 'mouseout' : 'mouseleave', function () {
  3036. if (curState !== 3) {
  3037. stateOptions = [normalState, hoverState, pressedState][curState];
  3038. stateStyle = [normalStyle, hoverStyle, pressedStyle][curState];
  3039. label.attr(stateOptions)
  3040. .css(stateStyle);
  3041. }
  3042. });
  3043. label.setState = function (state) {
  3044. label.state = curState = state;
  3045. if (!state) {
  3046. label.attr(normalState)
  3047. .css(normalStyle);
  3048. } else if (state === 2) {
  3049. label.attr(pressedState)
  3050. .css(pressedStyle);
  3051. } else if (state === 3) {
  3052. label.attr(disabledState)
  3053. .css(disabledStyle);
  3054. }
  3055. };
  3056. return label
  3057. .on('click', function () {
  3058. if (curState !== 3) {
  3059. callback.call(label);
  3060. }
  3061. })
  3062. .attr(normalState)
  3063. .css(extend({ cursor: 'default' }, normalStyle));
  3064. },
  3065. /**
  3066. * Make a straight line crisper by not spilling out to neighbour pixels
  3067. * @param {Array} points
  3068. * @param {Number} width
  3069. */
  3070. crispLine: function (points, width) {
  3071. // points format: [M, 0, 0, L, 100, 0]
  3072. // normalize to a crisp line
  3073. if (points[1] === points[4]) {
  3074. // Substract due to #1129. Now bottom and left axis gridlines behave the same.
  3075. points[1] = points[4] = mathRound(points[1]) - (width % 2 / 2);
  3076. }
  3077. if (points[2] === points[5]) {
  3078. points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2);
  3079. }
  3080. return points;
  3081. },
  3082. /**
  3083. * Draw a path
  3084. * @param {Array} path An SVG path in array form
  3085. */
  3086. path: function (path) {
  3087. var attr = {
  3088. fill: NONE
  3089. };
  3090. if (isArray(path)) {
  3091. attr.d = path;
  3092. } else if (isObject(path)) { // attributes
  3093. extend(attr, path);
  3094. }
  3095. return this.createElement('path').attr(attr);
  3096. },
  3097. /**
  3098. * Draw and return an SVG circle
  3099. * @param {Number} x The x position
  3100. * @param {Number} y The y position
  3101. * @param {Number} r The radius
  3102. */
  3103. circle: function (x, y, r) {
  3104. var attr = isObject(x) ?
  3105. x :
  3106. {
  3107. x: x,
  3108. y: y,
  3109. r: r
  3110. };
  3111. return this.createElement('circle').attr(attr);
  3112. },
  3113. /**
  3114. * Draw and return an arc
  3115. * @param {Number} x X position
  3116. * @param {Number} y Y position
  3117. * @param {Number} r Radius
  3118. * @param {Number} innerR Inner radius like used in donut charts
  3119. * @param {Number} start Starting angle
  3120. * @param {Number} end Ending angle
  3121. */
  3122. arc: function (x, y, r, innerR, start, end) {
  3123. var arc;
  3124. if (isObject(x)) {
  3125. y = x.y;
  3126. r = x.r;
  3127. innerR = x.innerR;
  3128. start = x.start;
  3129. end = x.end;
  3130. x = x.x;
  3131. }
  3132. // Arcs are defined as symbols for the ability to set
  3133. // attributes in attr and animate
  3134. arc = this.symbol('arc', x || 0, y || 0, r || 0, r || 0, {
  3135. innerR: innerR || 0,
  3136. start: start || 0,
  3137. end: end || 0
  3138. });
  3139. arc.r = r; // #959
  3140. return arc;
  3141. },
  3142. /**
  3143. * Draw and return a rectangle
  3144. * @param {Number} x Left position
  3145. * @param {Number} y Top position
  3146. * @param {Number} width
  3147. * @param {Number} height
  3148. * @param {Number} r Border corner radius
  3149. * @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing
  3150. */
  3151. rect: function (x, y, width, height, r, strokeWidth) {
  3152. r = isObject(x) ? x.r : r;
  3153. var wrapper = this.createElement('rect').attr({
  3154. rx: r,
  3155. ry: r,
  3156. fill: NONE
  3157. });
  3158. return wrapper.attr(
  3159. isObject(x) ?
  3160. x :
  3161. // do not crispify when an object is passed in (as in column charts)
  3162. wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0))
  3163. );
  3164. },
  3165. /**
  3166. * Resize the box and re-align all aligned elements
  3167. * @param {Object} width
  3168. * @param {Object} height
  3169. * @param {Boolean} animate
  3170. *
  3171. */
  3172. setSize: function (width, height, animate) {
  3173. var renderer = this,
  3174. alignedObjects = renderer.alignedObjects,
  3175. i = alignedObjects.length;
  3176. renderer.width = width;
  3177. renderer.height = height;
  3178. renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({
  3179. width: width,
  3180. height: height
  3181. });
  3182. while (i--) {
  3183. alignedObjects[i].align();
  3184. }
  3185. },
  3186. /**
  3187. * Create a group
  3188. * @param {String} name The group will be given a class name of 'highcharts-{name}'.
  3189. * This can be used for styling and scripting.
  3190. */
  3191. g: function (name) {
  3192. var elem = this.createElement('g');
  3193. return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem;
  3194. },
  3195. /**
  3196. * Display an image
  3197. * @param {String} src
  3198. * @param {Number} x
  3199. * @param {Number} y
  3200. * @param {Number} width
  3201. * @param {Number} height
  3202. */
  3203. image: function (src, x, y, width, height) {
  3204. var attribs = {
  3205. preserveAspectRatio: NONE
  3206. },
  3207. elemWrapper;
  3208. // optional properties
  3209. if (arguments.length > 1) {
  3210. extend(attribs, {
  3211. x: x,
  3212. y: y,
  3213. width: width,
  3214. height: height
  3215. });
  3216. }
  3217. elemWrapper = this.createElement('image').attr(attribs);
  3218. // set the href in the xlink namespace
  3219. if (elemWrapper.element.setAttributeNS) {
  3220. elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink',
  3221. 'href', src);
  3222. } else {
  3223. // could be exporting in IE
  3224. // using href throws "not supported" in ie7 and under, requries regex shim to fix later
  3225. elemWrapper.element.setAttribute('hc-svg-href', src);
  3226. }
  3227. return elemWrapper;
  3228. },
  3229. /**
  3230. * Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object.
  3231. *
  3232. * @param {Object} symbol
  3233. * @param {Object} x
  3234. * @param {Object} y
  3235. * @param {Object} radius
  3236. * @param {Object} options
  3237. */
  3238. symbol: function (symbol, x, y, width, height, options) {
  3239. var obj,
  3240. // get the symbol definition function
  3241. symbolFn = this.symbols[symbol],
  3242. // check if there's a path defined for this symbol
  3243. path = symbolFn && symbolFn(
  3244. mathRound(x),
  3245. mathRound(y),
  3246. width,
  3247. height,
  3248. options
  3249. ),
  3250. imageElement,
  3251. imageRegex = /^url\((.*?)\)$/,
  3252. imageSrc,
  3253. imageSize,
  3254. centerImage;
  3255. if (path) {
  3256. obj = this.path(path);
  3257. // expando properties for use in animate and attr
  3258. extend(obj, {
  3259. symbolName: symbol,
  3260. x: x,
  3261. y: y,
  3262. width: width,
  3263. height: height
  3264. });
  3265. if (options) {
  3266. extend(obj, options);
  3267. }
  3268. // image symbols
  3269. } else if (imageRegex.test(symbol)) {
  3270. // On image load, set the size and position
  3271. centerImage = function (img, size) {
  3272. if (img.element) { // it may be destroyed in the meantime (#1390)
  3273. img.attr({
  3274. width: size[0],
  3275. height: size[1]
  3276. });
  3277. if (!img.alignByTranslate) { // #185
  3278. img.translate(
  3279. mathRound((width - size[0]) / 2), // #1378
  3280. mathRound((height - size[1]) / 2)
  3281. );
  3282. }
  3283. }
  3284. };
  3285. imageSrc = symbol.match(imageRegex)[1];
  3286. imageSize = symbolSizes[imageSrc];
  3287. // Ireate the image synchronously, add attribs async
  3288. obj = this.image(imageSrc)
  3289. .attr({
  3290. x: x,
  3291. y: y
  3292. });
  3293. obj.isImg = true;
  3294. if (imageSize) {
  3295. centerImage(obj, imageSize);
  3296. } else {
  3297. // Initialize image to be 0 size so export will still function if there's no cached sizes.
  3298. //
  3299. obj.attr({ width: 0, height: 0 });
  3300. // Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8,
  3301. // the created element must be assigned to a variable in order to load (#292).
  3302. imageElement = createElement('img', {
  3303. onload: function () {
  3304. centerImage(obj, symbolSizes[imageSrc] = [this.width, this.height]);
  3305. },
  3306. src: imageSrc
  3307. });
  3308. }
  3309. }
  3310. return obj;
  3311. },
  3312. /**
  3313. * An extendable collection of functions for defining symbol paths.
  3314. */
  3315. symbols: {
  3316. 'circle': function (x, y, w, h) {
  3317. var cpw = 0.166 * w;
  3318. return [
  3319. M, x + w / 2, y,
  3320. 'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h,
  3321. 'C', x - cpw, y + h, x - cpw, y, x + w / 2, y,
  3322. 'Z'
  3323. ];
  3324. },
  3325. 'square': function (x, y, w, h) {
  3326. return [
  3327. M, x, y,
  3328. L, x + w, y,
  3329. x + w, y + h,
  3330. x, y + h,
  3331. 'Z'
  3332. ];
  3333. },
  3334. 'triangle': function (x, y, w, h) {
  3335. return [
  3336. M, x + w / 2, y,
  3337. L, x + w, y + h,
  3338. x, y + h,
  3339. 'Z'
  3340. ];
  3341. },
  3342. 'triangle-down': function (x, y, w, h) {
  3343. return [
  3344. M, x, y,
  3345. L, x + w, y,
  3346. x + w / 2, y + h,
  3347. 'Z'
  3348. ];
  3349. },
  3350. 'diamond': function (x, y, w, h) {
  3351. return [
  3352. M, x + w / 2, y,
  3353. L, x + w, y + h / 2,
  3354. x + w / 2, y + h,
  3355. x, y + h / 2,
  3356. 'Z'
  3357. ];
  3358. },
  3359. 'arc': function (x, y, w, h, options) {
  3360. var start = options.start,
  3361. radius = options.r || w || h,
  3362. end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561)
  3363. innerRadius = options.innerR,
  3364. open = options.open,
  3365. cosStart = mathCos(start),
  3366. sinStart = mathSin(start),
  3367. cosEnd = mathCos(end),
  3368. sinEnd = mathSin(end),
  3369. longArc = options.end - start < mathPI ? 0 : 1;
  3370. return [
  3371. M,
  3372. x + radius * cosStart,
  3373. y + radius * sinStart,
  3374. 'A', // arcTo
  3375. radius, // x radius
  3376. radius, // y radius
  3377. 0, // slanting
  3378. longArc, // long or short arc
  3379. 1, // clockwise
  3380. x + radius * cosEnd,
  3381. y + radius * sinEnd,
  3382. open ? M : L,
  3383. x + innerRadius * cosEnd,
  3384. y + innerRadius * sinEnd,
  3385. 'A', // arcTo
  3386. innerRadius, // x radius
  3387. innerRadius, // y radius
  3388. 0, // slanting
  3389. longArc, // long or short arc
  3390. 0, // clockwise
  3391. x + innerRadius * cosStart,
  3392. y + innerRadius * sinStart,
  3393. open ? '' : 'Z' // close
  3394. ];
  3395. }
  3396. },
  3397. /**
  3398. * Define a clipping rectangle
  3399. * @param {String} id
  3400. * @param {Number} x
  3401. * @param {Number} y
  3402. * @param {Number} width
  3403. * @param {Number} height
  3404. */
  3405. clipRect: function (x, y, width, height) {
  3406. var wrapper,
  3407. id = PREFIX + idCounter++,
  3408. clipPath = this.createElement('clipPath').attr({
  3409. id: id
  3410. }).add(this.defs);
  3411. wrapper = this.rect(x, y, width, height, 0).add(clipPath);
  3412. wrapper.id = id;
  3413. wrapper.clipPath = clipPath;
  3414. return wrapper;
  3415. },
  3416. /**
  3417. * Take a color and return it if it's a string, make it a gradient if it's a
  3418. * gradient configuration object. Prior to Highstock, an array was used to define
  3419. * a linear gradient with pixel positions relative to the SVG. In newer versions
  3420. * we change the coordinates to apply relative to the shape, using coordinates
  3421. * 0-1 within the shape. To preserve backwards compatibility, linearGradient
  3422. * in this definition is an object of x1, y1, x2 and y2.
  3423. *
  3424. * @param {Object} color The color or config object
  3425. */
  3426. color: function (color, elem, prop) {
  3427. var renderer = this,
  3428. colorObject,
  3429. regexRgba = /^rgba/,
  3430. gradName,
  3431. gradAttr,
  3432. gradients,
  3433. gradientObject,
  3434. stops,
  3435. stopColor,
  3436. stopOpacity,
  3437. radialReference,
  3438. n,
  3439. id,
  3440. key = [];
  3441. // Apply linear or radial gradients
  3442. if (color && color.linearGradient) {
  3443. gradName = 'linearGradient';
  3444. } else if (color && color.radialGradient) {
  3445. gradName = 'radialGradient';
  3446. }
  3447. if (gradName) {
  3448. gradAttr = color[gradName];
  3449. gradients = renderer.gradients;
  3450. stops = color.stops;
  3451. radialReference = elem.radialReference;
  3452. // Keep < 2.2 kompatibility
  3453. if (isArray(gradAttr)) {
  3454. color[gradName] = gradAttr = {
  3455. x1: gradAttr[0],
  3456. y1: gradAttr[1],
  3457. x2: gradAttr[2],
  3458. y2: gradAttr[3],
  3459. gradientUnits: 'userSpaceOnUse'
  3460. };
  3461. }
  3462. // Correct the radial gradient for the radial reference system
  3463. if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) {
  3464. gradAttr = merge(gradAttr, {
  3465. cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2],
  3466. cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2],
  3467. r: gradAttr.r * radialReference[2],
  3468. gradientUnits: 'userSpaceOnUse'
  3469. });
  3470. }
  3471. // Build the unique key to detect whether we need to create a new element (#1282)
  3472. for (n in gradAttr) {
  3473. if (n !== 'id') {
  3474. key.push(n, gradAttr[n]);
  3475. }
  3476. }
  3477. for (n in stops) {
  3478. key.push(stops[n]);
  3479. }
  3480. key = key.join(',');
  3481. // Check if a gradient object with the same config object is created within this renderer
  3482. if (gradients[key]) {
  3483. id = gradients[key].id;
  3484. } else {
  3485. // Set the id and create the element
  3486. gradAttr.id = id = PREFIX + idCounter++;
  3487. gradients[key] = gradientObject = renderer.createElement(gradName)
  3488. .attr(gradAttr)
  3489. .add(renderer.defs);
  3490. // The gradient needs to keep a list of stops to be able to destroy them
  3491. gradientObject.stops = [];
  3492. each(stops, function (stop) {
  3493. var stopObject;
  3494. if (regexRgba.test(stop[1])) {
  3495. colorObject = Color(stop[1]);
  3496. stopColor = colorObject.get('rgb');
  3497. stopOpacity = colorObject.get('a');
  3498. } else {
  3499. stopColor = stop[1];
  3500. stopOpacity = 1;
  3501. }
  3502. stopObject = renderer.createElement('stop').attr({
  3503. offset: stop[0],
  3504. 'stop-color': stopColor,
  3505. 'stop-opacity': stopOpacity
  3506. }).add(gradientObject);
  3507. // Add the stop element to the gradient
  3508. gradientObject.stops.push(stopObject);
  3509. });
  3510. }
  3511. // Return the reference to the gradient object
  3512. return 'url(' + renderer.url + '#' + id + ')';
  3513. // Webkit and Batik can't show rgba.
  3514. } else if (regexRgba.test(color)) {
  3515. colorObject = Color(color);
  3516. attr(elem, prop + '-opacity', colorObject.get('a'));
  3517. return colorObject.get('rgb');
  3518. } else {
  3519. // Remove the opacity attribute added above. Does not throw if the attribute is not there.
  3520. elem.removeAttribute(prop + '-opacity');
  3521. return color;
  3522. }
  3523. },
  3524. /**
  3525. * Add text to the SVG object
  3526. * @param {String} str
  3527. * @param {Number} x Left position
  3528. * @param {Number} y Top position
  3529. * @param {Boolean} useHTML Use HTML to render the text
  3530. */
  3531. text: function (str, x, y, useHTML) {
  3532. // declare variables
  3533. var renderer = this,
  3534. defaultChartStyle = defaultOptions.chart.style,
  3535. fakeSVG = useCanVG || (!hasSVG && renderer.forExport),
  3536. wrapper;
  3537. if (useHTML && !renderer.forExport) {
  3538. return renderer.html(str, x, y);
  3539. }
  3540. x = mathRound(pick(x, 0));
  3541. y = mathRound(pick(y, 0));
  3542. wrapper = renderer.createElement('text')
  3543. .attr({
  3544. x: x,
  3545. y: y,
  3546. text: str
  3547. })
  3548. .css({
  3549. fontFamily: defaultChartStyle.fontFamily,
  3550. fontSize: defaultChartStyle.fontSize
  3551. });
  3552. // Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063)
  3553. if (fakeSVG) {
  3554. wrapper.css({
  3555. position: ABSOLUTE
  3556. });
  3557. }
  3558. wrapper.x = x;
  3559. wrapper.y = y;
  3560. return wrapper;
  3561. },
  3562. /**
  3563. * Create HTML text node. This is used by the VML renderer as well as the SVG
  3564. * renderer through the useHTML option.
  3565. *
  3566. * @param {String} str
  3567. * @param {Number} x
  3568. * @param {Number} y
  3569. */
  3570. html: function (str, x, y) {
  3571. var defaultChartStyle = defaultOptions.chart.style,
  3572. wrapper = this.createElement('span'),
  3573. attrSetters = wrapper.attrSetters,
  3574. element = wrapper.element,
  3575. renderer = wrapper.renderer;
  3576. // Text setter
  3577. attrSetters.text = function (value) {
  3578. if (value !== element.innerHTML) {
  3579. delete this.bBox;
  3580. }
  3581. element.innerHTML = value;
  3582. return false;
  3583. };
  3584. // Various setters which rely on update transform
  3585. attrSetters.x = attrSetters.y = attrSetters.align = function (value, key) {
  3586. if (key === 'align') {
  3587. key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML.
  3588. }
  3589. wrapper[key] = value;
  3590. wrapper.htmlUpdateTransform();
  3591. return false;
  3592. };
  3593. // Set the default attributes
  3594. wrapper.attr({
  3595. text: str,
  3596. x: mathRound(x),
  3597. y: mathRound(y)
  3598. })
  3599. .css({
  3600. position: ABSOLUTE,
  3601. whiteSpace: 'nowrap',
  3602. fontFamily: defaultChartStyle.fontFamily,
  3603. fontSize: defaultChartStyle.fontSize
  3604. });
  3605. // Use the HTML specific .css method
  3606. wrapper.css = wrapper.htmlCss;
  3607. // This is specific for HTML within SVG
  3608. if (renderer.isSVG) {
  3609. wrapper.add = function (svgGroupWrapper) {
  3610. var htmlGroup,
  3611. container = renderer.box.parentNode,
  3612. parentGroup,
  3613. parents = [];
  3614. // Create a mock group to hold the HTML elements
  3615. if (svgGroupWrapper) {
  3616. htmlGroup = svgGroupWrapper.div;
  3617. if (!htmlGroup) {
  3618. // Read the parent chain into an array and read from top down
  3619. parentGroup = svgGroupWrapper;
  3620. while (parentGroup) {
  3621. parents.push(parentGroup);
  3622. // Move up to the next parent group
  3623. parentGroup = parentGroup.parentGroup;
  3624. }
  3625. // Ensure dynamically updating position when any parent is translated
  3626. each(parents.reverse(), function (parentGroup) {
  3627. var htmlGroupStyle;
  3628. // Create a HTML div and append it to the parent div to emulate
  3629. // the SVG group structure
  3630. htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, {
  3631. className: attr(parentGroup.element, 'class')
  3632. }, {
  3633. position: ABSOLUTE,
  3634. left: (parentGroup.translateX || 0) + PX,
  3635. top: (parentGroup.translateY || 0) + PX
  3636. }, htmlGroup || container); // the top group is appended to container
  3637. // Shortcut
  3638. htmlGroupStyle = htmlGroup.style;
  3639. // Set listeners to update the HTML div's position whenever the SVG group
  3640. // position is changed
  3641. extend(parentGroup.attrSetters, {
  3642. translateX: function (value) {
  3643. htmlGroupStyle.left = value + PX;
  3644. },
  3645. translateY: function (value) {
  3646. htmlGroupStyle.top = value + PX;
  3647. },
  3648. visibility: function (value, key) {
  3649. htmlGroupStyle[key] = value;
  3650. }
  3651. });
  3652. });
  3653. }
  3654. } else {
  3655. htmlGroup = container;
  3656. }
  3657. htmlGroup.appendChild(element);
  3658. // Shared with VML:
  3659. wrapper.added = true;
  3660. if (wrapper.alignOnAdd) {
  3661. wrapper.htmlUpdateTransform();
  3662. }
  3663. return wrapper;
  3664. };
  3665. }
  3666. return wrapper;
  3667. },
  3668. /**
  3669. * Utility to return the baseline offset and total line height from the font size
  3670. */
  3671. fontMetrics: function (fontSize) {
  3672. fontSize = pInt(fontSize || 11);
  3673. // Empirical values found by comparing font size and bounding box height.
  3674. // Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/
  3675. var lineHeight = fontSize < 24 ? fontSize + 4 : mathRound(fontSize * 1.2),
  3676. baseline = mathRound(lineHeight * 0.8);
  3677. return {
  3678. h: lineHeight,
  3679. b: baseline
  3680. };
  3681. },
  3682. /**
  3683. * Add a label, a text item that can hold a colored or gradient background
  3684. * as well as a border and shadow.
  3685. * @param {string} str
  3686. * @param {Number} x
  3687. * @param {Number} y
  3688. * @param {String} shape
  3689. * @param {Number} anchorX In case the shape has a pointer, like a flag, this is the
  3690. * coordinates it should be pinned to
  3691. * @param {Number} anchorY
  3692. * @param {Boolean} baseline Whether to position the label relative to the text baseline,
  3693. * like renderer.text, or to the upper border of the rectangle.
  3694. * @param {String} className Class name for the group
  3695. */
  3696. label: function (str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) {
  3697. var renderer = this,
  3698. wrapper = renderer.g(className),
  3699. text = renderer.text('', 0, 0, useHTML)
  3700. .attr({
  3701. zIndex: 1
  3702. }),
  3703. //.add(wrapper),
  3704. box,
  3705. bBox,
  3706. alignFactor = 0,
  3707. padding = 3,
  3708. paddingLeft = 0,
  3709. width,
  3710. height,
  3711. wrapperX,
  3712. wrapperY,
  3713. crispAdjust = 0,
  3714. deferredAttr = {},
  3715. baselineOffset,
  3716. attrSetters = wrapper.attrSetters,
  3717. needsBox;
  3718. /**
  3719. * This function runs after the label is added to the DOM (when the bounding box is
  3720. * available), and after the text of the label is updated to detect the new bounding
  3721. * box and reflect it in the border box.
  3722. */
  3723. function updateBoxSize() {
  3724. var boxX,
  3725. boxY,
  3726. style = text.element.style;
  3727. bBox = (width === undefined || height === undefined || wrapper.styles.textAlign) &&
  3728. text.getBBox();
  3729. wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft;
  3730. wrapper.height = (height || bBox.height || 0) + 2 * padding;
  3731. // update the label-scoped y offset
  3732. baselineOffset = padding + renderer.fontMetrics(style && style.fontSize).b;
  3733. if (needsBox) {
  3734. // create the border box if it is not already present
  3735. if (!box) {
  3736. boxX = mathRound(-alignFactor * padding);
  3737. boxY = baseline ? -baselineOffset : 0;
  3738. wrapper.box = box = shape ?
  3739. renderer.symbol(shape, boxX, boxY, wrapper.width, wrapper.height) :
  3740. renderer.rect(boxX, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]);
  3741. box.add(wrapper);
  3742. }
  3743. // apply the box attributes
  3744. if (!box.isImg) { // #1630
  3745. box.attr(merge({
  3746. width: wrapper.width,
  3747. height: wrapper.height
  3748. }, deferredAttr));
  3749. }
  3750. deferredAttr = null;
  3751. }
  3752. }
  3753. /**
  3754. * This function runs after setting text or padding, but only if padding is changed
  3755. */
  3756. function updateTextPadding() {
  3757. var styles = wrapper.styles,
  3758. textAlign = styles && styles.textAlign,
  3759. x = paddingLeft + padding * (1 - alignFactor),
  3760. y;
  3761. // determin y based on the baseline
  3762. y = baseline ? 0 : baselineOffset;
  3763. // compensate for alignment
  3764. if (defined(width) && (textAlign === 'center' || textAlign === 'right')) {
  3765. x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width);
  3766. }
  3767. // update if anything changed
  3768. if (x !== text.x || y !== text.y) {
  3769. text.attr({
  3770. x: x,
  3771. y: y
  3772. });
  3773. }
  3774. // record current values
  3775. text.x = x;
  3776. text.y = y;
  3777. }
  3778. /**
  3779. * Set a box attribute, or defer it if the box is not yet created
  3780. * @param {Object} key
  3781. * @param {Object} value
  3782. */
  3783. function boxAttr(key, value) {
  3784. if (box) {
  3785. box.attr(key, value);
  3786. } else {
  3787. deferredAttr[key] = value;
  3788. }
  3789. }
  3790. function getSizeAfterAdd() {
  3791. text.add(wrapper);
  3792. wrapper.attr({
  3793. text: str, // alignment is available now
  3794. x: x,
  3795. y: y
  3796. });
  3797. if (box && defined(anchorX)) {
  3798. wrapper.attr({
  3799. anchorX: anchorX,
  3800. anchorY: anchorY
  3801. });
  3802. }
  3803. }
  3804. /**
  3805. * After the text element is added, get the desired size of the border box
  3806. * and add it before the text in the DOM.
  3807. */
  3808. addEvent(wrapper, 'add', getSizeAfterAdd);
  3809. /*
  3810. * Add specific attribute setters.
  3811. */
  3812. // only change local variables
  3813. attrSetters.width = function (value) {
  3814. width = value;
  3815. return false;
  3816. };
  3817. attrSetters.height = function (value) {
  3818. height = value;
  3819. return false;
  3820. };
  3821. attrSetters.padding = function (value) {
  3822. if (defined(value) && value !== padding) {
  3823. padding = value;
  3824. updateTextPadding();
  3825. }
  3826. return false;
  3827. };
  3828. attrSetters.paddingLeft = function (value) {
  3829. if (defined(value) && value !== paddingLeft) {
  3830. paddingLeft = value;
  3831. updateTextPadding();
  3832. }
  3833. return false;
  3834. };
  3835. // change local variable and set attribue as well
  3836. attrSetters.align = function (value) {
  3837. alignFactor = { left: 0, center: 0.5, right: 1 }[value];
  3838. return false; // prevent setting text-anchor on the group
  3839. };
  3840. // apply these to the box and the text alike
  3841. attrSetters.text = function (value, key) {
  3842. text.attr(key, value);
  3843. updateBoxSize();
  3844. updateTextPadding();
  3845. return false;
  3846. };
  3847. // apply these to the box but not to the text
  3848. attrSetters[STROKE_WIDTH] = function (value, key) {
  3849. needsBox = true;
  3850. crispAdjust = value % 2 / 2;
  3851. boxAttr(key, value);
  3852. return false;
  3853. };
  3854. attrSetters.stroke = attrSetters.fill = attrSetters.r = function (value, key) {
  3855. if (key === 'fill') {
  3856. needsBox = true;
  3857. }
  3858. boxAttr(key, value);
  3859. return false;
  3860. };
  3861. attrSetters.anchorX = function (value, key) {
  3862. anchorX = value;
  3863. boxAttr(key, value + crispAdjust - wrapperX);
  3864. return false;
  3865. };
  3866. attrSetters.anchorY = function (value, key) {
  3867. anchorY = value;
  3868. boxAttr(key, value - wrapperY);
  3869. return false;
  3870. };
  3871. // rename attributes
  3872. attrSetters.x = function (value) {
  3873. wrapper.x = value; // for animation getter
  3874. value -= alignFactor * ((width || bBox.width) + padding);
  3875. wrapperX = mathRound(value);
  3876. wrapper.attr('translateX', wrapperX);
  3877. return false;
  3878. };
  3879. attrSetters.y = function (value) {
  3880. wrapperY = wrapper.y = mathRound(value);
  3881. wrapper.attr('translateY', wrapperY);
  3882. return false;
  3883. };
  3884. // Redirect certain methods to either the box or the text
  3885. var baseCss = wrapper.css;
  3886. return extend(wrapper, {
  3887. /**
  3888. * Pick up some properties and apply them to the text instead of the wrapper
  3889. */
  3890. css: function (styles) {
  3891. if (styles) {
  3892. var textStyles = {};
  3893. styles = merge(styles); // create a copy to avoid altering the original object (#537)
  3894. each(['fontSize', 'fontWeight', 'fontFamily', 'color', 'lineHeight', 'width', 'textDecoration', 'textShadow'], function (prop) {
  3895. if (styles[prop] !== UNDEFINED) {
  3896. textStyles[prop] = styles[prop];
  3897. delete styles[prop];
  3898. }
  3899. });
  3900. text.css(textStyles);
  3901. }
  3902. return baseCss.call(wrapper, styles);
  3903. },
  3904. /**
  3905. * Return the bounding box of the box, not the group
  3906. */
  3907. getBBox: function () {
  3908. return {
  3909. width: bBox.width + 2 * padding,
  3910. height: bBox.height + 2 * padding,
  3911. x: bBox.x - padding,
  3912. y: bBox.y - padding
  3913. };
  3914. },
  3915. /**
  3916. * Apply the shadow to the box
  3917. */
  3918. shadow: function (b) {
  3919. if (box) {
  3920. box.shadow(b);
  3921. }
  3922. return wrapper;
  3923. },
  3924. /**
  3925. * Destroy and release memory.
  3926. */
  3927. destroy: function () {
  3928. removeEvent(wrapper, 'add', getSizeAfterAdd);
  3929. // Added by button implementation
  3930. removeEvent(wrapper.element, 'mouseenter');
  3931. removeEvent(wrapper.element, 'mouseleave');
  3932. if (text) {
  3933. text = text.destroy();
  3934. }
  3935. if (box) {
  3936. box = box.destroy();
  3937. }
  3938. // Call base implementation to destroy the rest
  3939. SVGElement.prototype.destroy.call(wrapper);
  3940. // Release local pointers (#1298)
  3941. wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = getSizeAfterAdd = null;
  3942. }
  3943. });
  3944. }
  3945. }; // end SVGRenderer
  3946. // general renderer
  3947. Renderer = SVGRenderer;
  3948. /* ****************************************************************************
  3949. * *
  3950. * START OF INTERNET EXPLORER <= 8 SPECIFIC CODE *
  3951. * *
  3952. * For applications and websites that don't need IE support, like platform *
  3953. * targeted mobile apps and web apps, this code can be removed. *
  3954. * *
  3955. *****************************************************************************/
  3956. /**
  3957. * @constructor
  3958. */
  3959. var VMLRenderer, VMLElement;
  3960. if (!hasSVG && !useCanVG) {
  3961. /**
  3962. * The VML element wrapper.
  3963. */
  3964. Highcharts.VMLElement = VMLElement = {
  3965. /**
  3966. * Initialize a new VML element wrapper. It builds the markup as a string
  3967. * to minimize DOM traffic.
  3968. * @param {Object} renderer
  3969. * @param {Object} nodeName
  3970. */
  3971. init: function (renderer, nodeName) {
  3972. var wrapper = this,
  3973. markup = ['<', nodeName, ' filled="f" stroked="f"'],
  3974. style = ['position: ', ABSOLUTE, ';'],
  3975. isDiv = nodeName === DIV;
  3976. // divs and shapes need size
  3977. if (nodeName === 'shape' || isDiv) {
  3978. style.push('left:0;top:0;width:1px;height:1px;');
  3979. }
  3980. style.push('visibility: ', isDiv ? HIDDEN : VISIBLE);
  3981. markup.push(' style="', style.join(''), '"/>');
  3982. // create element with default attributes and style
  3983. if (nodeName) {
  3984. markup = isDiv || nodeName === 'span' || nodeName === 'img' ?
  3985. markup.join('')
  3986. : renderer.prepVML(markup);
  3987. wrapper.element = createElement(markup);
  3988. }
  3989. wrapper.renderer = renderer;
  3990. wrapper.attrSetters = {};
  3991. },
  3992. /**
  3993. * Add the node to the given parent
  3994. * @param {Object} parent
  3995. */
  3996. add: function (parent) {
  3997. var wrapper = this,
  3998. renderer = wrapper.renderer,
  3999. element = wrapper.element,
  4000. box = renderer.box,
  4001. inverted = parent && parent.inverted,
  4002. // get the parent node
  4003. parentNode = parent ?
  4004. parent.element || parent :
  4005. box;
  4006. // if the parent group is inverted, apply inversion on all children
  4007. if (inverted) { // only on groups
  4008. renderer.invertChild(element, parentNode);
  4009. }
  4010. // append it
  4011. parentNode.appendChild(element);
  4012. // align text after adding to be able to read offset
  4013. wrapper.added = true;
  4014. if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) {
  4015. wrapper.updateTransform();
  4016. }
  4017. // fire an event for internal hooks
  4018. fireEvent(wrapper, 'add');
  4019. return wrapper;
  4020. },
  4021. /**
  4022. * VML always uses htmlUpdateTransform
  4023. */
  4024. updateTransform: SVGElement.prototype.htmlUpdateTransform,
  4025. /**
  4026. * Set the rotation of a span with oldIE's filter
  4027. */
  4028. setSpanRotation: function (rotation, sintheta, costheta) {
  4029. // Adjust for alignment and rotation. Rotation of useHTML content is not yet implemented
  4030. // but it can probably be implemented for Firefox 3.5+ on user request. FF3.5+
  4031. // has support for CSS3 transform. The getBBox method also needs to be updated
  4032. // to compensate for the rotation, like it currently does for SVG.
  4033. // Test case: http://highcharts.com/tests/?file=text-rotation
  4034. css(this.element, {
  4035. filter: rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta,
  4036. ', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta,
  4037. ', sizingMethod=\'auto expand\')'].join('') : NONE
  4038. });
  4039. },
  4040. /**
  4041. * Converts a subset of an SVG path definition to its VML counterpart. Takes an array
  4042. * as the parameter and returns a string.
  4043. */
  4044. pathToVML: function (value) {
  4045. // convert paths
  4046. var i = value.length,
  4047. path = [],
  4048. clockwise;
  4049. while (i--) {
  4050. // Multiply by 10 to allow subpixel precision.
  4051. // Substracting half a pixel seems to make the coordinates
  4052. // align with SVG, but this hasn't been tested thoroughly
  4053. if (isNumber(value[i])) {
  4054. path[i] = mathRound(value[i] * 10) - 5;
  4055. } else if (value[i] === 'Z') { // close the path
  4056. path[i] = 'x';
  4057. } else {
  4058. path[i] = value[i];
  4059. // When the start X and end X coordinates of an arc are too close,
  4060. // they are rounded to the same value above. In this case, substract 1 from the end X
  4061. // position. #760, #1371.
  4062. if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) {
  4063. clockwise = value[i] === 'wa' ? 1 : -1; // #1642
  4064. if (path[i + 5] === path[i + 7]) {
  4065. path[i + 7] -= clockwise;
  4066. }
  4067. // Start and end Y (#1410)
  4068. if (path[i + 6] === path[i + 8]) {
  4069. path[i + 8] -= clockwise;
  4070. }
  4071. }
  4072. }
  4073. }
  4074. // Loop up again to handle path shortcuts (#2132)
  4075. /*while (i++ < path.length) {
  4076. if (path[i] === 'H') { // horizontal line to
  4077. path[i] = 'L';
  4078. path.splice(i + 2, 0, path[i - 1]);
  4079. } else if (path[i] === 'V') { // vertical line to
  4080. path[i] = 'L';
  4081. path.splice(i + 1, 0, path[i - 2]);
  4082. }
  4083. }*/
  4084. return path.join(' ') || 'x';
  4085. },
  4086. /**
  4087. * Get or set attributes
  4088. */
  4089. attr: function (hash, val) {
  4090. var wrapper = this,
  4091. key,
  4092. value,
  4093. i,
  4094. result,
  4095. element = wrapper.element || {},
  4096. elemStyle = element.style,
  4097. nodeName = element.nodeName,
  4098. renderer = wrapper.renderer,
  4099. symbolName = wrapper.symbolName,
  4100. hasSetSymbolSize,
  4101. shadows = wrapper.shadows,
  4102. skipAttr,
  4103. attrSetters = wrapper.attrSetters,
  4104. ret = wrapper;
  4105. // single key-value pair
  4106. if (isString(hash) && defined(val)) {
  4107. key = hash;
  4108. hash = {};
  4109. hash[key] = val;
  4110. }
  4111. // used as a getter, val is undefined
  4112. if (isString(hash)) {
  4113. key = hash;
  4114. if (key === 'strokeWidth' || key === 'stroke-width') {
  4115. ret = wrapper.strokeweight;
  4116. } else {
  4117. ret = wrapper[key];
  4118. }
  4119. // setter
  4120. } else {
  4121. for (key in hash) {
  4122. value = hash[key];
  4123. skipAttr = false;
  4124. // check for a specific attribute setter
  4125. result = attrSetters[key] && attrSetters[key].call(wrapper, value, key);
  4126. if (result !== false && value !== null) { // #620
  4127. if (result !== UNDEFINED) {
  4128. value = result; // the attribute setter has returned a new value to set
  4129. }
  4130. // prepare paths
  4131. // symbols
  4132. if (symbolName && /^(x|y|r|start|end|width|height|innerR|anchorX|anchorY)/.test(key)) {
  4133. // if one of the symbol size affecting parameters are changed,
  4134. // check all the others only once for each call to an element's
  4135. // .attr() method
  4136. if (!hasSetSymbolSize) {
  4137. wrapper.symbolAttr(hash);
  4138. hasSetSymbolSize = true;
  4139. }
  4140. skipAttr = true;
  4141. } else if (key === 'd') {
  4142. value = value || [];
  4143. wrapper.d = value.join(' '); // used in getter for animation
  4144. element.path = value = wrapper.pathToVML(value);
  4145. // update shadows
  4146. if (shadows) {
  4147. i = shadows.length;
  4148. while (i--) {
  4149. shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value;
  4150. }
  4151. }
  4152. skipAttr = true;
  4153. // handle visibility
  4154. } else if (key === 'visibility') {
  4155. // let the shadow follow the main element
  4156. if (shadows) {
  4157. i = shadows.length;
  4158. while (i--) {
  4159. shadows[i].style[key] = value;
  4160. }
  4161. }
  4162. // Instead of toggling the visibility CSS property, move the div out of the viewport.
  4163. // This works around #61 and #586
  4164. if (nodeName === 'DIV') {
  4165. value = value === HIDDEN ? '-999em' : 0;
  4166. // In order to redraw, IE7 needs the div to be visible when tucked away
  4167. // outside the viewport. So the visibility is actually opposite of
  4168. // the expected value. This applies to the tooltip only.
  4169. if (!docMode8) {
  4170. elemStyle[key] = value ? VISIBLE : HIDDEN;
  4171. }
  4172. key = 'top';
  4173. }
  4174. elemStyle[key] = value;
  4175. skipAttr = true;
  4176. // directly mapped to css
  4177. } else if (key === 'zIndex') {
  4178. if (value) {
  4179. elemStyle[key] = value;
  4180. }
  4181. skipAttr = true;
  4182. // x, y, width, height
  4183. } else if (inArray(key, ['x', 'y', 'width', 'height']) !== -1) {
  4184. wrapper[key] = value; // used in getter
  4185. if (key === 'x' || key === 'y') {
  4186. key = { x: 'left', y: 'top' }[key];
  4187. } else {
  4188. value = mathMax(0, value); // don't set width or height below zero (#311)
  4189. }
  4190. // clipping rectangle special
  4191. if (wrapper.updateClipping) {
  4192. wrapper[key] = value; // the key is now 'left' or 'top' for 'x' and 'y'
  4193. wrapper.updateClipping();
  4194. } else {
  4195. // normal
  4196. elemStyle[key] = value;
  4197. }
  4198. skipAttr = true;
  4199. // class name
  4200. } else if (key === 'class' && nodeName === 'DIV') {
  4201. // IE8 Standards mode has problems retrieving the className
  4202. element.className = value;
  4203. // stroke
  4204. } else if (key === 'stroke') {
  4205. value = renderer.color(value, element, key);
  4206. key = 'strokecolor';
  4207. // stroke width
  4208. } else if (key === 'stroke-width' || key === 'strokeWidth') {
  4209. element.stroked = value ? true : false;
  4210. key = 'strokeweight';
  4211. wrapper[key] = value; // used in getter, issue #113
  4212. if (isNumber(value)) {
  4213. value += PX;
  4214. }
  4215. // dashStyle
  4216. } else if (key === 'dashstyle') {
  4217. var strokeElem = element.getElementsByTagName('stroke')[0] ||
  4218. createElement(renderer.prepVML(['<stroke/>']), null, null, element);
  4219. strokeElem[key] = value || 'solid';
  4220. wrapper.dashstyle = value; /* because changing stroke-width will change the dash length
  4221. and cause an epileptic effect */
  4222. skipAttr = true;
  4223. // fill
  4224. } else if (key === 'fill') {
  4225. if (nodeName === 'SPAN') { // text color
  4226. elemStyle.color = value;
  4227. } else if (nodeName !== 'IMG') { // #1336
  4228. element.filled = value !== NONE ? true : false;
  4229. value = renderer.color(value, element, key, wrapper);
  4230. key = 'fillcolor';
  4231. }
  4232. // opacity: don't bother - animation is too slow and filters introduce artifacts
  4233. } else if (key === 'opacity') {
  4234. /*css(element, {
  4235. opacity: value
  4236. });*/
  4237. skipAttr = true;
  4238. // rotation on VML elements
  4239. } else if (nodeName === 'shape' && key === 'rotation') {
  4240. wrapper[key] = element.style[key] = value; // style is for #1873
  4241. // Correction for the 1x1 size of the shape container. Used in gauge needles.
  4242. element.style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX;
  4243. element.style.top = mathRound(mathCos(value * deg2rad)) + PX;
  4244. // translation for animation
  4245. } else if (key === 'translateX' || key === 'translateY' || key === 'rotation') {
  4246. wrapper[key] = value;
  4247. wrapper.updateTransform();
  4248. skipAttr = true;
  4249. // text for rotated and non-rotated elements
  4250. } else if (key === 'text') {
  4251. this.bBox = null;
  4252. element.innerHTML = value;
  4253. skipAttr = true;
  4254. }
  4255. if (!skipAttr) {
  4256. if (docMode8) { // IE8 setAttribute bug
  4257. element[key] = value;
  4258. } else {
  4259. attr(element, key, value);
  4260. }
  4261. }
  4262. }
  4263. }
  4264. }
  4265. return ret;
  4266. },
  4267. /**
  4268. * Set the element's clipping to a predefined rectangle
  4269. *
  4270. * @param {String} id The id of the clip rectangle
  4271. */
  4272. clip: function (clipRect) {
  4273. var wrapper = this,
  4274. clipMembers,
  4275. cssRet;
  4276. if (clipRect) {
  4277. clipMembers = clipRect.members;
  4278. erase(clipMembers, wrapper); // Ensure unique list of elements (#1258)
  4279. clipMembers.push(wrapper);
  4280. wrapper.destroyClip = function () {
  4281. erase(clipMembers, wrapper);
  4282. };
  4283. cssRet = clipRect.getCSS(wrapper);
  4284. } else {
  4285. if (wrapper.destroyClip) {
  4286. wrapper.destroyClip();
  4287. }
  4288. cssRet = { clip: docMode8 ? 'inherit' : 'rect(auto)' }; // #1214
  4289. }
  4290. return wrapper.css(cssRet);
  4291. },
  4292. /**
  4293. * Set styles for the element
  4294. * @param {Object} styles
  4295. */
  4296. css: SVGElement.prototype.htmlCss,
  4297. /**
  4298. * Removes a child either by removeChild or move to garbageBin.
  4299. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not.
  4300. */
  4301. safeRemoveChild: function (element) {
  4302. // discardElement will detach the node from its parent before attaching it
  4303. // to the garbage bin. Therefore it is important that the node is attached and have parent.
  4304. if (element.parentNode) {
  4305. discardElement(element);
  4306. }
  4307. },
  4308. /**
  4309. * Extend element.destroy by removing it from the clip members array
  4310. */
  4311. destroy: function () {
  4312. if (this.destroyClip) {
  4313. this.destroyClip();
  4314. }
  4315. return SVGElement.prototype.destroy.apply(this);
  4316. },
  4317. /**
  4318. * Add an event listener. VML override for normalizing event parameters.
  4319. * @param {String} eventType
  4320. * @param {Function} handler
  4321. */
  4322. on: function (eventType, handler) {
  4323. // simplest possible event model for internal use
  4324. this.element['on' + eventType] = function () {
  4325. var evt = win.event;
  4326. evt.target = evt.srcElement;
  4327. handler(evt);
  4328. };
  4329. return this;
  4330. },
  4331. /**
  4332. * In stacked columns, cut off the shadows so that they don't overlap
  4333. */
  4334. cutOffPath: function (path, length) {
  4335. var len;
  4336. path = path.split(/[ ,]/);
  4337. len = path.length;
  4338. if (len === 9 || len === 11) {
  4339. path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length;
  4340. }
  4341. return path.join(' ');
  4342. },
  4343. /**
  4344. * Apply a drop shadow by copying elements and giving them different strokes
  4345. * @param {Boolean|Object} shadowOptions
  4346. */
  4347. shadow: function (shadowOptions, group, cutOff) {
  4348. var shadows = [],
  4349. i,
  4350. element = this.element,
  4351. renderer = this.renderer,
  4352. shadow,
  4353. elemStyle = element.style,
  4354. markup,
  4355. path = element.path,
  4356. strokeWidth,
  4357. modifiedPath,
  4358. shadowWidth,
  4359. shadowElementOpacity;
  4360. // some times empty paths are not strings
  4361. if (path && typeof path.value !== 'string') {
  4362. path = 'x';
  4363. }
  4364. modifiedPath = path;
  4365. if (shadowOptions) {
  4366. shadowWidth = pick(shadowOptions.width, 3);
  4367. shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth;
  4368. for (i = 1; i <= 3; i++) {
  4369. strokeWidth = (shadowWidth * 2) + 1 - (2 * i);
  4370. // Cut off shadows for stacked column items
  4371. if (cutOff) {
  4372. modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5);
  4373. }
  4374. markup = ['<shape isShadow="true" strokeweight="', strokeWidth,
  4375. '" filled="false" path="', modifiedPath,
  4376. '" coordsize="10 10" style="', element.style.cssText, '" />'];
  4377. shadow = createElement(renderer.prepVML(markup),
  4378. null, {
  4379. left: pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1),
  4380. top: pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1)
  4381. }
  4382. );
  4383. if (cutOff) {
  4384. shadow.cutOff = strokeWidth + 1;
  4385. }
  4386. // apply the opacity
  4387. markup = ['<stroke color="', shadowOptions.color || 'black', '" opacity="', shadowElementOpacity * i, '"/>'];
  4388. createElement(renderer.prepVML(markup), null, null, shadow);
  4389. // insert it
  4390. if (group) {
  4391. group.element.appendChild(shadow);
  4392. } else {
  4393. element.parentNode.insertBefore(shadow, element);
  4394. }
  4395. // record it
  4396. shadows.push(shadow);
  4397. }
  4398. this.shadows = shadows;
  4399. }
  4400. return this;
  4401. }
  4402. };
  4403. VMLElement = extendClass(SVGElement, VMLElement);
  4404. /**
  4405. * The VML renderer
  4406. */
  4407. var VMLRendererExtension = { // inherit SVGRenderer
  4408. Element: VMLElement,
  4409. isIE8: userAgent.indexOf('MSIE 8.0') > -1,
  4410. /**
  4411. * Initialize the VMLRenderer
  4412. * @param {Object} container
  4413. * @param {Number} width
  4414. * @param {Number} height
  4415. */
  4416. init: function (container, width, height) {
  4417. var renderer = this,
  4418. boxWrapper,
  4419. box;
  4420. renderer.alignedObjects = [];
  4421. boxWrapper = renderer.createElement(DIV);
  4422. box = boxWrapper.element;
  4423. box.style.position = RELATIVE; // for freeform drawing using renderer directly
  4424. container.appendChild(boxWrapper.element);
  4425. // generate the containing box
  4426. renderer.isVML = true;
  4427. renderer.box = box;
  4428. renderer.boxWrapper = boxWrapper;
  4429. renderer.setSize(width, height, false);
  4430. // The only way to make IE6 and IE7 print is to use a global namespace. However,
  4431. // with IE8 the only way to make the dynamic shapes visible in screen and print mode
  4432. // seems to be to add the xmlns attribute and the behaviour style inline.
  4433. if (!doc.namespaces.hcv) {
  4434. doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml');
  4435. // Setup default CSS (#2153)
  4436. (doc.styleSheets.length ? doc.styleSheets[0] : doc.createStyleSheet()).cssText +=
  4437. 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' +
  4438. '{ behavior:url(#default#VML); display: inline-block; } ';
  4439. }
  4440. },
  4441. /**
  4442. * Detect whether the renderer is hidden. This happens when one of the parent elements
  4443. * has display: none
  4444. */
  4445. isHidden: function () {
  4446. return !this.box.offsetWidth;
  4447. },
  4448. /**
  4449. * Define a clipping rectangle. In VML it is accomplished by storing the values
  4450. * for setting the CSS style to all associated members.
  4451. *
  4452. * @param {Number} x
  4453. * @param {Number} y
  4454. * @param {Number} width
  4455. * @param {Number} height
  4456. */
  4457. clipRect: function (x, y, width, height) {
  4458. // create a dummy element
  4459. var clipRect = this.createElement(),
  4460. isObj = isObject(x);
  4461. // mimic a rectangle with its style object for automatic updating in attr
  4462. return extend(clipRect, {
  4463. members: [],
  4464. left: (isObj ? x.x : x) + 1,
  4465. top: (isObj ? x.y : y) + 1,
  4466. width: (isObj ? x.width : width) - 1,
  4467. height: (isObj ? x.height : height) - 1,
  4468. getCSS: function (wrapper) {
  4469. var element = wrapper.element,
  4470. nodeName = element.nodeName,
  4471. isShape = nodeName === 'shape',
  4472. inverted = wrapper.inverted,
  4473. rect = this,
  4474. top = rect.top - (isShape ? element.offsetTop : 0),
  4475. left = rect.left,
  4476. right = left + rect.width,
  4477. bottom = top + rect.height,
  4478. ret = {
  4479. clip: 'rect(' +
  4480. mathRound(inverted ? left : top) + 'px,' +
  4481. mathRound(inverted ? bottom : right) + 'px,' +
  4482. mathRound(inverted ? right : bottom) + 'px,' +
  4483. mathRound(inverted ? top : left) + 'px)'
  4484. };
  4485. // issue 74 workaround
  4486. if (!inverted && docMode8 && nodeName === 'DIV') {
  4487. extend(ret, {
  4488. width: right + PX,
  4489. height: bottom + PX
  4490. });
  4491. }
  4492. return ret;
  4493. },
  4494. // used in attr and animation to update the clipping of all members
  4495. updateClipping: function () {
  4496. each(clipRect.members, function (member) {
  4497. member.css(clipRect.getCSS(member));
  4498. });
  4499. }
  4500. });
  4501. },
  4502. /**
  4503. * Take a color and return it if it's a string, make it a gradient if it's a
  4504. * gradient configuration object, and apply opacity.
  4505. *
  4506. * @param {Object} color The color or config object
  4507. */
  4508. color: function (color, elem, prop, wrapper) {
  4509. var renderer = this,
  4510. colorObject,
  4511. regexRgba = /^rgba/,
  4512. markup,
  4513. fillType,
  4514. ret = NONE;
  4515. // Check for linear or radial gradient
  4516. if (color && color.linearGradient) {
  4517. fillType = 'gradient';
  4518. } else if (color && color.radialGradient) {
  4519. fillType = 'pattern';
  4520. }
  4521. if (fillType) {
  4522. var stopColor,
  4523. stopOpacity,
  4524. gradient = color.linearGradient || color.radialGradient,
  4525. x1,
  4526. y1,
  4527. x2,
  4528. y2,
  4529. opacity1,
  4530. opacity2,
  4531. color1,
  4532. color2,
  4533. fillAttr = '',
  4534. stops = color.stops,
  4535. firstStop,
  4536. lastStop,
  4537. colors = [],
  4538. addFillNode = function () {
  4539. // Add the fill subnode. When colors attribute is used, the meanings of opacity and o:opacity2
  4540. // are reversed.
  4541. markup = ['<fill colors="' + colors.join(',') + '" opacity="', opacity2, '" o:opacity2="', opacity1,
  4542. '" type="', fillType, '" ', fillAttr, 'focus="100%" method="any" />'];
  4543. createElement(renderer.prepVML(markup), null, null, elem);
  4544. };
  4545. // Extend from 0 to 1
  4546. firstStop = stops[0];
  4547. lastStop = stops[stops.length - 1];
  4548. if (firstStop[0] > 0) {
  4549. stops.unshift([
  4550. 0,
  4551. firstStop[1]
  4552. ]);
  4553. }
  4554. if (lastStop[0] < 1) {
  4555. stops.push([
  4556. 1,
  4557. lastStop[1]
  4558. ]);
  4559. }
  4560. // Compute the stops
  4561. each(stops, function (stop, i) {
  4562. if (regexRgba.test(stop[1])) {
  4563. colorObject = Color(stop[1]);
  4564. stopColor = colorObject.get('rgb');
  4565. stopOpacity = colorObject.get('a');
  4566. } else {
  4567. stopColor = stop[1];
  4568. stopOpacity = 1;
  4569. }
  4570. // Build the color attribute
  4571. colors.push((stop[0] * 100) + '% ' + stopColor);
  4572. // Only start and end opacities are allowed, so we use the first and the last
  4573. if (!i) {
  4574. opacity1 = stopOpacity;
  4575. color2 = stopColor;
  4576. } else {
  4577. opacity2 = stopOpacity;
  4578. color1 = stopColor;
  4579. }
  4580. });
  4581. // Apply the gradient to fills only.
  4582. if (prop === 'fill') {
  4583. // Handle linear gradient angle
  4584. if (fillType === 'gradient') {
  4585. x1 = gradient.x1 || gradient[0] || 0;
  4586. y1 = gradient.y1 || gradient[1] || 0;
  4587. x2 = gradient.x2 || gradient[2] || 0;
  4588. y2 = gradient.y2 || gradient[3] || 0;
  4589. fillAttr = 'angle="' + (90 - math.atan(
  4590. (y2 - y1) / // y vector
  4591. (x2 - x1) // x vector
  4592. ) * 180 / mathPI) + '"';
  4593. addFillNode();
  4594. // Radial (circular) gradient
  4595. } else {
  4596. var r = gradient.r,
  4597. sizex = r * 2,
  4598. sizey = r * 2,
  4599. cx = gradient.cx,
  4600. cy = gradient.cy,
  4601. radialReference = elem.radialReference,
  4602. bBox,
  4603. applyRadialGradient = function () {
  4604. if (radialReference) {
  4605. bBox = wrapper.getBBox();
  4606. cx += (radialReference[0] - bBox.x) / bBox.width - 0.5;
  4607. cy += (radialReference[1] - bBox.y) / bBox.height - 0.5;
  4608. sizex *= radialReference[2] / bBox.width;
  4609. sizey *= radialReference[2] / bBox.height;
  4610. }
  4611. fillAttr = 'src="' + defaultOptions.global.VMLRadialGradientURL + '" ' +
  4612. 'size="' + sizex + ',' + sizey + '" ' +
  4613. 'origin="0.5,0.5" ' +
  4614. 'position="' + cx + ',' + cy + '" ' +
  4615. 'color2="' + color2 + '" ';
  4616. addFillNode();
  4617. };
  4618. // Apply radial gradient
  4619. if (wrapper.added) {
  4620. applyRadialGradient();
  4621. } else {
  4622. // We need to know the bounding box to get the size and position right
  4623. addEvent(wrapper, 'add', applyRadialGradient);
  4624. }
  4625. // The fill element's color attribute is broken in IE8 standards mode, so we
  4626. // need to set the parent shape's fillcolor attribute instead.
  4627. ret = color1;
  4628. }
  4629. // Gradients are not supported for VML stroke, return the first color. #722.
  4630. } else {
  4631. ret = stopColor;
  4632. }
  4633. // if the color is an rgba color, split it and add a fill node
  4634. // to hold the opacity component
  4635. } else if (regexRgba.test(color) && elem.tagName !== 'IMG') {
  4636. colorObject = Color(color);
  4637. markup = ['<', prop, ' opacity="', colorObject.get('a'), '"/>'];
  4638. createElement(this.prepVML(markup), null, null, elem);
  4639. ret = colorObject.get('rgb');
  4640. } else {
  4641. var propNodes = elem.getElementsByTagName(prop); // 'stroke' or 'fill' node
  4642. if (propNodes.length) {
  4643. propNodes[0].opacity = 1;
  4644. propNodes[0].type = 'solid';
  4645. }
  4646. ret = color;
  4647. }
  4648. return ret;
  4649. },
  4650. /**
  4651. * Take a VML string and prepare it for either IE8 or IE6/IE7.
  4652. * @param {Array} markup A string array of the VML markup to prepare
  4653. */
  4654. prepVML: function (markup) {
  4655. var vmlStyle = 'display:inline-block;behavior:url(#default#VML);',
  4656. isIE8 = this.isIE8;
  4657. markup = markup.join('');
  4658. if (isIE8) { // add xmlns and style inline
  4659. markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />');
  4660. if (markup.indexOf('style="') === -1) {
  4661. markup = markup.replace('/>', ' style="' + vmlStyle + '" />');
  4662. } else {
  4663. markup = markup.replace('style="', 'style="' + vmlStyle);
  4664. }
  4665. } else { // add namespace
  4666. markup = markup.replace('<', '<hcv:');
  4667. }
  4668. return markup;
  4669. },
  4670. /**
  4671. * Create rotated and aligned text
  4672. * @param {String} str
  4673. * @param {Number} x
  4674. * @param {Number} y
  4675. */
  4676. text: SVGRenderer.prototype.html,
  4677. /**
  4678. * Create and return a path element
  4679. * @param {Array} path
  4680. */
  4681. path: function (path) {
  4682. var attr = {
  4683. // subpixel precision down to 0.1 (width and height = 1px)
  4684. coordsize: '10 10'
  4685. };
  4686. if (isArray(path)) {
  4687. attr.d = path;
  4688. } else if (isObject(path)) { // attributes
  4689. extend(attr, path);
  4690. }
  4691. // create the shape
  4692. return this.createElement('shape').attr(attr);
  4693. },
  4694. /**
  4695. * Create and return a circle element. In VML circles are implemented as
  4696. * shapes, which is faster than v:oval
  4697. * @param {Number} x
  4698. * @param {Number} y
  4699. * @param {Number} r
  4700. */
  4701. circle: function (x, y, r) {
  4702. var circle = this.symbol('circle');
  4703. if (isObject(x)) {
  4704. r = x.r;
  4705. y = x.y;
  4706. x = x.x;
  4707. }
  4708. circle.isCircle = true; // Causes x and y to mean center (#1682)
  4709. circle.r = r;
  4710. return circle.attr({ x: x, y: y });
  4711. },
  4712. /**
  4713. * Create a group using an outer div and an inner v:group to allow rotating
  4714. * and flipping. A simple v:group would have problems with positioning
  4715. * child HTML elements and CSS clip.
  4716. *
  4717. * @param {String} name The name of the group
  4718. */
  4719. g: function (name) {
  4720. var wrapper,
  4721. attribs;
  4722. // set the class name
  4723. if (name) {
  4724. attribs = { 'className': PREFIX + name, 'class': PREFIX + name };
  4725. }
  4726. // the div to hold HTML and clipping
  4727. wrapper = this.createElement(DIV).attr(attribs);
  4728. return wrapper;
  4729. },
  4730. /**
  4731. * VML override to create a regular HTML image
  4732. * @param {String} src
  4733. * @param {Number} x
  4734. * @param {Number} y
  4735. * @param {Number} width
  4736. * @param {Number} height
  4737. */
  4738. image: function (src, x, y, width, height) {
  4739. var obj = this.createElement('img')
  4740. .attr({ src: src });
  4741. if (arguments.length > 1) {
  4742. obj.attr({
  4743. x: x,
  4744. y: y,
  4745. width: width,
  4746. height: height
  4747. });
  4748. }
  4749. return obj;
  4750. },
  4751. /**
  4752. * VML uses a shape for rect to overcome bugs and rotation problems
  4753. */
  4754. rect: function (x, y, width, height, r, strokeWidth) {
  4755. var wrapper = this.symbol('rect');
  4756. wrapper.r = isObject(x) ? x.r : r;
  4757. //return wrapper.attr(wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0)));
  4758. return wrapper.attr(
  4759. isObject(x) ?
  4760. x :
  4761. // do not crispify when an object is passed in (as in column charts)
  4762. wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0))
  4763. );
  4764. },
  4765. /**
  4766. * In the VML renderer, each child of an inverted div (group) is inverted
  4767. * @param {Object} element
  4768. * @param {Object} parentNode
  4769. */
  4770. invertChild: function (element, parentNode) {
  4771. var parentStyle = parentNode.style;
  4772. css(element, {
  4773. flip: 'x',
  4774. left: pInt(parentStyle.width) - 1,
  4775. top: pInt(parentStyle.height) - 1,
  4776. rotation: -90
  4777. });
  4778. },
  4779. /**
  4780. * Symbol definitions that override the parent SVG renderer's symbols
  4781. *
  4782. */
  4783. symbols: {
  4784. // VML specific arc function
  4785. arc: function (x, y, w, h, options) {
  4786. var start = options.start,
  4787. end = options.end,
  4788. radius = options.r || w || h,
  4789. innerRadius = options.innerR,
  4790. cosStart = mathCos(start),
  4791. sinStart = mathSin(start),
  4792. cosEnd = mathCos(end),
  4793. sinEnd = mathSin(end),
  4794. ret;
  4795. if (end - start === 0) { // no angle, don't show it.
  4796. return ['x'];
  4797. }
  4798. ret = [
  4799. 'wa', // clockwise arc to
  4800. x - radius, // left
  4801. y - radius, // top
  4802. x + radius, // right
  4803. y + radius, // bottom
  4804. x + radius * cosStart, // start x
  4805. y + radius * sinStart, // start y
  4806. x + radius * cosEnd, // end x
  4807. y + radius * sinEnd // end y
  4808. ];
  4809. if (options.open && !innerRadius) {
  4810. ret.push(
  4811. 'e',
  4812. M,
  4813. x,// - innerRadius,
  4814. y// - innerRadius
  4815. );
  4816. }
  4817. ret.push(
  4818. 'at', // anti clockwise arc to
  4819. x - innerRadius, // left
  4820. y - innerRadius, // top
  4821. x + innerRadius, // right
  4822. y + innerRadius, // bottom
  4823. x + innerRadius * cosEnd, // start x
  4824. y + innerRadius * sinEnd, // start y
  4825. x + innerRadius * cosStart, // end x
  4826. y + innerRadius * sinStart, // end y
  4827. 'x', // finish path
  4828. 'e' // close
  4829. );
  4830. ret.isArc = true;
  4831. return ret;
  4832. },
  4833. // Add circle symbol path. This performs significantly faster than v:oval.
  4834. circle: function (x, y, w, h, wrapper) {
  4835. if (wrapper) {
  4836. w = h = 2 * wrapper.r;
  4837. }
  4838. // Center correction, #1682
  4839. if (wrapper && wrapper.isCircle) {
  4840. x -= w / 2;
  4841. y -= h / 2;
  4842. }
  4843. // Return the path
  4844. return [
  4845. 'wa', // clockwisearcto
  4846. x, // left
  4847. y, // top
  4848. x + w, // right
  4849. y + h, // bottom
  4850. x + w, // start x
  4851. y + h / 2, // start y
  4852. x + w, // end x
  4853. y + h / 2, // end y
  4854. //'x', // finish path
  4855. 'e' // close
  4856. ];
  4857. },
  4858. /**
  4859. * Add rectangle symbol path which eases rotation and omits arcsize problems
  4860. * compared to the built-in VML roundrect shape
  4861. *
  4862. * @param {Number} left Left position
  4863. * @param {Number} top Top position
  4864. * @param {Number} r Border radius
  4865. * @param {Object} options Width and height
  4866. */
  4867. rect: function (left, top, width, height, options) {
  4868. var right = left + width,
  4869. bottom = top + height,
  4870. ret,
  4871. r;
  4872. // No radius, return the more lightweight square
  4873. if (!defined(options) || !options.r) {
  4874. ret = SVGRenderer.prototype.symbols.square.apply(0, arguments);
  4875. // Has radius add arcs for the corners
  4876. } else {
  4877. r = mathMin(options.r, width, height);
  4878. ret = [
  4879. M,
  4880. left + r, top,
  4881. L,
  4882. right - r, top,
  4883. 'wa',
  4884. right - 2 * r, top,
  4885. right, top + 2 * r,
  4886. right - r, top,
  4887. right, top + r,
  4888. L,
  4889. right, bottom - r,
  4890. 'wa',
  4891. right - 2 * r, bottom - 2 * r,
  4892. right, bottom,
  4893. right, bottom - r,
  4894. right - r, bottom,
  4895. L,
  4896. left + r, bottom,
  4897. 'wa',
  4898. left, bottom - 2 * r,
  4899. left + 2 * r, bottom,
  4900. left + r, bottom,
  4901. left, bottom - r,
  4902. L,
  4903. left, top + r,
  4904. 'wa',
  4905. left, top,
  4906. left + 2 * r, top + 2 * r,
  4907. left, top + r,
  4908. left + r, top,
  4909. 'x',
  4910. 'e'
  4911. ];
  4912. }
  4913. return ret;
  4914. }
  4915. }
  4916. };
  4917. Highcharts.VMLRenderer = VMLRenderer = function () {
  4918. this.init.apply(this, arguments);
  4919. };
  4920. VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension);
  4921. // general renderer
  4922. Renderer = VMLRenderer;
  4923. }
  4924. /* ****************************************************************************
  4925. * *
  4926. * END OF INTERNET EXPLORER <= 8 SPECIFIC CODE *
  4927. * *
  4928. *****************************************************************************/
  4929. /* ****************************************************************************
  4930. * *
  4931. * START OF ANDROID < 3 SPECIFIC CODE. THIS CAN BE REMOVED IF YOU'RE NOT *
  4932. * TARGETING THAT SYSTEM. *
  4933. * *
  4934. *****************************************************************************/
  4935. var CanVGRenderer,
  4936. CanVGController;
  4937. if (useCanVG) {
  4938. /**
  4939. * The CanVGRenderer is empty from start to keep the source footprint small.
  4940. * When requested, the CanVGController downloads the rest of the source packaged
  4941. * together with the canvg library.
  4942. */
  4943. Highcharts.CanVGRenderer = CanVGRenderer = function () {
  4944. // Override the global SVG namespace to fake SVG/HTML that accepts CSS
  4945. SVG_NS = 'http://www.w3.org/1999/xhtml';
  4946. };
  4947. /**
  4948. * Start with an empty symbols object. This is needed when exporting is used (exporting.src.js will add a few symbols), but
  4949. * the implementation from SvgRenderer will not be merged in until first render.
  4950. */
  4951. CanVGRenderer.prototype.symbols = {};
  4952. /**
  4953. * Handles on demand download of canvg rendering support.
  4954. */
  4955. CanVGController = (function () {
  4956. // List of renderering calls
  4957. var deferredRenderCalls = [];
  4958. /**
  4959. * When downloaded, we are ready to draw deferred charts.
  4960. */
  4961. function drawDeferred() {
  4962. var callLength = deferredRenderCalls.length,
  4963. callIndex;
  4964. // Draw all pending render calls
  4965. for (callIndex = 0; callIndex < callLength; callIndex++) {
  4966. deferredRenderCalls[callIndex]();
  4967. }
  4968. // Clear the list
  4969. deferredRenderCalls = [];
  4970. }
  4971. return {
  4972. push: function (func, scriptLocation) {
  4973. // Only get the script once
  4974. if (deferredRenderCalls.length === 0) {
  4975. getScript(scriptLocation, drawDeferred);
  4976. }
  4977. // Register render call
  4978. deferredRenderCalls.push(func);
  4979. }
  4980. };
  4981. }());
  4982. Renderer = CanVGRenderer;
  4983. } // end CanVGRenderer
  4984. /* ****************************************************************************
  4985. * *
  4986. * END OF ANDROID < 3 SPECIFIC CODE *
  4987. * *
  4988. *****************************************************************************/
  4989. /**
  4990. * The Tick class
  4991. */
  4992. function Tick(axis, pos, type, noLabel) {
  4993. this.axis = axis;
  4994. this.pos = pos;
  4995. this.type = type || '';
  4996. this.isNew = true;
  4997. if (!type && !noLabel) {
  4998. this.addLabel();
  4999. }
  5000. }
  5001. Tick.prototype = {
  5002. /**
  5003. * Write the tick label
  5004. */
  5005. addLabel: function () {
  5006. var tick = this,
  5007. axis = tick.axis,
  5008. options = axis.options,
  5009. chart = axis.chart,
  5010. horiz = axis.horiz,
  5011. categories = axis.categories,
  5012. names = axis.series[0] && axis.series[0].names,
  5013. pos = tick.pos,
  5014. labelOptions = options.labels,
  5015. str,
  5016. tickPositions = axis.tickPositions,
  5017. width = (horiz && categories &&
  5018. !labelOptions.step && !labelOptions.staggerLines &&
  5019. !labelOptions.rotation &&
  5020. chart.plotWidth / tickPositions.length) ||
  5021. (!horiz && (chart.margin[3] || chart.chartWidth * 0.33)), // #1580, #1931
  5022. isFirst = pos === tickPositions[0],
  5023. isLast = pos === tickPositions[tickPositions.length - 1],
  5024. css,
  5025. attr,
  5026. value = categories ?
  5027. pick(categories[pos], names && names[pos], pos) :
  5028. pos,
  5029. label = tick.label,
  5030. tickPositionInfo = tickPositions.info,
  5031. dateTimeLabelFormat;
  5032. // Set the datetime label format. If a higher rank is set for this position, use that. If not,
  5033. // use the general format.
  5034. if (axis.isDatetimeAxis && tickPositionInfo) {
  5035. dateTimeLabelFormat = options.dateTimeLabelFormats[tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName];
  5036. }
  5037. // set properties for access in render method
  5038. tick.isFirst = isFirst;
  5039. tick.isLast = isLast;
  5040. // get the string
  5041. str = axis.labelFormatter.call({
  5042. axis: axis,
  5043. chart: chart,
  5044. isFirst: isFirst,
  5045. isLast: isLast,
  5046. dateTimeLabelFormat: dateTimeLabelFormat,
  5047. value: axis.isLog ? correctFloat(lin2log(value)) : value
  5048. });
  5049. // prepare CSS
  5050. css = width && { width: mathMax(1, mathRound(width - 2 * (labelOptions.padding || 10))) + PX };
  5051. css = extend(css, labelOptions.style);
  5052. // first call
  5053. if (!defined(label)) {
  5054. attr = {
  5055. align: axis.labelAlign
  5056. };
  5057. if (isNumber(labelOptions.rotation)) {
  5058. attr.rotation = labelOptions.rotation;
  5059. }
  5060. if (width && labelOptions.ellipsis) {
  5061. attr._clipHeight = axis.len / tickPositions.length;
  5062. }
  5063. tick.label =
  5064. defined(str) && labelOptions.enabled ?
  5065. chart.renderer.text(
  5066. str,
  5067. 0,
  5068. 0,
  5069. labelOptions.useHTML
  5070. )
  5071. .attr(attr)
  5072. // without position absolute, IE export sometimes is wrong
  5073. .css(css)
  5074. .add(axis.labelGroup) :
  5075. null;
  5076. // update
  5077. } else if (label) {
  5078. label.attr({
  5079. text: str
  5080. })
  5081. .css(css);
  5082. }
  5083. },
  5084. /**
  5085. * Get the offset height or width of the label
  5086. */
  5087. getLabelSize: function () {
  5088. var label = this.label,
  5089. axis = this.axis;
  5090. return label ?
  5091. ((this.labelBBox = label.getBBox()))[axis.horiz ? 'height' : 'width'] :
  5092. 0;
  5093. },
  5094. /**
  5095. * Find how far the labels extend to the right and left of the tick's x position. Used for anti-collision
  5096. * detection with overflow logic.
  5097. */
  5098. getLabelSides: function () {
  5099. var bBox = this.labelBBox, // assume getLabelSize has run at this point
  5100. axis = this.axis,
  5101. options = axis.options,
  5102. labelOptions = options.labels,
  5103. width = bBox.width,
  5104. leftSide = width * { left: 0, center: 0.5, right: 1 }[axis.labelAlign] - labelOptions.x;
  5105. return [-leftSide, width - leftSide];
  5106. },
  5107. /**
  5108. * Handle the label overflow by adjusting the labels to the left and right edge, or
  5109. * hide them if they collide into the neighbour label.
  5110. */
  5111. handleOverflow: function (index, xy) {
  5112. var show = true,
  5113. axis = this.axis,
  5114. chart = axis.chart,
  5115. isFirst = this.isFirst,
  5116. isLast = this.isLast,
  5117. x = xy.x,
  5118. reversed = axis.reversed,
  5119. tickPositions = axis.tickPositions;
  5120. if (isFirst || isLast) {
  5121. var sides = this.getLabelSides(),
  5122. leftSide = sides[0],
  5123. rightSide = sides[1],
  5124. plotLeft = chart.plotLeft,
  5125. plotRight = plotLeft + axis.len,
  5126. neighbour = axis.ticks[tickPositions[index + (isFirst ? 1 : -1)]],
  5127. neighbourEdge = neighbour && neighbour.label.xy && neighbour.label.xy.x + neighbour.getLabelSides()[isFirst ? 0 : 1];
  5128. if ((isFirst && !reversed) || (isLast && reversed)) {
  5129. // Is the label spilling out to the left of the plot area?
  5130. if (x + leftSide < plotLeft) {
  5131. // Align it to plot left
  5132. x = plotLeft - leftSide;
  5133. // Hide it if it now overlaps the neighbour label
  5134. if (neighbour && x + rightSide > neighbourEdge) {
  5135. show = false;
  5136. }
  5137. }
  5138. } else {
  5139. // Is the label spilling out to the right of the plot area?
  5140. if (x + rightSide > plotRight) {
  5141. // Align it to plot right
  5142. x = plotRight - rightSide;
  5143. // Hide it if it now overlaps the neighbour label
  5144. if (neighbour && x + leftSide < neighbourEdge) {
  5145. show = false;
  5146. }
  5147. }
  5148. }
  5149. // Set the modified x position of the label
  5150. xy.x = x;
  5151. }
  5152. return show;
  5153. },
  5154. /**
  5155. * Get the x and y position for ticks and labels
  5156. */
  5157. getPosition: function (horiz, pos, tickmarkOffset, old) {
  5158. var axis = this.axis,
  5159. chart = axis.chart,
  5160. cHeight = (old && chart.oldChartHeight) || chart.chartHeight;
  5161. return {
  5162. x: horiz ?
  5163. axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB :
  5164. axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0),
  5165. y: horiz ?
  5166. cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) :
  5167. cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB
  5168. };
  5169. },
  5170. /**
  5171. * Get the x, y position of the tick label
  5172. */
  5173. getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) {
  5174. var axis = this.axis,
  5175. transA = axis.transA,
  5176. reversed = axis.reversed,
  5177. staggerLines = axis.staggerLines,
  5178. baseline = axis.chart.renderer.fontMetrics(labelOptions.style.fontSize).b,
  5179. rotation = labelOptions.rotation;
  5180. x = x + labelOptions.x - (tickmarkOffset && horiz ?
  5181. tickmarkOffset * transA * (reversed ? -1 : 1) : 0);
  5182. y = y + labelOptions.y - (tickmarkOffset && !horiz ?
  5183. tickmarkOffset * transA * (reversed ? 1 : -1) : 0);
  5184. // Correct for rotation (#1764)
  5185. if (rotation && axis.side === 2) {
  5186. y -= baseline - baseline * mathCos(rotation * deg2rad);
  5187. }
  5188. // Vertically centered
  5189. if (!defined(labelOptions.y) && !rotation) { // #1951
  5190. y += baseline - label.getBBox().height / 2;
  5191. }
  5192. // Correct for staggered labels
  5193. if (staggerLines) {
  5194. y += (index / (step || 1) % staggerLines) * (axis.labelOffset / staggerLines);
  5195. }
  5196. return {
  5197. x: x,
  5198. y: y
  5199. };
  5200. },
  5201. /**
  5202. * Extendible method to return the path of the marker
  5203. */
  5204. getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) {
  5205. return renderer.crispLine([
  5206. M,
  5207. x,
  5208. y,
  5209. L,
  5210. x + (horiz ? 0 : -tickLength),
  5211. y + (horiz ? tickLength : 0)
  5212. ], tickWidth);
  5213. },
  5214. /**
  5215. * Put everything in place
  5216. *
  5217. * @param index {Number}
  5218. * @param old {Boolean} Use old coordinates to prepare an animation into new position
  5219. */
  5220. render: function (index, old, opacity) {
  5221. var tick = this,
  5222. axis = tick.axis,
  5223. options = axis.options,
  5224. chart = axis.chart,
  5225. renderer = chart.renderer,
  5226. horiz = axis.horiz,
  5227. type = tick.type,
  5228. label = tick.label,
  5229. pos = tick.pos,
  5230. labelOptions = options.labels,
  5231. gridLine = tick.gridLine,
  5232. gridPrefix = type ? type + 'Grid' : 'grid',
  5233. tickPrefix = type ? type + 'Tick' : 'tick',
  5234. gridLineWidth = options[gridPrefix + 'LineWidth'],
  5235. gridLineColor = options[gridPrefix + 'LineColor'],
  5236. dashStyle = options[gridPrefix + 'LineDashStyle'],
  5237. tickLength = options[tickPrefix + 'Length'],
  5238. tickWidth = options[tickPrefix + 'Width'] || 0,
  5239. tickColor = options[tickPrefix + 'Color'],
  5240. tickPosition = options[tickPrefix + 'Position'],
  5241. gridLinePath,
  5242. mark = tick.mark,
  5243. markPath,
  5244. step = labelOptions.step,
  5245. attribs,
  5246. show = true,
  5247. tickmarkOffset = axis.tickmarkOffset,
  5248. xy = tick.getPosition(horiz, pos, tickmarkOffset, old),
  5249. x = xy.x,
  5250. y = xy.y,
  5251. reverseCrisp = ((horiz && x === axis.pos + axis.len) || (!horiz && y === axis.pos)) ? -1 : 1, // #1480, #1687
  5252. staggerLines = axis.staggerLines;
  5253. this.isActive = true;
  5254. // create the grid line
  5255. if (gridLineWidth) {
  5256. gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLineWidth * reverseCrisp, old, true);
  5257. if (gridLine === UNDEFINED) {
  5258. attribs = {
  5259. stroke: gridLineColor,
  5260. 'stroke-width': gridLineWidth
  5261. };
  5262. if (dashStyle) {
  5263. attribs.dashstyle = dashStyle;
  5264. }
  5265. if (!type) {
  5266. attribs.zIndex = 1;
  5267. }
  5268. if (old) {
  5269. attribs.opacity = 0;
  5270. }
  5271. tick.gridLine = gridLine =
  5272. gridLineWidth ?
  5273. renderer.path(gridLinePath)
  5274. .attr(attribs).add(axis.gridGroup) :
  5275. null;
  5276. }
  5277. // If the parameter 'old' is set, the current call will be followed
  5278. // by another call, therefore do not do any animations this time
  5279. if (!old && gridLine && gridLinePath) {
  5280. gridLine[tick.isNew ? 'attr' : 'animate']({
  5281. d: gridLinePath,
  5282. opacity: opacity
  5283. });
  5284. }
  5285. }
  5286. // create the tick mark
  5287. if (tickWidth && tickLength) {
  5288. // negate the length
  5289. if (tickPosition === 'inside') {
  5290. tickLength = -tickLength;
  5291. }
  5292. if (axis.opposite) {
  5293. tickLength = -tickLength;
  5294. }
  5295. markPath = tick.getMarkPath(x, y, tickLength, tickWidth * reverseCrisp, horiz, renderer);
  5296. if (mark) { // updating
  5297. mark.animate({
  5298. d: markPath,
  5299. opacity: opacity
  5300. });
  5301. } else { // first time
  5302. tick.mark = renderer.path(
  5303. markPath
  5304. ).attr({
  5305. stroke: tickColor,
  5306. 'stroke-width': tickWidth,
  5307. opacity: opacity
  5308. }).add(axis.axisGroup);
  5309. }
  5310. }
  5311. // the label is created on init - now move it into place
  5312. if (label && !isNaN(x)) {
  5313. label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step);
  5314. // Apply show first and show last. If the tick is both first and last, it is
  5315. // a single centered tick, in which case we show the label anyway (#2100).
  5316. if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) ||
  5317. (tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) {
  5318. show = false;
  5319. // Handle label overflow and show or hide accordingly
  5320. } else if (!staggerLines && horiz && labelOptions.overflow === 'justify' && !tick.handleOverflow(index, xy)) {
  5321. show = false;
  5322. }
  5323. // apply step
  5324. if (step && index % step) {
  5325. // show those indices dividable by step
  5326. show = false;
  5327. }
  5328. // Set the new position, and show or hide
  5329. if (show && !isNaN(xy.y)) {
  5330. xy.opacity = opacity;
  5331. label[tick.isNew ? 'attr' : 'animate'](xy);
  5332. tick.isNew = false;
  5333. } else {
  5334. label.attr('y', -9999); // #1338
  5335. }
  5336. }
  5337. },
  5338. /**
  5339. * Destructor for the tick prototype
  5340. */
  5341. destroy: function () {
  5342. destroyObjectProperties(this, this.axis);
  5343. }
  5344. };
  5345. /**
  5346. * The object wrapper for plot lines and plot bands
  5347. * @param {Object} options
  5348. */
  5349. function PlotLineOrBand(axis, options) {
  5350. this.axis = axis;
  5351. if (options) {
  5352. this.options = options;
  5353. this.id = options.id;
  5354. }
  5355. }
  5356. PlotLineOrBand.prototype = {
  5357. /**
  5358. * Render the plot line or plot band. If it is already existing,
  5359. * move it.
  5360. */
  5361. render: function () {
  5362. var plotLine = this,
  5363. axis = plotLine.axis,
  5364. horiz = axis.horiz,
  5365. halfPointRange = (axis.pointRange || 0) / 2,
  5366. options = plotLine.options,
  5367. optionsLabel = options.label,
  5368. label = plotLine.label,
  5369. width = options.width,
  5370. to = options.to,
  5371. from = options.from,
  5372. isBand = defined(from) && defined(to),
  5373. value = options.value,
  5374. dashStyle = options.dashStyle,
  5375. svgElem = plotLine.svgElem,
  5376. path = [],
  5377. addEvent,
  5378. eventType,
  5379. xs,
  5380. ys,
  5381. x,
  5382. y,
  5383. color = options.color,
  5384. zIndex = options.zIndex,
  5385. events = options.events,
  5386. attribs,
  5387. renderer = axis.chart.renderer;
  5388. // logarithmic conversion
  5389. if (axis.isLog) {
  5390. from = log2lin(from);
  5391. to = log2lin(to);
  5392. value = log2lin(value);
  5393. }
  5394. // plot line
  5395. if (width) {
  5396. path = axis.getPlotLinePath(value, width);
  5397. attribs = {
  5398. stroke: color,
  5399. 'stroke-width': width
  5400. };
  5401. if (dashStyle) {
  5402. attribs.dashstyle = dashStyle;
  5403. }
  5404. } else if (isBand) { // plot band
  5405. // keep within plot area
  5406. from = mathMax(from, axis.min - halfPointRange);
  5407. to = mathMin(to, axis.max + halfPointRange);
  5408. path = axis.getPlotBandPath(from, to, options);
  5409. attribs = {
  5410. fill: color
  5411. };
  5412. if (options.borderWidth) {
  5413. attribs.stroke = options.borderColor;
  5414. attribs['stroke-width'] = options.borderWidth;
  5415. }
  5416. } else {
  5417. return;
  5418. }
  5419. // zIndex
  5420. if (defined(zIndex)) {
  5421. attribs.zIndex = zIndex;
  5422. }
  5423. // common for lines and bands
  5424. if (svgElem) {
  5425. if (path) {
  5426. svgElem.animate({
  5427. d: path
  5428. }, null, svgElem.onGetPath);
  5429. } else {
  5430. svgElem.hide();
  5431. svgElem.onGetPath = function () {
  5432. svgElem.show();
  5433. };
  5434. }
  5435. } else if (path && path.length) {
  5436. plotLine.svgElem = svgElem = renderer.path(path)
  5437. .attr(attribs).add();
  5438. // events
  5439. if (events) {
  5440. addEvent = function (eventType) {
  5441. svgElem.on(eventType, function (e) {
  5442. events[eventType].apply(plotLine, [e]);
  5443. });
  5444. };
  5445. for (eventType in events) {
  5446. addEvent(eventType);
  5447. }
  5448. }
  5449. }
  5450. // the plot band/line label
  5451. if (optionsLabel && defined(optionsLabel.text) && path && path.length && axis.width > 0 && axis.height > 0) {
  5452. // apply defaults
  5453. optionsLabel = merge({
  5454. align: horiz && isBand && 'center',
  5455. x: horiz ? !isBand && 4 : 10,
  5456. verticalAlign : !horiz && isBand && 'middle',
  5457. y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4,
  5458. rotation: horiz && !isBand && 90
  5459. }, optionsLabel);
  5460. // add the SVG element
  5461. if (!label) {
  5462. plotLine.label = label = renderer.text(
  5463. optionsLabel.text,
  5464. 0,
  5465. 0,
  5466. optionsLabel.useHTML
  5467. )
  5468. .attr({
  5469. align: optionsLabel.textAlign || optionsLabel.align,
  5470. rotation: optionsLabel.rotation,
  5471. zIndex: zIndex
  5472. })
  5473. .css(optionsLabel.style)
  5474. .add();
  5475. }
  5476. // get the bounding box and align the label
  5477. xs = [path[1], path[4], pick(path[6], path[1])];
  5478. ys = [path[2], path[5], pick(path[7], path[2])];
  5479. x = arrayMin(xs);
  5480. y = arrayMin(ys);
  5481. label.align(optionsLabel, false, {
  5482. x: x,
  5483. y: y,
  5484. width: arrayMax(xs) - x,
  5485. height: arrayMax(ys) - y
  5486. });
  5487. label.show();
  5488. } else if (label) { // move out of sight
  5489. label.hide();
  5490. }
  5491. // chainable
  5492. return plotLine;
  5493. },
  5494. /**
  5495. * Remove the plot line or band
  5496. */
  5497. destroy: function () {
  5498. // remove it from the lookup
  5499. erase(this.axis.plotLinesAndBands, this);
  5500. delete this.axis;
  5501. destroyObjectProperties(this);
  5502. }
  5503. };
  5504. /**
  5505. * The class for stack items
  5506. */
  5507. function StackItem(axis, options, isNegative, x, stackOption, stacking) {
  5508. var inverted = axis.chart.inverted;
  5509. this.axis = axis;
  5510. // Tells if the stack is negative
  5511. this.isNegative = isNegative;
  5512. // Save the options to be able to style the label
  5513. this.options = options;
  5514. // Save the x value to be able to position the label later
  5515. this.x = x;
  5516. // Initialize total value
  5517. this.total = null;
  5518. // This will keep each points' extremes stored by series.index
  5519. this.points = {};
  5520. // Save the stack option on the series configuration object, and whether to treat it as percent
  5521. this.stack = stackOption;
  5522. this.percent = stacking === 'percent';
  5523. // The align options and text align varies on whether the stack is negative and
  5524. // if the chart is inverted or not.
  5525. // First test the user supplied value, then use the dynamic.
  5526. this.alignOptions = {
  5527. align: options.align || (inverted ? (isNegative ? 'left' : 'right') : 'center'),
  5528. verticalAlign: options.verticalAlign || (inverted ? 'middle' : (isNegative ? 'bottom' : 'top')),
  5529. y: pick(options.y, inverted ? 4 : (isNegative ? 14 : -6)),
  5530. x: pick(options.x, inverted ? (isNegative ? -6 : 6) : 0)
  5531. };
  5532. this.textAlign = options.textAlign || (inverted ? (isNegative ? 'right' : 'left') : 'center');
  5533. }
  5534. StackItem.prototype = {
  5535. destroy: function () {
  5536. destroyObjectProperties(this, this.axis);
  5537. },
  5538. /**
  5539. * Renders the stack total label and adds it to the stack label group.
  5540. */
  5541. render: function (group) {
  5542. var options = this.options,
  5543. formatOption = options.format,
  5544. str = formatOption ?
  5545. format(formatOption, this) :
  5546. options.formatter.call(this); // format the text in the label
  5547. // Change the text to reflect the new total and set visibility to hidden in case the serie is hidden
  5548. if (this.label) {
  5549. this.label.attr({text: str, visibility: HIDDEN});
  5550. // Create new label
  5551. } else {
  5552. this.label =
  5553. this.axis.chart.renderer.text(str, 0, 0, options.useHTML) // dummy positions, actual position updated with setOffset method in columnseries
  5554. .css(options.style) // apply style
  5555. .attr({
  5556. align: this.textAlign, // fix the text-anchor
  5557. rotation: options.rotation, // rotation
  5558. visibility: HIDDEN // hidden until setOffset is called
  5559. })
  5560. .add(group); // add to the labels-group
  5561. }
  5562. },
  5563. /**
  5564. * Sets the offset that the stack has from the x value and repositions the label.
  5565. */
  5566. setOffset: function (xOffset, xWidth) {
  5567. var stackItem = this,
  5568. axis = stackItem.axis,
  5569. chart = axis.chart,
  5570. inverted = chart.inverted,
  5571. neg = this.isNegative, // special treatment is needed for negative stacks
  5572. y = axis.translate(this.percent ? 100 : this.total, 0, 0, 0, 1), // stack value translated mapped to chart coordinates
  5573. yZero = axis.translate(0), // stack origin
  5574. h = mathAbs(y - yZero), // stack height
  5575. x = chart.xAxis[0].translate(this.x) + xOffset, // stack x position
  5576. plotHeight = chart.plotHeight,
  5577. stackBox = { // this is the box for the complete stack
  5578. x: inverted ? (neg ? y : y - h) : x,
  5579. y: inverted ? plotHeight - x - xWidth : (neg ? (plotHeight - y - h) : plotHeight - y),
  5580. width: inverted ? h : xWidth,
  5581. height: inverted ? xWidth : h
  5582. },
  5583. label = this.label,
  5584. alignAttr;
  5585. if (label) {
  5586. label.align(this.alignOptions, null, stackBox); // align the label to the box
  5587. // Set visibility (#678)
  5588. alignAttr = label.alignAttr;
  5589. label.attr({
  5590. visibility: this.options.crop === false || chart.isInsidePlot(alignAttr.x, alignAttr.y) ?
  5591. (hasSVG ? 'inherit' : VISIBLE) :
  5592. HIDDEN
  5593. });
  5594. }
  5595. }
  5596. };
  5597. /**
  5598. * Create a new axis object
  5599. * @param {Object} chart
  5600. * @param {Object} options
  5601. */
  5602. function Axis() {
  5603. this.init.apply(this, arguments);
  5604. }
  5605. Axis.prototype = {
  5606. /**
  5607. * Default options for the X axis - the Y axis has extended defaults
  5608. */
  5609. defaultOptions: {
  5610. // allowDecimals: null,
  5611. // alternateGridColor: null,
  5612. // categories: [],
  5613. dateTimeLabelFormats: {
  5614. millisecond: '%H:%M:%S.%L',
  5615. second: '%H:%M:%S',
  5616. minute: '%H:%M',
  5617. hour: '%H:%M',
  5618. day: '%e. %b',
  5619. week: '%e. %b',
  5620. month: '%b \'%y',
  5621. year: '%Y'
  5622. },
  5623. endOnTick: false,
  5624. gridLineColor: '#C0C0C0',
  5625. // gridLineDashStyle: 'solid',
  5626. // gridLineWidth: 0,
  5627. // reversed: false,
  5628. labels: defaultLabelOptions,
  5629. // { step: null },
  5630. lineColor: '#C0D0E0',
  5631. lineWidth: 1,
  5632. //linkedTo: null,
  5633. //max: undefined,
  5634. //min: undefined,
  5635. minPadding: 0.01,
  5636. maxPadding: 0.01,
  5637. //minRange: null,
  5638. minorGridLineColor: '#E0E0E0',
  5639. // minorGridLineDashStyle: null,
  5640. minorGridLineWidth: 1,
  5641. minorTickColor: '#A0A0A0',
  5642. //minorTickInterval: null,
  5643. minorTickLength: 2,
  5644. minorTickPosition: 'outside', // inside or outside
  5645. //minorTickWidth: 0,
  5646. //opposite: false,
  5647. //offset: 0,
  5648. //plotBands: [{
  5649. // events: {},
  5650. // zIndex: 1,
  5651. // labels: { align, x, verticalAlign, y, style, rotation, textAlign }
  5652. //}],
  5653. //plotLines: [{
  5654. // events: {}
  5655. // dashStyle: {}
  5656. // zIndex:
  5657. // labels: { align, x, verticalAlign, y, style, rotation, textAlign }
  5658. //}],
  5659. //reversed: false,
  5660. // showFirstLabel: true,
  5661. // showLastLabel: true,
  5662. startOfWeek: 1,
  5663. startOnTick: false,
  5664. tickColor: '#C0D0E0',
  5665. //tickInterval: null,
  5666. tickLength: 5,
  5667. tickmarkPlacement: 'between', // on or between
  5668. tickPixelInterval: 100,
  5669. tickPosition: 'outside',
  5670. tickWidth: 1,
  5671. title: {
  5672. //text: null,
  5673. align: 'middle', // low, middle or high
  5674. //margin: 0 for horizontal, 10 for vertical axes,
  5675. //rotation: 0,
  5676. //side: 'outside',
  5677. style: {
  5678. color: '#4d759e',
  5679. //font: defaultFont.replace('normal', 'bold')
  5680. fontWeight: 'bold'
  5681. }
  5682. //x: 0,
  5683. //y: 0
  5684. },
  5685. type: 'linear' // linear, logarithmic or datetime
  5686. },
  5687. /**
  5688. * This options set extends the defaultOptions for Y axes
  5689. */
  5690. defaultYAxisOptions: {
  5691. endOnTick: true,
  5692. gridLineWidth: 1,
  5693. tickPixelInterval: 72,
  5694. showLastLabel: true,
  5695. labels: {
  5696. x: -8,
  5697. y: 3
  5698. },
  5699. lineWidth: 0,
  5700. maxPadding: 0.05,
  5701. minPadding: 0.05,
  5702. startOnTick: true,
  5703. tickWidth: 0,
  5704. title: {
  5705. rotation: 270,
  5706. text: 'Values'
  5707. },
  5708. stackLabels: {
  5709. enabled: false,
  5710. //align: dynamic,
  5711. //y: dynamic,
  5712. //x: dynamic,
  5713. //verticalAlign: dynamic,
  5714. //textAlign: dynamic,
  5715. //rotation: 0,
  5716. formatter: function () {
  5717. return numberFormat(this.total, -1);
  5718. },
  5719. style: defaultLabelOptions.style
  5720. }
  5721. },
  5722. /**
  5723. * These options extend the defaultOptions for left axes
  5724. */
  5725. defaultLeftAxisOptions: {
  5726. labels: {
  5727. x: -8,
  5728. y: null
  5729. },
  5730. title: {
  5731. rotation: 270
  5732. }
  5733. },
  5734. /**
  5735. * These options extend the defaultOptions for right axes
  5736. */
  5737. defaultRightAxisOptions: {
  5738. labels: {
  5739. x: 8,
  5740. y: null
  5741. },
  5742. title: {
  5743. rotation: 90
  5744. }
  5745. },
  5746. /**
  5747. * These options extend the defaultOptions for bottom axes
  5748. */
  5749. defaultBottomAxisOptions: {
  5750. labels: {
  5751. x: 0,
  5752. y: 14
  5753. // overflow: undefined,
  5754. // staggerLines: null
  5755. },
  5756. title: {
  5757. rotation: 0
  5758. }
  5759. },
  5760. /**
  5761. * These options extend the defaultOptions for left axes
  5762. */
  5763. defaultTopAxisOptions: {
  5764. labels: {
  5765. x: 0,
  5766. y: -5
  5767. // overflow: undefined
  5768. // staggerLines: null
  5769. },
  5770. title: {
  5771. rotation: 0
  5772. }
  5773. },
  5774. /**
  5775. * Initialize the axis
  5776. */
  5777. init: function (chart, userOptions) {
  5778. var isXAxis = userOptions.isX,
  5779. axis = this;
  5780. // Flag, is the axis horizontal
  5781. axis.horiz = chart.inverted ? !isXAxis : isXAxis;
  5782. // Flag, isXAxis
  5783. axis.isXAxis = isXAxis;
  5784. axis.xOrY = isXAxis ? 'x' : 'y';
  5785. axis.opposite = userOptions.opposite; // needed in setOptions
  5786. axis.side = axis.horiz ?
  5787. (axis.opposite ? 0 : 2) : // top : bottom
  5788. (axis.opposite ? 1 : 3); // right : left
  5789. axis.setOptions(userOptions);
  5790. var options = this.options,
  5791. type = options.type,
  5792. isDatetimeAxis = type === 'datetime';
  5793. axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format
  5794. // Flag, stagger lines or not
  5795. axis.userOptions = userOptions;
  5796. //axis.axisTitleMargin = UNDEFINED,// = options.title.margin,
  5797. axis.minPixelPadding = 0;
  5798. //axis.ignoreMinPadding = UNDEFINED; // can be set to true by a column or bar series
  5799. //axis.ignoreMaxPadding = UNDEFINED;
  5800. axis.chart = chart;
  5801. axis.reversed = options.reversed;
  5802. axis.zoomEnabled = options.zoomEnabled !== false;
  5803. // Initial categories
  5804. axis.categories = options.categories || type === 'category';
  5805. // Elements
  5806. //axis.axisGroup = UNDEFINED;
  5807. //axis.gridGroup = UNDEFINED;
  5808. //axis.axisTitle = UNDEFINED;
  5809. //axis.axisLine = UNDEFINED;
  5810. // Shorthand types
  5811. axis.isLog = type === 'logarithmic';
  5812. axis.isDatetimeAxis = isDatetimeAxis;
  5813. // Flag, if axis is linked to another axis
  5814. axis.isLinked = defined(options.linkedTo);
  5815. // Linked axis.
  5816. //axis.linkedParent = UNDEFINED;
  5817. // Tick positions
  5818. //axis.tickPositions = UNDEFINED; // array containing predefined positions
  5819. // Tick intervals
  5820. //axis.tickInterval = UNDEFINED;
  5821. //axis.minorTickInterval = UNDEFINED;
  5822. axis.tickmarkOffset = (axis.categories && options.tickmarkPlacement === 'between') ? 0.5 : 0;
  5823. // Major ticks
  5824. axis.ticks = {};
  5825. // Minor ticks
  5826. axis.minorTicks = {};
  5827. //axis.tickAmount = UNDEFINED;
  5828. // List of plotLines/Bands
  5829. axis.plotLinesAndBands = [];
  5830. // Alternate bands
  5831. axis.alternateBands = {};
  5832. // Axis metrics
  5833. //axis.left = UNDEFINED;
  5834. //axis.top = UNDEFINED;
  5835. //axis.width = UNDEFINED;
  5836. //axis.height = UNDEFINED;
  5837. //axis.bottom = UNDEFINED;
  5838. //axis.right = UNDEFINED;
  5839. //axis.transA = UNDEFINED;
  5840. //axis.transB = UNDEFINED;
  5841. //axis.oldTransA = UNDEFINED;
  5842. axis.len = 0;
  5843. //axis.oldMin = UNDEFINED;
  5844. //axis.oldMax = UNDEFINED;
  5845. //axis.oldUserMin = UNDEFINED;
  5846. //axis.oldUserMax = UNDEFINED;
  5847. //axis.oldAxisLength = UNDEFINED;
  5848. axis.minRange = axis.userMinRange = options.minRange || options.maxZoom;
  5849. axis.range = options.range;
  5850. axis.offset = options.offset || 0;
  5851. // Dictionary for stacks
  5852. axis.stacks = {};
  5853. axis.oldStacks = {};
  5854. // Dictionary for stacks max values
  5855. axis.stackExtremes = {};
  5856. // Min and max in the data
  5857. //axis.dataMin = UNDEFINED,
  5858. //axis.dataMax = UNDEFINED,
  5859. // The axis range
  5860. axis.max = null;
  5861. axis.min = null;
  5862. // User set min and max
  5863. //axis.userMin = UNDEFINED,
  5864. //axis.userMax = UNDEFINED,
  5865. // Run Axis
  5866. var eventType,
  5867. events = axis.options.events;
  5868. // Register
  5869. if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update()
  5870. chart.axes.push(axis);
  5871. chart[isXAxis ? 'xAxis' : 'yAxis'].push(axis);
  5872. }
  5873. axis.series = axis.series || []; // populated by Series
  5874. // inverted charts have reversed xAxes as default
  5875. if (chart.inverted && isXAxis && axis.reversed === UNDEFINED) {
  5876. axis.reversed = true;
  5877. }
  5878. axis.removePlotBand = axis.removePlotBandOrLine;
  5879. axis.removePlotLine = axis.removePlotBandOrLine;
  5880. // register event listeners
  5881. for (eventType in events) {
  5882. addEvent(axis, eventType, events[eventType]);
  5883. }
  5884. // extend logarithmic axis
  5885. if (axis.isLog) {
  5886. axis.val2lin = log2lin;
  5887. axis.lin2val = lin2log;
  5888. }
  5889. },
  5890. /**
  5891. * Merge and set options
  5892. */
  5893. setOptions: function (userOptions) {
  5894. this.options = merge(
  5895. this.defaultOptions,
  5896. this.isXAxis ? {} : this.defaultYAxisOptions,
  5897. [this.defaultTopAxisOptions, this.defaultRightAxisOptions,
  5898. this.defaultBottomAxisOptions, this.defaultLeftAxisOptions][this.side],
  5899. merge(
  5900. defaultOptions[this.isXAxis ? 'xAxis' : 'yAxis'], // if set in setOptions (#1053)
  5901. userOptions
  5902. )
  5903. );
  5904. },
  5905. /**
  5906. * Update the axis with a new options structure
  5907. */
  5908. update: function (newOptions, redraw) {
  5909. var chart = this.chart;
  5910. newOptions = chart.options[this.xOrY + 'Axis'][this.options.index] = merge(this.userOptions, newOptions);
  5911. this.destroy(true);
  5912. this._addedPlotLB = this.userMin = this.userMax = UNDEFINED; // #1611, #2306
  5913. this.init(chart, extend(newOptions, { events: UNDEFINED }));
  5914. chart.isDirtyBox = true;
  5915. if (pick(redraw, true)) {
  5916. chart.redraw();
  5917. }
  5918. },
  5919. /**
  5920. * Remove the axis from the chart
  5921. */
  5922. remove: function (redraw) {
  5923. var chart = this.chart,
  5924. key = this.xOrY + 'Axis'; // xAxis or yAxis
  5925. // Remove associated series
  5926. each(this.series, function (series) {
  5927. series.remove(false);
  5928. });
  5929. // Remove the axis
  5930. erase(chart.axes, this);
  5931. erase(chart[key], this);
  5932. chart.options[key].splice(this.options.index, 1);
  5933. each(chart[key], function (axis, i) { // Re-index, #1706
  5934. axis.options.index = i;
  5935. });
  5936. this.destroy();
  5937. chart.isDirtyBox = true;
  5938. if (pick(redraw, true)) {
  5939. chart.redraw();
  5940. }
  5941. },
  5942. /**
  5943. * The default label formatter. The context is a special config object for the label.
  5944. */
  5945. defaultLabelFormatter: function () {
  5946. var axis = this.axis,
  5947. value = this.value,
  5948. categories = axis.categories,
  5949. dateTimeLabelFormat = this.dateTimeLabelFormat,
  5950. numericSymbols = defaultOptions.lang.numericSymbols,
  5951. i = numericSymbols && numericSymbols.length,
  5952. multi,
  5953. ret,
  5954. formatOption = axis.options.labels.format,
  5955. // make sure the same symbol is added for all labels on a linear axis
  5956. numericSymbolDetector = axis.isLog ? value : axis.tickInterval;
  5957. if (formatOption) {
  5958. ret = format(formatOption, this);
  5959. } else if (categories) {
  5960. ret = value;
  5961. } else if (dateTimeLabelFormat) { // datetime axis
  5962. ret = dateFormat(dateTimeLabelFormat, value);
  5963. } else if (i && numericSymbolDetector >= 1000) {
  5964. // Decide whether we should add a numeric symbol like k (thousands) or M (millions).
  5965. // If we are to enable this in tooltip or other places as well, we can move this
  5966. // logic to the numberFormatter and enable it by a parameter.
  5967. while (i-- && ret === UNDEFINED) {
  5968. multi = Math.pow(1000, i + 1);
  5969. if (numericSymbolDetector >= multi && numericSymbols[i] !== null) {
  5970. ret = numberFormat(value / multi, -1) + numericSymbols[i];
  5971. }
  5972. }
  5973. }
  5974. if (ret === UNDEFINED) {
  5975. if (value >= 1000) { // add thousands separators
  5976. ret = numberFormat(value, 0);
  5977. } else { // small numbers
  5978. ret = numberFormat(value, -1);
  5979. }
  5980. }
  5981. return ret;
  5982. },
  5983. /**
  5984. * Get the minimum and maximum for the series of each axis
  5985. */
  5986. getSeriesExtremes: function () {
  5987. var axis = this,
  5988. chart = axis.chart;
  5989. axis.hasVisibleSeries = false;
  5990. // reset dataMin and dataMax in case we're redrawing
  5991. axis.dataMin = axis.dataMax = null;
  5992. // reset cached stacking extremes
  5993. axis.stackExtremes = {};
  5994. axis.buildStacks();
  5995. // loop through this axis' series
  5996. each(axis.series, function (series) {
  5997. if (series.visible || !chart.options.chart.ignoreHiddenSeries) {
  5998. var seriesOptions = series.options,
  5999. xData,
  6000. threshold = seriesOptions.threshold,
  6001. seriesDataMin,
  6002. seriesDataMax;
  6003. axis.hasVisibleSeries = true;
  6004. // Validate threshold in logarithmic axes
  6005. if (axis.isLog && threshold <= 0) {
  6006. threshold = null;
  6007. }
  6008. // Get dataMin and dataMax for X axes
  6009. if (axis.isXAxis) {
  6010. xData = series.xData;
  6011. if (xData.length) {
  6012. axis.dataMin = mathMin(pick(axis.dataMin, xData[0]), arrayMin(xData));
  6013. axis.dataMax = mathMax(pick(axis.dataMax, xData[0]), arrayMax(xData));
  6014. }
  6015. // Get dataMin and dataMax for Y axes, as well as handle stacking and processed data
  6016. } else {
  6017. // Get this particular series extremes
  6018. series.getExtremes();
  6019. seriesDataMax = series.dataMax;
  6020. seriesDataMin = series.dataMin;
  6021. // Get the dataMin and dataMax so far. If percentage is used, the min and max are
  6022. // always 0 and 100. If seriesDataMin and seriesDataMax is null, then series
  6023. // doesn't have active y data, we continue with nulls
  6024. if (defined(seriesDataMin) && defined(seriesDataMax)) {
  6025. axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin);
  6026. axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax);
  6027. }
  6028. // Adjust to threshold
  6029. if (defined(threshold)) {
  6030. if (axis.dataMin >= threshold) {
  6031. axis.dataMin = threshold;
  6032. axis.ignoreMinPadding = true;
  6033. } else if (axis.dataMax < threshold) {
  6034. axis.dataMax = threshold;
  6035. axis.ignoreMaxPadding = true;
  6036. }
  6037. }
  6038. }
  6039. }
  6040. });
  6041. },
  6042. /**
  6043. * Translate from axis value to pixel position on the chart, or back
  6044. *
  6045. */
  6046. translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacement) {
  6047. var axis = this,
  6048. axisLength = axis.len,
  6049. sign = 1,
  6050. cvsOffset = 0,
  6051. localA = old ? axis.oldTransA : axis.transA,
  6052. localMin = old ? axis.oldMin : axis.min,
  6053. returnValue,
  6054. minPixelPadding = axis.minPixelPadding,
  6055. postTranslate = (axis.options.ordinal || (axis.isLog && handleLog)) && axis.lin2val;
  6056. if (!localA) {
  6057. localA = axis.transA;
  6058. }
  6059. // In vertical axes, the canvas coordinates start from 0 at the top like in
  6060. // SVG.
  6061. if (cvsCoord) {
  6062. sign *= -1; // canvas coordinates inverts the value
  6063. cvsOffset = axisLength;
  6064. }
  6065. // Handle reversed axis
  6066. if (axis.reversed) {
  6067. sign *= -1;
  6068. cvsOffset -= sign * axisLength;
  6069. }
  6070. // From pixels to value
  6071. if (backwards) { // reverse translation
  6072. val = val * sign + cvsOffset;
  6073. val -= minPixelPadding;
  6074. returnValue = val / localA + localMin; // from chart pixel to value
  6075. if (postTranslate) { // log and ordinal axes
  6076. returnValue = axis.lin2val(returnValue);
  6077. }
  6078. // From value to pixels
  6079. } else {
  6080. if (postTranslate) { // log and ordinal axes
  6081. val = axis.val2lin(val);
  6082. }
  6083. if (pointPlacement === 'between') {
  6084. pointPlacement = 0.5;
  6085. }
  6086. returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) +
  6087. (isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0);
  6088. }
  6089. return returnValue;
  6090. },
  6091. /**
  6092. * Utility method to translate an axis value to pixel position.
  6093. * @param {Number} value A value in terms of axis units
  6094. * @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart
  6095. * or just the axis/pane itself.
  6096. */
  6097. toPixels: function (value, paneCoordinates) {
  6098. return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos);
  6099. },
  6100. /*
  6101. * Utility method to translate a pixel position in to an axis value
  6102. * @param {Number} pixel The pixel value coordinate
  6103. * @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the
  6104. * axis/pane itself.
  6105. */
  6106. toValue: function (pixel, paneCoordinates) {
  6107. return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true);
  6108. },
  6109. /**
  6110. * Create the path for a plot line that goes from the given value on
  6111. * this axis, across the plot to the opposite side
  6112. * @param {Number} value
  6113. * @param {Number} lineWidth Used for calculation crisp line
  6114. * @param {Number] old Use old coordinates (for resizing and rescaling)
  6115. */
  6116. getPlotLinePath: function (value, lineWidth, old, force) {
  6117. var axis = this,
  6118. chart = axis.chart,
  6119. axisLeft = axis.left,
  6120. axisTop = axis.top,
  6121. x1,
  6122. y1,
  6123. x2,
  6124. y2,
  6125. translatedValue = axis.translate(value, null, null, old),
  6126. cHeight = (old && chart.oldChartHeight) || chart.chartHeight,
  6127. cWidth = (old && chart.oldChartWidth) || chart.chartWidth,
  6128. skip,
  6129. transB = axis.transB;
  6130. x1 = x2 = mathRound(translatedValue + transB);
  6131. y1 = y2 = mathRound(cHeight - translatedValue - transB);
  6132. if (isNaN(translatedValue)) { // no min or max
  6133. skip = true;
  6134. } else if (axis.horiz) {
  6135. y1 = axisTop;
  6136. y2 = cHeight - axis.bottom;
  6137. if (x1 < axisLeft || x1 > axisLeft + axis.width) {
  6138. skip = true;
  6139. }
  6140. } else {
  6141. x1 = axisLeft;
  6142. x2 = cWidth - axis.right;
  6143. if (y1 < axisTop || y1 > axisTop + axis.height) {
  6144. skip = true;
  6145. }
  6146. }
  6147. return skip && !force ?
  6148. null :
  6149. chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 0);
  6150. },
  6151. /**
  6152. * Create the path for a plot band
  6153. */
  6154. getPlotBandPath: function (from, to) {
  6155. var toPath = this.getPlotLinePath(to),
  6156. path = this.getPlotLinePath(from);
  6157. if (path && toPath) {
  6158. path.push(
  6159. toPath[4],
  6160. toPath[5],
  6161. toPath[1],
  6162. toPath[2]
  6163. );
  6164. } else { // outside the axis area
  6165. path = null;
  6166. }
  6167. return path;
  6168. },
  6169. /**
  6170. * Set the tick positions of a linear axis to round values like whole tens or every five.
  6171. */
  6172. getLinearTickPositions: function (tickInterval, min, max) {
  6173. var pos,
  6174. lastPos,
  6175. roundedMin = correctFloat(mathFloor(min / tickInterval) * tickInterval),
  6176. roundedMax = correctFloat(mathCeil(max / tickInterval) * tickInterval),
  6177. tickPositions = [];
  6178. // Populate the intermediate values
  6179. pos = roundedMin;
  6180. while (pos <= roundedMax) {
  6181. // Place the tick on the rounded value
  6182. tickPositions.push(pos);
  6183. // Always add the raw tickInterval, not the corrected one.
  6184. pos = correctFloat(pos + tickInterval);
  6185. // If the interval is not big enough in the current min - max range to actually increase
  6186. // the loop variable, we need to break out to prevent endless loop. Issue #619
  6187. if (pos === lastPos) {
  6188. break;
  6189. }
  6190. // Record the last value
  6191. lastPos = pos;
  6192. }
  6193. return tickPositions;
  6194. },
  6195. /**
  6196. * Set the tick positions of a logarithmic axis
  6197. */
  6198. getLogTickPositions: function (interval, min, max, minor) {
  6199. var axis = this,
  6200. options = axis.options,
  6201. axisLength = axis.len,
  6202. // Since we use this method for both major and minor ticks,
  6203. // use a local variable and return the result
  6204. positions = [];
  6205. // Reset
  6206. if (!minor) {
  6207. axis._minorAutoInterval = null;
  6208. }
  6209. // First case: All ticks fall on whole logarithms: 1, 10, 100 etc.
  6210. if (interval >= 0.5) {
  6211. interval = mathRound(interval);
  6212. positions = axis.getLinearTickPositions(interval, min, max);
  6213. // Second case: We need intermediary ticks. For example
  6214. // 1, 2, 4, 6, 8, 10, 20, 40 etc.
  6215. } else if (interval >= 0.08) {
  6216. var roundedMin = mathFloor(min),
  6217. intermediate,
  6218. i,
  6219. j,
  6220. len,
  6221. pos,
  6222. lastPos,
  6223. break2;
  6224. if (interval > 0.3) {
  6225. intermediate = [1, 2, 4];
  6226. } else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc
  6227. intermediate = [1, 2, 4, 6, 8];
  6228. } else { // 0.1 equals ten minor ticks per 1, 10, 100 etc
  6229. intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  6230. }
  6231. for (i = roundedMin; i < max + 1 && !break2; i++) {
  6232. len = intermediate.length;
  6233. for (j = 0; j < len && !break2; j++) {
  6234. pos = log2lin(lin2log(i) * intermediate[j]);
  6235. if (pos > min && (!minor || lastPos <= max)) { // #1670
  6236. positions.push(lastPos);
  6237. }
  6238. if (lastPos > max) {
  6239. break2 = true;
  6240. }
  6241. lastPos = pos;
  6242. }
  6243. }
  6244. // Third case: We are so deep in between whole logarithmic values that
  6245. // we might as well handle the tick positions like a linear axis. For
  6246. // example 1.01, 1.02, 1.03, 1.04.
  6247. } else {
  6248. var realMin = lin2log(min),
  6249. realMax = lin2log(max),
  6250. tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'],
  6251. filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption,
  6252. tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1),
  6253. totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength;
  6254. interval = pick(
  6255. filteredTickIntervalOption,
  6256. axis._minorAutoInterval,
  6257. (realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1)
  6258. );
  6259. interval = normalizeTickInterval(
  6260. interval,
  6261. null,
  6262. getMagnitude(interval)
  6263. );
  6264. positions = map(axis.getLinearTickPositions(
  6265. interval,
  6266. realMin,
  6267. realMax
  6268. ), log2lin);
  6269. if (!minor) {
  6270. axis._minorAutoInterval = interval / 5;
  6271. }
  6272. }
  6273. // Set the axis-level tickInterval variable
  6274. if (!minor) {
  6275. axis.tickInterval = interval;
  6276. }
  6277. return positions;
  6278. },
  6279. /**
  6280. * Return the minor tick positions. For logarithmic axes, reuse the same logic
  6281. * as for major ticks.
  6282. */
  6283. getMinorTickPositions: function () {
  6284. var axis = this,
  6285. options = axis.options,
  6286. tickPositions = axis.tickPositions,
  6287. minorTickInterval = axis.minorTickInterval,
  6288. minorTickPositions = [],
  6289. pos,
  6290. i,
  6291. len;
  6292. if (axis.isLog) {
  6293. len = tickPositions.length;
  6294. for (i = 1; i < len; i++) {
  6295. minorTickPositions = minorTickPositions.concat(
  6296. axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true)
  6297. );
  6298. }
  6299. } else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314
  6300. minorTickPositions = minorTickPositions.concat(
  6301. getTimeTicks(
  6302. normalizeTimeTickInterval(minorTickInterval),
  6303. axis.min,
  6304. axis.max,
  6305. options.startOfWeek
  6306. )
  6307. );
  6308. if (minorTickPositions[0] < axis.min) {
  6309. minorTickPositions.shift();
  6310. }
  6311. } else {
  6312. for (pos = axis.min + (tickPositions[0] - axis.min) % minorTickInterval; pos <= axis.max; pos += minorTickInterval) {
  6313. minorTickPositions.push(pos);
  6314. }
  6315. }
  6316. return minorTickPositions;
  6317. },
  6318. /**
  6319. * Adjust the min and max for the minimum range. Keep in mind that the series data is
  6320. * not yet processed, so we don't have information on data cropping and grouping, or
  6321. * updated axis.pointRange or series.pointRange. The data can't be processed until
  6322. * we have finally established min and max.
  6323. */
  6324. adjustForMinRange: function () {
  6325. var axis = this,
  6326. options = axis.options,
  6327. min = axis.min,
  6328. max = axis.max,
  6329. zoomOffset,
  6330. spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange,
  6331. closestDataRange,
  6332. i,
  6333. distance,
  6334. xData,
  6335. loopLength,
  6336. minArgs,
  6337. maxArgs;
  6338. // Set the automatic minimum range based on the closest point distance
  6339. if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) {
  6340. if (defined(options.min) || defined(options.max)) {
  6341. axis.minRange = null; // don't do this again
  6342. } else {
  6343. // Find the closest distance between raw data points, as opposed to
  6344. // closestPointRange that applies to processed points (cropped and grouped)
  6345. each(axis.series, function (series) {
  6346. xData = series.xData;
  6347. loopLength = series.xIncrement ? 1 : xData.length - 1;
  6348. for (i = loopLength; i > 0; i--) {
  6349. distance = xData[i] - xData[i - 1];
  6350. if (closestDataRange === UNDEFINED || distance < closestDataRange) {
  6351. closestDataRange = distance;
  6352. }
  6353. }
  6354. });
  6355. axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin);
  6356. }
  6357. }
  6358. // if minRange is exceeded, adjust
  6359. if (max - min < axis.minRange) {
  6360. var minRange = axis.minRange;
  6361. zoomOffset = (minRange - max + min) / 2;
  6362. // if min and max options have been set, don't go beyond it
  6363. minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)];
  6364. if (spaceAvailable) { // if space is available, stay within the data range
  6365. minArgs[2] = axis.dataMin;
  6366. }
  6367. min = arrayMax(minArgs);
  6368. maxArgs = [min + minRange, pick(options.max, min + minRange)];
  6369. if (spaceAvailable) { // if space is availabe, stay within the data range
  6370. maxArgs[2] = axis.dataMax;
  6371. }
  6372. max = arrayMin(maxArgs);
  6373. // now if the max is adjusted, adjust the min back
  6374. if (max - min < minRange) {
  6375. minArgs[0] = max - minRange;
  6376. minArgs[1] = pick(options.min, max - minRange);
  6377. min = arrayMax(minArgs);
  6378. }
  6379. }
  6380. // Record modified extremes
  6381. axis.min = min;
  6382. axis.max = max;
  6383. },
  6384. /**
  6385. * Update translation information
  6386. */
  6387. setAxisTranslation: function (saveOld) {
  6388. var axis = this,
  6389. range = axis.max - axis.min,
  6390. pointRange = 0,
  6391. closestPointRange,
  6392. minPointOffset = 0,
  6393. pointRangePadding = 0,
  6394. linkedParent = axis.linkedParent,
  6395. ordinalCorrection,
  6396. transA = axis.transA;
  6397. // adjust translation for padding
  6398. if (axis.isXAxis) {
  6399. if (linkedParent) {
  6400. minPointOffset = linkedParent.minPointOffset;
  6401. pointRangePadding = linkedParent.pointRangePadding;
  6402. } else {
  6403. each(axis.series, function (series) {
  6404. var seriesPointRange = series.pointRange,
  6405. pointPlacement = series.options.pointPlacement,
  6406. seriesClosestPointRange = series.closestPointRange;
  6407. if (seriesPointRange > range) { // #1446
  6408. seriesPointRange = 0;
  6409. }
  6410. pointRange = mathMax(pointRange, seriesPointRange);
  6411. // minPointOffset is the value padding to the left of the axis in order to make
  6412. // room for points with a pointRange, typically columns. When the pointPlacement option
  6413. // is 'between' or 'on', this padding does not apply.
  6414. minPointOffset = mathMax(
  6415. minPointOffset,
  6416. isString(pointPlacement) ? 0 : seriesPointRange / 2
  6417. );
  6418. // Determine the total padding needed to the length of the axis to make room for the
  6419. // pointRange. If the series' pointPlacement is 'on', no padding is added.
  6420. pointRangePadding = mathMax(
  6421. pointRangePadding,
  6422. pointPlacement === 'on' ? 0 : seriesPointRange
  6423. );
  6424. // Set the closestPointRange
  6425. if (!series.noSharedTooltip && defined(seriesClosestPointRange)) {
  6426. closestPointRange = defined(closestPointRange) ?
  6427. mathMin(closestPointRange, seriesClosestPointRange) :
  6428. seriesClosestPointRange;
  6429. }
  6430. });
  6431. }
  6432. // Record minPointOffset and pointRangePadding
  6433. ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853
  6434. axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection;
  6435. axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection;
  6436. // pointRange means the width reserved for each point, like in a column chart
  6437. axis.pointRange = mathMin(pointRange, range);
  6438. // closestPointRange means the closest distance between points. In columns
  6439. // it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange
  6440. // is some other value
  6441. axis.closestPointRange = closestPointRange;
  6442. }
  6443. // Secondary values
  6444. if (saveOld) {
  6445. axis.oldTransA = transA;
  6446. }
  6447. axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1);
  6448. axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend
  6449. axis.minPixelPadding = transA * minPointOffset;
  6450. },
  6451. /**
  6452. * Set the tick positions to round values and optionally extend the extremes
  6453. * to the nearest tick
  6454. */
  6455. setTickPositions: function (secondPass) {
  6456. var axis = this,
  6457. chart = axis.chart,
  6458. options = axis.options,
  6459. isLog = axis.isLog,
  6460. isDatetimeAxis = axis.isDatetimeAxis,
  6461. isXAxis = axis.isXAxis,
  6462. isLinked = axis.isLinked,
  6463. tickPositioner = axis.options.tickPositioner,
  6464. maxPadding = options.maxPadding,
  6465. minPadding = options.minPadding,
  6466. length,
  6467. linkedParentExtremes,
  6468. tickIntervalOption = options.tickInterval,
  6469. minTickIntervalOption = options.minTickInterval,
  6470. tickPixelIntervalOption = options.tickPixelInterval,
  6471. tickPositions,
  6472. keepTwoTicksOnly,
  6473. categories = axis.categories;
  6474. // linked axis gets the extremes from the parent axis
  6475. if (isLinked) {
  6476. axis.linkedParent = chart[isXAxis ? 'xAxis' : 'yAxis'][options.linkedTo];
  6477. linkedParentExtremes = axis.linkedParent.getExtremes();
  6478. axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin);
  6479. axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax);
  6480. if (options.type !== axis.linkedParent.options.type) {
  6481. error(11, 1); // Can't link axes of different type
  6482. }
  6483. } else { // initial min and max from the extreme data values
  6484. axis.min = pick(axis.userMin, options.min, axis.dataMin);
  6485. axis.max = pick(axis.userMax, options.max, axis.dataMax);
  6486. }
  6487. if (isLog) {
  6488. if (!secondPass && mathMin(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978
  6489. error(10, 1); // Can't plot negative values on log axis
  6490. }
  6491. axis.min = correctFloat(log2lin(axis.min)); // correctFloat cures #934
  6492. axis.max = correctFloat(log2lin(axis.max));
  6493. }
  6494. // handle zoomed range
  6495. if (axis.range) {
  6496. axis.userMin = axis.min = mathMax(axis.min, axis.max - axis.range); // #618
  6497. axis.userMax = axis.max;
  6498. if (secondPass) {
  6499. axis.range = null; // don't use it when running setExtremes
  6500. }
  6501. }
  6502. // Hook for adjusting this.min and this.max. Used by bubble series.
  6503. if (axis.beforePadding) {
  6504. axis.beforePadding();
  6505. }
  6506. // adjust min and max for the minimum range
  6507. axis.adjustForMinRange();
  6508. // Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding
  6509. // into account, we do this after computing tick interval (#1337).
  6510. if (!categories && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) {
  6511. length = axis.max - axis.min;
  6512. if (length) {
  6513. if (!defined(options.min) && !defined(axis.userMin) && minPadding && (axis.dataMin < 0 || !axis.ignoreMinPadding)) {
  6514. axis.min -= length * minPadding;
  6515. }
  6516. if (!defined(options.max) && !defined(axis.userMax) && maxPadding && (axis.dataMax > 0 || !axis.ignoreMaxPadding)) {
  6517. axis.max += length * maxPadding;
  6518. }
  6519. }
  6520. }
  6521. // get tickInterval
  6522. if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) {
  6523. axis.tickInterval = 1;
  6524. } else if (isLinked && !tickIntervalOption &&
  6525. tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) {
  6526. axis.tickInterval = axis.linkedParent.tickInterval;
  6527. } else {
  6528. axis.tickInterval = pick(
  6529. tickIntervalOption,
  6530. categories ? // for categoried axis, 1 is default, for linear axis use tickPix
  6531. 1 :
  6532. // don't let it be more than the data range
  6533. (axis.max - axis.min) * tickPixelIntervalOption / mathMax(axis.len, tickPixelIntervalOption)
  6534. );
  6535. // For squished axes, set only two ticks
  6536. if (!defined(tickIntervalOption) && axis.len < tickPixelIntervalOption && !this.isRadial) {
  6537. keepTwoTicksOnly = true;
  6538. axis.tickInterval /= 4; // tick extremes closer to the real values
  6539. }
  6540. }
  6541. // Now we're finished detecting min and max, crop and group series data. This
  6542. // is in turn needed in order to find tick positions in ordinal axes.
  6543. if (isXAxis && !secondPass) {
  6544. each(axis.series, function (series) {
  6545. series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax);
  6546. });
  6547. }
  6548. // set the translation factor used in translate function
  6549. axis.setAxisTranslation(true);
  6550. // hook for ordinal axes and radial axes
  6551. if (axis.beforeSetTickPositions) {
  6552. axis.beforeSetTickPositions();
  6553. }
  6554. // hook for extensions, used in Highstock ordinal axes
  6555. if (axis.postProcessTickInterval) {
  6556. axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval);
  6557. }
  6558. // In column-like charts, don't cramp in more ticks than there are points (#1943)
  6559. if (axis.pointRange) {
  6560. axis.tickInterval = mathMax(axis.pointRange, axis.tickInterval);
  6561. }
  6562. // Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined.
  6563. if (!tickIntervalOption && axis.tickInterval < minTickIntervalOption) {
  6564. axis.tickInterval = minTickIntervalOption;
  6565. }
  6566. // for linear axes, get magnitude and normalize the interval
  6567. if (!isDatetimeAxis && !isLog) { // linear
  6568. if (!tickIntervalOption) {
  6569. axis.tickInterval = normalizeTickInterval(axis.tickInterval, null, getMagnitude(axis.tickInterval), options);
  6570. }
  6571. }
  6572. // get minorTickInterval
  6573. axis.minorTickInterval = options.minorTickInterval === 'auto' && axis.tickInterval ?
  6574. axis.tickInterval / 5 : options.minorTickInterval;
  6575. // find the tick positions
  6576. axis.tickPositions = tickPositions = options.tickPositions ?
  6577. [].concat(options.tickPositions) : // Work on a copy (#1565)
  6578. (tickPositioner && tickPositioner.apply(axis, [axis.min, axis.max]));
  6579. if (!tickPositions) {
  6580. // Too many ticks
  6581. if (!axis.ordinalPositions && (axis.max - axis.min) / axis.tickInterval > mathMax(2 * axis.len, 200)) {
  6582. error(19, true);
  6583. }
  6584. if (isDatetimeAxis) {
  6585. tickPositions = (axis.getNonLinearTimeTicks || getTimeTicks)(
  6586. normalizeTimeTickInterval(axis.tickInterval, options.units),
  6587. axis.min,
  6588. axis.max,
  6589. options.startOfWeek,
  6590. axis.ordinalPositions,
  6591. axis.closestPointRange,
  6592. true
  6593. );
  6594. } else if (isLog) {
  6595. tickPositions = axis.getLogTickPositions(axis.tickInterval, axis.min, axis.max);
  6596. } else {
  6597. tickPositions = axis.getLinearTickPositions(axis.tickInterval, axis.min, axis.max);
  6598. }
  6599. if (keepTwoTicksOnly) {
  6600. tickPositions.splice(1, tickPositions.length - 2);
  6601. }
  6602. axis.tickPositions = tickPositions;
  6603. }
  6604. if (!isLinked) {
  6605. // reset min/max or remove extremes based on start/end on tick
  6606. var roundedMin = tickPositions[0],
  6607. roundedMax = tickPositions[tickPositions.length - 1],
  6608. minPointOffset = axis.minPointOffset || 0,
  6609. singlePad;
  6610. if (options.startOnTick) {
  6611. axis.min = roundedMin;
  6612. } else if (axis.min - minPointOffset > roundedMin) {
  6613. tickPositions.shift();
  6614. }
  6615. if (options.endOnTick) {
  6616. axis.max = roundedMax;
  6617. } else if (axis.max + minPointOffset < roundedMax) {
  6618. tickPositions.pop();
  6619. }
  6620. // When there is only one point, or all points have the same value on this axis, then min
  6621. // and max are equal and tickPositions.length is 1. In this case, add some padding
  6622. // in order to center the point, but leave it with one tick. #1337.
  6623. if (tickPositions.length === 1) {
  6624. singlePad = 0.001; // The lowest possible number to avoid extra padding on columns
  6625. axis.min -= singlePad;
  6626. axis.max += singlePad;
  6627. }
  6628. }
  6629. },
  6630. /**
  6631. * Set the max ticks of either the x and y axis collection
  6632. */
  6633. setMaxTicks: function () {
  6634. var chart = this.chart,
  6635. maxTicks = chart.maxTicks || {},
  6636. tickPositions = this.tickPositions,
  6637. key = this._maxTicksKey = [this.xOrY, this.pos, this.len].join('-');
  6638. if (!this.isLinked && !this.isDatetimeAxis && tickPositions && tickPositions.length > (maxTicks[key] || 0) && this.options.alignTicks !== false) {
  6639. maxTicks[key] = tickPositions.length;
  6640. }
  6641. chart.maxTicks = maxTicks;
  6642. },
  6643. /**
  6644. * When using multiple axes, adjust the number of ticks to match the highest
  6645. * number of ticks in that group
  6646. */
  6647. adjustTickAmount: function () {
  6648. var axis = this,
  6649. chart = axis.chart,
  6650. key = axis._maxTicksKey,
  6651. tickPositions = axis.tickPositions,
  6652. maxTicks = chart.maxTicks;
  6653. if (maxTicks && maxTicks[key] && !axis.isDatetimeAxis && !axis.categories && !axis.isLinked && axis.options.alignTicks !== false) { // only apply to linear scale
  6654. var oldTickAmount = axis.tickAmount,
  6655. calculatedTickAmount = tickPositions.length,
  6656. tickAmount;
  6657. // set the axis-level tickAmount to use below
  6658. axis.tickAmount = tickAmount = maxTicks[key];
  6659. if (calculatedTickAmount < tickAmount) {
  6660. while (tickPositions.length < tickAmount) {
  6661. tickPositions.push(correctFloat(
  6662. tickPositions[tickPositions.length - 1] + axis.tickInterval
  6663. ));
  6664. }
  6665. axis.transA *= (calculatedTickAmount - 1) / (tickAmount - 1);
  6666. axis.max = tickPositions[tickPositions.length - 1];
  6667. }
  6668. if (defined(oldTickAmount) && tickAmount !== oldTickAmount) {
  6669. axis.isDirty = true;
  6670. }
  6671. }
  6672. },
  6673. /**
  6674. * Set the scale based on data min and max, user set min and max or options
  6675. *
  6676. */
  6677. setScale: function () {
  6678. var axis = this,
  6679. stacks = axis.stacks,
  6680. type,
  6681. i,
  6682. isDirtyData,
  6683. isDirtyAxisLength;
  6684. axis.oldMin = axis.min;
  6685. axis.oldMax = axis.max;
  6686. axis.oldAxisLength = axis.len;
  6687. // set the new axisLength
  6688. axis.setAxisSize();
  6689. //axisLength = horiz ? axisWidth : axisHeight;
  6690. isDirtyAxisLength = axis.len !== axis.oldAxisLength;
  6691. // is there new data?
  6692. each(axis.series, function (series) {
  6693. if (series.isDirtyData || series.isDirty ||
  6694. series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well
  6695. isDirtyData = true;
  6696. }
  6697. });
  6698. // do we really need to go through all this?
  6699. if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw ||
  6700. axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax) {
  6701. // reset stacks
  6702. if (!axis.isXAxis) {
  6703. for (type in stacks) {
  6704. delete stacks[type];
  6705. }
  6706. }
  6707. axis.forceRedraw = false;
  6708. // get data extremes if needed
  6709. axis.getSeriesExtremes();
  6710. // get fixed positions based on tickInterval
  6711. axis.setTickPositions();
  6712. // record old values to decide whether a rescale is necessary later on (#540)
  6713. axis.oldUserMin = axis.userMin;
  6714. axis.oldUserMax = axis.userMax;
  6715. // Mark as dirty if it is not already set to dirty and extremes have changed. #595.
  6716. if (!axis.isDirty) {
  6717. axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax;
  6718. }
  6719. } else if (!axis.isXAxis) {
  6720. if (axis.oldStacks) {
  6721. stacks = axis.stacks = axis.oldStacks;
  6722. }
  6723. // reset stacks
  6724. for (type in stacks) {
  6725. for (i in stacks[type]) {
  6726. stacks[type][i].cum = stacks[type][i].total;
  6727. }
  6728. }
  6729. }
  6730. // Set the maximum tick amount
  6731. axis.setMaxTicks();
  6732. },
  6733. /**
  6734. * Set the extremes and optionally redraw
  6735. * @param {Number} newMin
  6736. * @param {Number} newMax
  6737. * @param {Boolean} redraw
  6738. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  6739. * configuration
  6740. * @param {Object} eventArguments
  6741. *
  6742. */
  6743. setExtremes: function (newMin, newMax, redraw, animation, eventArguments) {
  6744. var axis = this,
  6745. chart = axis.chart;
  6746. redraw = pick(redraw, true); // defaults to true
  6747. // Extend the arguments with min and max
  6748. eventArguments = extend(eventArguments, {
  6749. min: newMin,
  6750. max: newMax
  6751. });
  6752. // Fire the event
  6753. fireEvent(axis, 'setExtremes', eventArguments, function () { // the default event handler
  6754. axis.userMin = newMin;
  6755. axis.userMax = newMax;
  6756. axis.eventArgs = eventArguments;
  6757. // Mark for running afterSetExtremes
  6758. axis.isDirtyExtremes = true;
  6759. // redraw
  6760. if (redraw) {
  6761. chart.redraw(animation);
  6762. }
  6763. });
  6764. },
  6765. /**
  6766. * Overridable method for zooming chart. Pulled out in a separate method to allow overriding
  6767. * in stock charts.
  6768. */
  6769. zoom: function (newMin, newMax) {
  6770. // Prevent pinch zooming out of range. Check for defined is for #1946.
  6771. if (!this.allowZoomOutside) {
  6772. if (defined(this.dataMin) && newMin <= this.dataMin) {
  6773. newMin = UNDEFINED;
  6774. }
  6775. if (defined(this.dataMax) && newMax >= this.dataMax) {
  6776. newMax = UNDEFINED;
  6777. }
  6778. }
  6779. // In full view, displaying the reset zoom button is not required
  6780. this.displayBtn = newMin !== UNDEFINED || newMax !== UNDEFINED;
  6781. // Do it
  6782. this.setExtremes(
  6783. newMin,
  6784. newMax,
  6785. false,
  6786. UNDEFINED,
  6787. { trigger: 'zoom' }
  6788. );
  6789. return true;
  6790. },
  6791. /**
  6792. * Update the axis metrics
  6793. */
  6794. setAxisSize: function () {
  6795. var chart = this.chart,
  6796. options = this.options,
  6797. offsetLeft = options.offsetLeft || 0,
  6798. offsetRight = options.offsetRight || 0,
  6799. horiz = this.horiz,
  6800. width,
  6801. height,
  6802. top,
  6803. left;
  6804. // Expose basic values to use in Series object and navigator
  6805. this.left = left = pick(options.left, chart.plotLeft + offsetLeft);
  6806. this.top = top = pick(options.top, chart.plotTop);
  6807. this.width = width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight);
  6808. this.height = height = pick(options.height, chart.plotHeight);
  6809. this.bottom = chart.chartHeight - height - top;
  6810. this.right = chart.chartWidth - width - left;
  6811. // Direction agnostic properties
  6812. this.len = mathMax(horiz ? width : height, 0); // mathMax fixes #905
  6813. this.pos = horiz ? left : top; // distance from SVG origin
  6814. },
  6815. /**
  6816. * Get the actual axis extremes
  6817. */
  6818. getExtremes: function () {
  6819. var axis = this,
  6820. isLog = axis.isLog;
  6821. return {
  6822. min: isLog ? correctFloat(lin2log(axis.min)) : axis.min,
  6823. max: isLog ? correctFloat(lin2log(axis.max)) : axis.max,
  6824. dataMin: axis.dataMin,
  6825. dataMax: axis.dataMax,
  6826. userMin: axis.userMin,
  6827. userMax: axis.userMax
  6828. };
  6829. },
  6830. /**
  6831. * Get the zero plane either based on zero or on the min or max value.
  6832. * Used in bar and area plots
  6833. */
  6834. getThreshold: function (threshold) {
  6835. var axis = this,
  6836. isLog = axis.isLog;
  6837. var realMin = isLog ? lin2log(axis.min) : axis.min,
  6838. realMax = isLog ? lin2log(axis.max) : axis.max;
  6839. if (realMin > threshold || threshold === null) {
  6840. threshold = realMin;
  6841. } else if (realMax < threshold) {
  6842. threshold = realMax;
  6843. }
  6844. return axis.translate(threshold, 0, 1, 0, 1);
  6845. },
  6846. addPlotBand: function (options) {
  6847. this.addPlotBandOrLine(options, 'plotBands');
  6848. },
  6849. addPlotLine: function (options) {
  6850. this.addPlotBandOrLine(options, 'plotLines');
  6851. },
  6852. /**
  6853. * Add a plot band or plot line after render time
  6854. *
  6855. * @param options {Object} The plotBand or plotLine configuration object
  6856. */
  6857. addPlotBandOrLine: function (options, coll) {
  6858. var obj = new PlotLineOrBand(this, options).render(),
  6859. userOptions = this.userOptions;
  6860. if (obj) { // #2189
  6861. // Add it to the user options for exporting and Axis.update
  6862. if (coll) {
  6863. userOptions[coll] = userOptions[coll] || [];
  6864. userOptions[coll].push(options);
  6865. }
  6866. this.plotLinesAndBands.push(obj);
  6867. }
  6868. return obj;
  6869. },
  6870. /**
  6871. * Compute auto alignment for the axis label based on which side the axis is on
  6872. * and the given rotation for the label
  6873. */
  6874. autoLabelAlign: function (rotation) {
  6875. var ret,
  6876. angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360;
  6877. if (angle > 15 && angle < 165) {
  6878. ret = 'right';
  6879. } else if (angle > 195 && angle < 345) {
  6880. ret = 'left';
  6881. } else {
  6882. ret = 'center';
  6883. }
  6884. return ret;
  6885. },
  6886. /**
  6887. * Render the tick labels to a preliminary position to get their sizes
  6888. */
  6889. getOffset: function () {
  6890. var axis = this,
  6891. chart = axis.chart,
  6892. renderer = chart.renderer,
  6893. options = axis.options,
  6894. tickPositions = axis.tickPositions,
  6895. ticks = axis.ticks,
  6896. horiz = axis.horiz,
  6897. side = axis.side,
  6898. invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side,
  6899. hasData,
  6900. showAxis,
  6901. titleOffset = 0,
  6902. titleOffsetOption,
  6903. titleMargin = 0,
  6904. axisTitleOptions = options.title,
  6905. labelOptions = options.labels,
  6906. labelOffset = 0, // reset
  6907. axisOffset = chart.axisOffset,
  6908. clipOffset = chart.clipOffset,
  6909. directionFactor = [-1, 1, 1, -1][side],
  6910. n,
  6911. i,
  6912. autoStaggerLines = 1,
  6913. maxStaggerLines = pick(labelOptions.maxStaggerLines, 5),
  6914. sortedPositions,
  6915. lastRight,
  6916. overlap,
  6917. pos,
  6918. bBox,
  6919. x,
  6920. w,
  6921. lineNo;
  6922. // For reuse in Axis.render
  6923. axis.hasData = hasData = (axis.hasVisibleSeries || (defined(axis.min) && defined(axis.max) && !!tickPositions));
  6924. axis.showAxis = showAxis = hasData || pick(options.showEmpty, true);
  6925. // Set/reset staggerLines
  6926. axis.staggerLines = axis.horiz && labelOptions.staggerLines;
  6927. // Create the axisGroup and gridGroup elements on first iteration
  6928. if (!axis.axisGroup) {
  6929. axis.gridGroup = renderer.g('grid')
  6930. .attr({ zIndex: options.gridZIndex || 1 })
  6931. .add();
  6932. axis.axisGroup = renderer.g('axis')
  6933. .attr({ zIndex: options.zIndex || 2 })
  6934. .add();
  6935. axis.labelGroup = renderer.g('axis-labels')
  6936. .attr({ zIndex: labelOptions.zIndex || 7 })
  6937. .add();
  6938. }
  6939. if (hasData || axis.isLinked) {
  6940. // Set the explicit or automatic label alignment
  6941. axis.labelAlign = pick(labelOptions.align || axis.autoLabelAlign(labelOptions.rotation));
  6942. each(tickPositions, function (pos) {
  6943. if (!ticks[pos]) {
  6944. ticks[pos] = new Tick(axis, pos);
  6945. } else {
  6946. ticks[pos].addLabel(); // update labels depending on tick interval
  6947. }
  6948. });
  6949. // Handle automatic stagger lines
  6950. if (axis.horiz && !axis.staggerLines && maxStaggerLines && !labelOptions.rotation) {
  6951. sortedPositions = axis.reversed ? [].concat(tickPositions).reverse() : tickPositions;
  6952. while (autoStaggerLines < maxStaggerLines) {
  6953. lastRight = [];
  6954. overlap = false;
  6955. for (i = 0; i < sortedPositions.length; i++) {
  6956. pos = sortedPositions[i];
  6957. bBox = ticks[pos].label && ticks[pos].label.getBBox();
  6958. w = bBox ? bBox.width : 0;
  6959. lineNo = i % autoStaggerLines;
  6960. if (w) {
  6961. x = axis.translate(pos); // don't handle log
  6962. if (lastRight[lineNo] !== UNDEFINED && x < lastRight[lineNo]) {
  6963. overlap = true;
  6964. }
  6965. lastRight[lineNo] = x + w;
  6966. }
  6967. }
  6968. if (overlap) {
  6969. autoStaggerLines++;
  6970. } else {
  6971. break;
  6972. }
  6973. }
  6974. if (autoStaggerLines > 1) {
  6975. axis.staggerLines = autoStaggerLines;
  6976. }
  6977. }
  6978. each(tickPositions, function (pos) {
  6979. // left side must be align: right and right side must have align: left for labels
  6980. if (side === 0 || side === 2 || { 1: 'left', 3: 'right' }[side] === axis.labelAlign) {
  6981. // get the highest offset
  6982. labelOffset = mathMax(
  6983. ticks[pos].getLabelSize(),
  6984. labelOffset
  6985. );
  6986. }
  6987. });
  6988. if (axis.staggerLines) {
  6989. labelOffset *= axis.staggerLines;
  6990. axis.labelOffset = labelOffset;
  6991. }
  6992. } else { // doesn't have data
  6993. for (n in ticks) {
  6994. ticks[n].destroy();
  6995. delete ticks[n];
  6996. }
  6997. }
  6998. if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) {
  6999. if (!axis.axisTitle) {
  7000. axis.axisTitle = renderer.text(
  7001. axisTitleOptions.text,
  7002. 0,
  7003. 0,
  7004. axisTitleOptions.useHTML
  7005. )
  7006. .attr({
  7007. zIndex: 7,
  7008. rotation: axisTitleOptions.rotation || 0,
  7009. align:
  7010. axisTitleOptions.textAlign ||
  7011. { low: 'left', middle: 'center', high: 'right' }[axisTitleOptions.align]
  7012. })
  7013. .css(axisTitleOptions.style)
  7014. .add(axis.axisGroup);
  7015. axis.axisTitle.isNew = true;
  7016. }
  7017. if (showAxis) {
  7018. titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width'];
  7019. titleMargin = pick(axisTitleOptions.margin, horiz ? 5 : 10);
  7020. titleOffsetOption = axisTitleOptions.offset;
  7021. }
  7022. // hide or show the title depending on whether showEmpty is set
  7023. axis.axisTitle[showAxis ? 'show' : 'hide']();
  7024. }
  7025. // handle automatic or user set offset
  7026. axis.offset = directionFactor * pick(options.offset, axisOffset[side]);
  7027. axis.axisTitleMargin =
  7028. pick(titleOffsetOption,
  7029. labelOffset + titleMargin +
  7030. (side !== 2 && labelOffset && directionFactor * options.labels[horiz ? 'y' : 'x'])
  7031. );
  7032. axisOffset[side] = mathMax(
  7033. axisOffset[side],
  7034. axis.axisTitleMargin + titleOffset + directionFactor * axis.offset
  7035. );
  7036. clipOffset[invertedSide] = mathMax(clipOffset[invertedSide], mathFloor(options.lineWidth / 2) * 2);
  7037. },
  7038. /**
  7039. * Get the path for the axis line
  7040. */
  7041. getLinePath: function (lineWidth) {
  7042. var chart = this.chart,
  7043. opposite = this.opposite,
  7044. offset = this.offset,
  7045. horiz = this.horiz,
  7046. lineLeft = this.left + (opposite ? this.width : 0) + offset,
  7047. lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset;
  7048. if (opposite) {
  7049. lineWidth *= -1; // crispify the other way - #1480, #1687
  7050. }
  7051. return chart.renderer.crispLine([
  7052. M,
  7053. horiz ?
  7054. this.left :
  7055. lineLeft,
  7056. horiz ?
  7057. lineTop :
  7058. this.top,
  7059. L,
  7060. horiz ?
  7061. chart.chartWidth - this.right :
  7062. lineLeft,
  7063. horiz ?
  7064. lineTop :
  7065. chart.chartHeight - this.bottom
  7066. ], lineWidth);
  7067. },
  7068. /**
  7069. * Position the title
  7070. */
  7071. getTitlePosition: function () {
  7072. // compute anchor points for each of the title align options
  7073. var horiz = this.horiz,
  7074. axisLeft = this.left,
  7075. axisTop = this.top,
  7076. axisLength = this.len,
  7077. axisTitleOptions = this.options.title,
  7078. margin = horiz ? axisLeft : axisTop,
  7079. opposite = this.opposite,
  7080. offset = this.offset,
  7081. fontSize = pInt(axisTitleOptions.style.fontSize || 12),
  7082. // the position in the length direction of the axis
  7083. alongAxis = {
  7084. low: margin + (horiz ? 0 : axisLength),
  7085. middle: margin + axisLength / 2,
  7086. high: margin + (horiz ? axisLength : 0)
  7087. }[axisTitleOptions.align],
  7088. // the position in the perpendicular direction of the axis
  7089. offAxis = (horiz ? axisTop + this.height : axisLeft) +
  7090. (horiz ? 1 : -1) * // horizontal axis reverses the margin
  7091. (opposite ? -1 : 1) * // so does opposite axes
  7092. this.axisTitleMargin +
  7093. (this.side === 2 ? fontSize : 0);
  7094. return {
  7095. x: horiz ?
  7096. alongAxis :
  7097. offAxis + (opposite ? this.width : 0) + offset +
  7098. (axisTitleOptions.x || 0), // x
  7099. y: horiz ?
  7100. offAxis - (opposite ? this.height : 0) + offset :
  7101. alongAxis + (axisTitleOptions.y || 0) // y
  7102. };
  7103. },
  7104. /**
  7105. * Render the axis
  7106. */
  7107. render: function () {
  7108. var axis = this,
  7109. chart = axis.chart,
  7110. renderer = chart.renderer,
  7111. options = axis.options,
  7112. isLog = axis.isLog,
  7113. isLinked = axis.isLinked,
  7114. tickPositions = axis.tickPositions,
  7115. axisTitle = axis.axisTitle,
  7116. stacks = axis.stacks,
  7117. ticks = axis.ticks,
  7118. minorTicks = axis.minorTicks,
  7119. alternateBands = axis.alternateBands,
  7120. stackLabelOptions = options.stackLabels,
  7121. alternateGridColor = options.alternateGridColor,
  7122. tickmarkOffset = axis.tickmarkOffset,
  7123. lineWidth = options.lineWidth,
  7124. linePath,
  7125. hasRendered = chart.hasRendered,
  7126. slideInTicks = hasRendered && defined(axis.oldMin) && !isNaN(axis.oldMin),
  7127. hasData = axis.hasData,
  7128. showAxis = axis.showAxis,
  7129. from,
  7130. to;
  7131. // Mark all elements inActive before we go over and mark the active ones
  7132. each([ticks, minorTicks, alternateBands], function (coll) {
  7133. var pos;
  7134. for (pos in coll) {
  7135. coll[pos].isActive = false;
  7136. }
  7137. });
  7138. // If the series has data draw the ticks. Else only the line and title
  7139. if (hasData || isLinked) {
  7140. // minor ticks
  7141. if (axis.minorTickInterval && !axis.categories) {
  7142. each(axis.getMinorTickPositions(), function (pos) {
  7143. if (!minorTicks[pos]) {
  7144. minorTicks[pos] = new Tick(axis, pos, 'minor');
  7145. }
  7146. // render new ticks in old position
  7147. if (slideInTicks && minorTicks[pos].isNew) {
  7148. minorTicks[pos].render(null, true);
  7149. }
  7150. minorTicks[pos].render(null, false, 1);
  7151. });
  7152. }
  7153. // Major ticks. Pull out the first item and render it last so that
  7154. // we can get the position of the neighbour label. #808.
  7155. if (tickPositions.length) { // #1300
  7156. each(tickPositions.slice(1).concat([tickPositions[0]]), function (pos, i) {
  7157. // Reorganize the indices
  7158. i = (i === tickPositions.length - 1) ? 0 : i + 1;
  7159. // linked axes need an extra check to find out if
  7160. if (!isLinked || (pos >= axis.min && pos <= axis.max)) {
  7161. if (!ticks[pos]) {
  7162. ticks[pos] = new Tick(axis, pos);
  7163. }
  7164. // render new ticks in old position
  7165. if (slideInTicks && ticks[pos].isNew) {
  7166. ticks[pos].render(i, true);
  7167. }
  7168. ticks[pos].render(i, false, 1);
  7169. }
  7170. });
  7171. // In a categorized axis, the tick marks are displayed between labels. So
  7172. // we need to add a tick mark and grid line at the left edge of the X axis.
  7173. if (tickmarkOffset && axis.min === 0) {
  7174. if (!ticks[-1]) {
  7175. ticks[-1] = new Tick(axis, -1, null, true);
  7176. }
  7177. ticks[-1].render(-1);
  7178. }
  7179. }
  7180. // alternate grid color
  7181. if (alternateGridColor) {
  7182. each(tickPositions, function (pos, i) {
  7183. if (i % 2 === 0 && pos < axis.max) {
  7184. if (!alternateBands[pos]) {
  7185. alternateBands[pos] = new PlotLineOrBand(axis);
  7186. }
  7187. from = pos + tickmarkOffset; // #949
  7188. to = tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] + tickmarkOffset : axis.max;
  7189. alternateBands[pos].options = {
  7190. from: isLog ? lin2log(from) : from,
  7191. to: isLog ? lin2log(to) : to,
  7192. color: alternateGridColor
  7193. };
  7194. alternateBands[pos].render();
  7195. alternateBands[pos].isActive = true;
  7196. }
  7197. });
  7198. }
  7199. // custom plot lines and bands
  7200. if (!axis._addedPlotLB) { // only first time
  7201. each((options.plotLines || []).concat(options.plotBands || []), function (plotLineOptions) {
  7202. axis.addPlotBandOrLine(plotLineOptions);
  7203. });
  7204. axis._addedPlotLB = true;
  7205. }
  7206. } // end if hasData
  7207. // Remove inactive ticks
  7208. each([ticks, minorTicks, alternateBands], function (coll) {
  7209. var pos,
  7210. i,
  7211. forDestruction = [],
  7212. delay = globalAnimation ? globalAnimation.duration || 500 : 0,
  7213. destroyInactiveItems = function () {
  7214. i = forDestruction.length;
  7215. while (i--) {
  7216. // When resizing rapidly, the same items may be destroyed in different timeouts,
  7217. // or the may be reactivated
  7218. if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) {
  7219. coll[forDestruction[i]].destroy();
  7220. delete coll[forDestruction[i]];
  7221. }
  7222. }
  7223. };
  7224. for (pos in coll) {
  7225. if (!coll[pos].isActive) {
  7226. // Render to zero opacity
  7227. coll[pos].render(pos, false, 0);
  7228. coll[pos].isActive = false;
  7229. forDestruction.push(pos);
  7230. }
  7231. }
  7232. // When the objects are finished fading out, destroy them
  7233. if (coll === alternateBands || !chart.hasRendered || !delay) {
  7234. destroyInactiveItems();
  7235. } else if (delay) {
  7236. setTimeout(destroyInactiveItems, delay);
  7237. }
  7238. });
  7239. // Static items. As the axis group is cleared on subsequent calls
  7240. // to render, these items are added outside the group.
  7241. // axis line
  7242. if (lineWidth) {
  7243. linePath = axis.getLinePath(lineWidth);
  7244. if (!axis.axisLine) {
  7245. axis.axisLine = renderer.path(linePath)
  7246. .attr({
  7247. stroke: options.lineColor,
  7248. 'stroke-width': lineWidth,
  7249. zIndex: 7
  7250. })
  7251. .add(axis.axisGroup);
  7252. } else {
  7253. axis.axisLine.animate({ d: linePath });
  7254. }
  7255. // show or hide the line depending on options.showEmpty
  7256. axis.axisLine[showAxis ? 'show' : 'hide']();
  7257. }
  7258. if (axisTitle && showAxis) {
  7259. axisTitle[axisTitle.isNew ? 'attr' : 'animate'](
  7260. axis.getTitlePosition()
  7261. );
  7262. axisTitle.isNew = false;
  7263. }
  7264. // Stacked totals:
  7265. if (stackLabelOptions && stackLabelOptions.enabled) {
  7266. var stackKey, oneStack, stackCategory,
  7267. stackTotalGroup = axis.stackTotalGroup;
  7268. // Create a separate group for the stack total labels
  7269. if (!stackTotalGroup) {
  7270. axis.stackTotalGroup = stackTotalGroup =
  7271. renderer.g('stack-labels')
  7272. .attr({
  7273. visibility: VISIBLE,
  7274. zIndex: 6
  7275. })
  7276. .add();
  7277. }
  7278. // plotLeft/Top will change when y axis gets wider so we need to translate the
  7279. // stackTotalGroup at every render call. See bug #506 and #516
  7280. stackTotalGroup.translate(chart.plotLeft, chart.plotTop);
  7281. // Render each stack total
  7282. for (stackKey in stacks) {
  7283. oneStack = stacks[stackKey];
  7284. for (stackCategory in oneStack) {
  7285. oneStack[stackCategory].render(stackTotalGroup);
  7286. }
  7287. }
  7288. }
  7289. // End stacked totals
  7290. axis.isDirty = false;
  7291. },
  7292. /**
  7293. * Remove a plot band or plot line from the chart by id
  7294. * @param {Object} id
  7295. */
  7296. removePlotBandOrLine: function (id) {
  7297. var plotLinesAndBands = this.plotLinesAndBands,
  7298. options = this.options,
  7299. userOptions = this.userOptions,
  7300. i = plotLinesAndBands.length;
  7301. while (i--) {
  7302. if (plotLinesAndBands[i].id === id) {
  7303. plotLinesAndBands[i].destroy();
  7304. }
  7305. }
  7306. each([options.plotLines || [], userOptions.plotLines || [], options.plotBands || [], userOptions.plotBands || []], function (arr) {
  7307. i = arr.length;
  7308. while (i--) {
  7309. if (arr[i].id === id) {
  7310. erase(arr, arr[i]);
  7311. }
  7312. }
  7313. });
  7314. },
  7315. /**
  7316. * Update the axis title by options
  7317. */
  7318. setTitle: function (newTitleOptions, redraw) {
  7319. this.update({ title: newTitleOptions }, redraw);
  7320. },
  7321. /**
  7322. * Redraw the axis to reflect changes in the data or axis extremes
  7323. */
  7324. redraw: function () {
  7325. var axis = this,
  7326. chart = axis.chart,
  7327. pointer = chart.pointer;
  7328. // hide tooltip and hover states
  7329. if (pointer.reset) {
  7330. pointer.reset(true);
  7331. }
  7332. // render the axis
  7333. axis.render();
  7334. // move plot lines and bands
  7335. each(axis.plotLinesAndBands, function (plotLine) {
  7336. plotLine.render();
  7337. });
  7338. // mark associated series as dirty and ready for redraw
  7339. each(axis.series, function (series) {
  7340. series.isDirty = true;
  7341. });
  7342. },
  7343. /**
  7344. * Build the stacks from top down
  7345. */
  7346. buildStacks: function () {
  7347. var series = this.series,
  7348. i = series.length;
  7349. if (!this.isXAxis) {
  7350. while (i--) {
  7351. series[i].setStackedPoints();
  7352. }
  7353. // Loop up again to compute percent stack
  7354. if (this.usePercentage) {
  7355. for (i = 0; i < series.length; i++) {
  7356. series[i].setPercentStacks();
  7357. }
  7358. }
  7359. }
  7360. },
  7361. /**
  7362. * Set new axis categories and optionally redraw
  7363. * @param {Array} categories
  7364. * @param {Boolean} redraw
  7365. */
  7366. setCategories: function (categories, redraw) {
  7367. this.update({ categories: categories }, redraw);
  7368. },
  7369. /**
  7370. * Destroys an Axis instance.
  7371. */
  7372. destroy: function (keepEvents) {
  7373. var axis = this,
  7374. stacks = axis.stacks,
  7375. stackKey,
  7376. plotLinesAndBands = axis.plotLinesAndBands,
  7377. i;
  7378. // Remove the events
  7379. if (!keepEvents) {
  7380. removeEvent(axis);
  7381. }
  7382. // Destroy each stack total
  7383. for (stackKey in stacks) {
  7384. destroyObjectProperties(stacks[stackKey]);
  7385. stacks[stackKey] = null;
  7386. }
  7387. // Destroy collections
  7388. each([axis.ticks, axis.minorTicks, axis.alternateBands], function (coll) {
  7389. destroyObjectProperties(coll);
  7390. });
  7391. i = plotLinesAndBands.length;
  7392. while (i--) { // #1975
  7393. plotLinesAndBands[i].destroy();
  7394. }
  7395. // Destroy local variables
  7396. each(['stackTotalGroup', 'axisLine', 'axisGroup', 'gridGroup', 'labelGroup', 'axisTitle'], function (prop) {
  7397. if (axis[prop]) {
  7398. axis[prop] = axis[prop].destroy();
  7399. }
  7400. });
  7401. }
  7402. }; // end Axis
  7403. /**
  7404. * The tooltip object
  7405. * @param {Object} chart The chart instance
  7406. * @param {Object} options Tooltip options
  7407. */
  7408. function Tooltip() {
  7409. this.init.apply(this, arguments);
  7410. }
  7411. Tooltip.prototype = {
  7412. init: function (chart, options) {
  7413. var borderWidth = options.borderWidth,
  7414. style = options.style,
  7415. padding = pInt(style.padding);
  7416. // Save the chart and options
  7417. this.chart = chart;
  7418. this.options = options;
  7419. // Keep track of the current series
  7420. //this.currentSeries = UNDEFINED;
  7421. // List of crosshairs
  7422. this.crosshairs = [];
  7423. // Current values of x and y when animating
  7424. this.now = { x: 0, y: 0 };
  7425. // The tooltip is initially hidden
  7426. this.isHidden = true;
  7427. // create the label
  7428. this.label = chart.renderer.label('', 0, 0, options.shape, null, null, options.useHTML, null, 'tooltip')
  7429. .attr({
  7430. padding: padding,
  7431. fill: options.backgroundColor,
  7432. 'stroke-width': borderWidth,
  7433. r: options.borderRadius,
  7434. zIndex: 8
  7435. })
  7436. .css(style)
  7437. .css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117)
  7438. .add()
  7439. .attr({ y: -999 }); // #2301
  7440. // When using canVG the shadow shows up as a gray circle
  7441. // even if the tooltip is hidden.
  7442. if (!useCanVG) {
  7443. this.label.shadow(options.shadow);
  7444. }
  7445. // Public property for getting the shared state.
  7446. this.shared = options.shared;
  7447. },
  7448. /**
  7449. * Destroy the tooltip and its elements.
  7450. */
  7451. destroy: function () {
  7452. each(this.crosshairs, function (crosshair) {
  7453. if (crosshair) {
  7454. crosshair.destroy();
  7455. }
  7456. });
  7457. // Destroy and clear local variables
  7458. if (this.label) {
  7459. this.label = this.label.destroy();
  7460. }
  7461. clearTimeout(this.hideTimer);
  7462. clearTimeout(this.tooltipTimeout);
  7463. },
  7464. /**
  7465. * Provide a soft movement for the tooltip
  7466. *
  7467. * @param {Number} x
  7468. * @param {Number} y
  7469. * @private
  7470. */
  7471. move: function (x, y, anchorX, anchorY) {
  7472. var tooltip = this,
  7473. now = tooltip.now,
  7474. animate = tooltip.options.animation !== false && !tooltip.isHidden;
  7475. // get intermediate values for animation
  7476. extend(now, {
  7477. x: animate ? (2 * now.x + x) / 3 : x,
  7478. y: animate ? (now.y + y) / 2 : y,
  7479. anchorX: animate ? (2 * now.anchorX + anchorX) / 3 : anchorX,
  7480. anchorY: animate ? (now.anchorY + anchorY) / 2 : anchorY
  7481. });
  7482. // move to the intermediate value
  7483. tooltip.label.attr(now);
  7484. // run on next tick of the mouse tracker
  7485. if (animate && (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1)) {
  7486. // never allow two timeouts
  7487. clearTimeout(this.tooltipTimeout);
  7488. // set the fixed interval ticking for the smooth tooltip
  7489. this.tooltipTimeout = setTimeout(function () {
  7490. // The interval function may still be running during destroy, so check that the chart is really there before calling.
  7491. if (tooltip) {
  7492. tooltip.move(x, y, anchorX, anchorY);
  7493. }
  7494. }, 32);
  7495. }
  7496. },
  7497. /**
  7498. * Hide the tooltip
  7499. */
  7500. hide: function () {
  7501. var tooltip = this,
  7502. hoverPoints;
  7503. clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766)
  7504. if (!this.isHidden) {
  7505. hoverPoints = this.chart.hoverPoints;
  7506. this.hideTimer = setTimeout(function () {
  7507. tooltip.label.fadeOut();
  7508. tooltip.isHidden = true;
  7509. }, pick(this.options.hideDelay, 500));
  7510. // hide previous hoverPoints and set new
  7511. if (hoverPoints) {
  7512. each(hoverPoints, function (point) {
  7513. point.setState();
  7514. });
  7515. }
  7516. this.chart.hoverPoints = null;
  7517. }
  7518. },
  7519. /**
  7520. * Hide the crosshairs
  7521. */
  7522. hideCrosshairs: function () {
  7523. each(this.crosshairs, function (crosshair) {
  7524. if (crosshair) {
  7525. crosshair.hide();
  7526. }
  7527. });
  7528. },
  7529. /**
  7530. * Extendable method to get the anchor position of the tooltip
  7531. * from a point or set of points
  7532. */
  7533. getAnchor: function (points, mouseEvent) {
  7534. var ret,
  7535. chart = this.chart,
  7536. inverted = chart.inverted,
  7537. plotTop = chart.plotTop,
  7538. plotX = 0,
  7539. plotY = 0,
  7540. yAxis;
  7541. points = splat(points);
  7542. // Pie uses a special tooltipPos
  7543. ret = points[0].tooltipPos;
  7544. // When tooltip follows mouse, relate the position to the mouse
  7545. if (this.followPointer && mouseEvent) {
  7546. if (mouseEvent.chartX === UNDEFINED) {
  7547. mouseEvent = chart.pointer.normalize(mouseEvent);
  7548. }
  7549. ret = [
  7550. mouseEvent.chartX - chart.plotLeft,
  7551. mouseEvent.chartY - plotTop
  7552. ];
  7553. }
  7554. // When shared, use the average position
  7555. if (!ret) {
  7556. each(points, function (point) {
  7557. yAxis = point.series.yAxis;
  7558. plotX += point.plotX;
  7559. plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) +
  7560. (!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151
  7561. });
  7562. plotX /= points.length;
  7563. plotY /= points.length;
  7564. ret = [
  7565. inverted ? chart.plotWidth - plotY : plotX,
  7566. this.shared && !inverted && points.length > 1 && mouseEvent ?
  7567. mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424)
  7568. inverted ? chart.plotHeight - plotX : plotY
  7569. ];
  7570. }
  7571. return map(ret, mathRound);
  7572. },
  7573. /**
  7574. * Place the tooltip in a chart without spilling over
  7575. * and not covering the point it self.
  7576. */
  7577. getPosition: function (boxWidth, boxHeight, point) {
  7578. // Set up the variables
  7579. var chart = this.chart,
  7580. plotLeft = chart.plotLeft,
  7581. plotTop = chart.plotTop,
  7582. plotWidth = chart.plotWidth,
  7583. plotHeight = chart.plotHeight,
  7584. distance = pick(this.options.distance, 12),
  7585. pointX = point.plotX,
  7586. pointY = point.plotY,
  7587. x = pointX + plotLeft + (chart.inverted ? distance : -boxWidth - distance),
  7588. y = pointY - boxHeight + plotTop + 15, // 15 means the point is 15 pixels up from the bottom of the tooltip
  7589. alignedRight;
  7590. // It is too far to the left, adjust it
  7591. if (x < 7) {
  7592. x = plotLeft + mathMax(pointX, 0) + distance;
  7593. }
  7594. // Test to see if the tooltip is too far to the right,
  7595. // if it is, move it back to be inside and then up to not cover the point.
  7596. if ((x + boxWidth) > (plotLeft + plotWidth)) {
  7597. x -= (x + boxWidth) - (plotLeft + plotWidth);
  7598. y = pointY - boxHeight + plotTop - distance;
  7599. alignedRight = true;
  7600. }
  7601. // If it is now above the plot area, align it to the top of the plot area
  7602. if (y < plotTop + 5) {
  7603. y = plotTop + 5;
  7604. // If the tooltip is still covering the point, move it below instead
  7605. if (alignedRight && pointY >= y && pointY <= (y + boxHeight)) {
  7606. y = pointY + plotTop + distance; // below
  7607. }
  7608. }
  7609. // Now if the tooltip is below the chart, move it up. It's better to cover the
  7610. // point than to disappear outside the chart. #834.
  7611. if (y + boxHeight > plotTop + plotHeight) {
  7612. y = mathMax(plotTop, plotTop + plotHeight - boxHeight - distance); // below
  7613. }
  7614. return {x: x, y: y};
  7615. },
  7616. /**
  7617. * In case no user defined formatter is given, this will be used. Note that the context
  7618. * here is an object holding point, series, x, y etc.
  7619. */
  7620. defaultFormatter: function (tooltip) {
  7621. var items = this.points || splat(this),
  7622. series = items[0].series,
  7623. s;
  7624. // build the header
  7625. s = [series.tooltipHeaderFormatter(items[0])];
  7626. // build the values
  7627. each(items, function (item) {
  7628. series = item.series;
  7629. s.push((series.tooltipFormatter && series.tooltipFormatter(item)) ||
  7630. item.point.tooltipFormatter(series.tooltipOptions.pointFormat));
  7631. });
  7632. // footer
  7633. s.push(tooltip.options.footerFormat || '');
  7634. return s.join('');
  7635. },
  7636. /**
  7637. * Refresh the tooltip's text and position.
  7638. * @param {Object} point
  7639. */
  7640. refresh: function (point, mouseEvent) {
  7641. var tooltip = this,
  7642. chart = tooltip.chart,
  7643. label = tooltip.label,
  7644. options = tooltip.options,
  7645. x,
  7646. y,
  7647. anchor,
  7648. textConfig = {},
  7649. text,
  7650. pointConfig = [],
  7651. formatter = options.formatter || tooltip.defaultFormatter,
  7652. hoverPoints = chart.hoverPoints,
  7653. borderColor,
  7654. crosshairsOptions = options.crosshairs,
  7655. shared = tooltip.shared,
  7656. currentSeries;
  7657. clearTimeout(this.hideTimer);
  7658. // get the reference point coordinates (pie charts use tooltipPos)
  7659. tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer;
  7660. anchor = tooltip.getAnchor(point, mouseEvent);
  7661. x = anchor[0];
  7662. y = anchor[1];
  7663. // shared tooltip, array is sent over
  7664. if (shared && !(point.series && point.series.noSharedTooltip)) {
  7665. // hide previous hoverPoints and set new
  7666. chart.hoverPoints = point;
  7667. if (hoverPoints) {
  7668. each(hoverPoints, function (point) {
  7669. point.setState();
  7670. });
  7671. }
  7672. each(point, function (item) {
  7673. item.setState(HOVER_STATE);
  7674. pointConfig.push(item.getLabelConfig());
  7675. });
  7676. textConfig = {
  7677. x: point[0].category,
  7678. y: point[0].y
  7679. };
  7680. textConfig.points = pointConfig;
  7681. point = point[0];
  7682. // single point tooltip
  7683. } else {
  7684. textConfig = point.getLabelConfig();
  7685. }
  7686. text = formatter.call(textConfig, tooltip);
  7687. // register the current series
  7688. currentSeries = point.series;
  7689. // update the inner HTML
  7690. if (text === false) {
  7691. this.hide();
  7692. } else {
  7693. // show it
  7694. if (tooltip.isHidden) {
  7695. stop(label);
  7696. label.attr('opacity', 1).show();
  7697. }
  7698. // update text
  7699. label.attr({
  7700. text: text
  7701. });
  7702. // set the stroke color of the box
  7703. borderColor = options.borderColor || point.color || currentSeries.color || '#606060';
  7704. label.attr({
  7705. stroke: borderColor
  7706. });
  7707. tooltip.updatePosition({ plotX: x, plotY: y });
  7708. this.isHidden = false;
  7709. }
  7710. // crosshairs
  7711. if (crosshairsOptions) {
  7712. crosshairsOptions = splat(crosshairsOptions); // [x, y]
  7713. var path,
  7714. i = crosshairsOptions.length,
  7715. attribs,
  7716. axis,
  7717. val,
  7718. series;
  7719. while (i--) {
  7720. series = point.series;
  7721. axis = series[i ? 'yAxis' : 'xAxis'];
  7722. if (crosshairsOptions[i] && axis) {
  7723. val = i ? pick(point.stackY, point.y) : point.x; // #814
  7724. if (axis.isLog) { // #1671
  7725. val = log2lin(val);
  7726. }
  7727. if (i === 1 && series.modifyValue) { // #1205, #2316
  7728. val = series.modifyValue(val);
  7729. }
  7730. path = axis.getPlotLinePath(
  7731. val,
  7732. 1
  7733. );
  7734. if (tooltip.crosshairs[i]) {
  7735. tooltip.crosshairs[i].attr({ d: path, visibility: VISIBLE });
  7736. } else {
  7737. attribs = {
  7738. 'stroke-width': crosshairsOptions[i].width || 1,
  7739. stroke: crosshairsOptions[i].color || '#C0C0C0',
  7740. zIndex: crosshairsOptions[i].zIndex || 2
  7741. };
  7742. if (crosshairsOptions[i].dashStyle) {
  7743. attribs.dashstyle = crosshairsOptions[i].dashStyle;
  7744. }
  7745. tooltip.crosshairs[i] = chart.renderer.path(path)
  7746. .attr(attribs)
  7747. .add();
  7748. }
  7749. }
  7750. }
  7751. }
  7752. fireEvent(chart, 'tooltipRefresh', {
  7753. text: text,
  7754. x: x + chart.plotLeft,
  7755. y: y + chart.plotTop,
  7756. borderColor: borderColor
  7757. });
  7758. },
  7759. /**
  7760. * Find the new position and perform the move
  7761. */
  7762. updatePosition: function (point) {
  7763. var chart = this.chart,
  7764. label = this.label,
  7765. pos = (this.options.positioner || this.getPosition).call(
  7766. this,
  7767. label.width,
  7768. label.height,
  7769. point
  7770. );
  7771. // do the move
  7772. this.move(
  7773. mathRound(pos.x),
  7774. mathRound(pos.y),
  7775. point.plotX + chart.plotLeft,
  7776. point.plotY + chart.plotTop
  7777. );
  7778. }
  7779. };
  7780. /**
  7781. * The mouse tracker object. All methods starting with "on" are primary DOM event handlers.
  7782. * Subsequent methods should be named differently from what they are doing.
  7783. * @param {Object} chart The Chart instance
  7784. * @param {Object} options The root options object
  7785. */
  7786. function Pointer(chart, options) {
  7787. this.init(chart, options);
  7788. }
  7789. Pointer.prototype = {
  7790. /**
  7791. * Initialize Pointer
  7792. */
  7793. init: function (chart, options) {
  7794. var chartOptions = options.chart,
  7795. chartEvents = chartOptions.events,
  7796. zoomType = useCanVG ? '' : chartOptions.zoomType,
  7797. inverted = chart.inverted,
  7798. zoomX,
  7799. zoomY;
  7800. // Store references
  7801. this.options = options;
  7802. this.chart = chart;
  7803. // Zoom status
  7804. this.zoomX = zoomX = /x/.test(zoomType);
  7805. this.zoomY = zoomY = /y/.test(zoomType);
  7806. this.zoomHor = (zoomX && !inverted) || (zoomY && inverted);
  7807. this.zoomVert = (zoomY && !inverted) || (zoomX && inverted);
  7808. // Do we need to handle click on a touch device?
  7809. this.runChartClick = chartEvents && !!chartEvents.click;
  7810. this.pinchDown = [];
  7811. this.lastValidTouch = {};
  7812. if (options.tooltip.enabled) {
  7813. chart.tooltip = new Tooltip(chart, options.tooltip);
  7814. }
  7815. this.setDOMEvents();
  7816. },
  7817. /**
  7818. * Add crossbrowser support for chartX and chartY
  7819. * @param {Object} e The event object in standard browsers
  7820. */
  7821. normalize: function (e, chartPosition) {
  7822. var chartX,
  7823. chartY,
  7824. ePos;
  7825. // common IE normalizing
  7826. e = e || win.event;
  7827. if (!e.target) {
  7828. e.target = e.srcElement;
  7829. }
  7830. // Framework specific normalizing (#1165)
  7831. e = washMouseEvent(e);
  7832. // iOS
  7833. ePos = e.touches ? e.touches.item(0) : e;
  7834. // Get mouse position
  7835. if (!chartPosition) {
  7836. this.chartPosition = chartPosition = offset(this.chart.container);
  7837. }
  7838. // chartX and chartY
  7839. if (ePos.pageX === UNDEFINED) { // IE < 9. #886.
  7840. chartX = mathMax(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is
  7841. // for IE10 quirks mode within framesets
  7842. chartY = e.y;
  7843. } else {
  7844. chartX = ePos.pageX - chartPosition.left;
  7845. chartY = ePos.pageY - chartPosition.top;
  7846. }
  7847. return extend(e, {
  7848. chartX: mathRound(chartX),
  7849. chartY: mathRound(chartY)
  7850. });
  7851. },
  7852. /**
  7853. * Get the click position in terms of axis values.
  7854. *
  7855. * @param {Object} e A pointer event
  7856. */
  7857. getCoordinates: function (e) {
  7858. var coordinates = {
  7859. xAxis: [],
  7860. yAxis: []
  7861. };
  7862. each(this.chart.axes, function (axis) {
  7863. coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({
  7864. axis: axis,
  7865. value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY'])
  7866. });
  7867. });
  7868. return coordinates;
  7869. },
  7870. /**
  7871. * Return the index in the tooltipPoints array, corresponding to pixel position in
  7872. * the plot area.
  7873. */
  7874. getIndex: function (e) {
  7875. var chart = this.chart;
  7876. return chart.inverted ?
  7877. chart.plotHeight + chart.plotTop - e.chartY :
  7878. e.chartX - chart.plotLeft;
  7879. },
  7880. /**
  7881. * With line type charts with a single tracker, get the point closest to the mouse.
  7882. * Run Point.onMouseOver and display tooltip for the point or points.
  7883. */
  7884. runPointActions: function (e) {
  7885. var pointer = this,
  7886. chart = pointer.chart,
  7887. series = chart.series,
  7888. tooltip = chart.tooltip,
  7889. point,
  7890. points,
  7891. hoverPoint = chart.hoverPoint,
  7892. hoverSeries = chart.hoverSeries,
  7893. i,
  7894. j,
  7895. distance = chart.chartWidth,
  7896. index = pointer.getIndex(e),
  7897. anchor;
  7898. // shared tooltip
  7899. if (tooltip && pointer.options.tooltip.shared && !(hoverSeries && hoverSeries.noSharedTooltip)) {
  7900. points = [];
  7901. // loop over all series and find the ones with points closest to the mouse
  7902. i = series.length;
  7903. for (j = 0; j < i; j++) {
  7904. if (series[j].visible &&
  7905. series[j].options.enableMouseTracking !== false &&
  7906. !series[j].noSharedTooltip && series[j].tooltipPoints.length) {
  7907. point = series[j].tooltipPoints[index];
  7908. if (point && point.series) { // not a dummy point, #1544
  7909. point._dist = mathAbs(index - point.clientX);
  7910. distance = mathMin(distance, point._dist);
  7911. points.push(point);
  7912. }
  7913. }
  7914. }
  7915. // remove furthest points
  7916. i = points.length;
  7917. while (i--) {
  7918. if (points[i]._dist > distance) {
  7919. points.splice(i, 1);
  7920. }
  7921. }
  7922. // refresh the tooltip if necessary
  7923. if (points.length && (points[0].clientX !== pointer.hoverX)) {
  7924. tooltip.refresh(points, e);
  7925. pointer.hoverX = points[0].clientX;
  7926. }
  7927. }
  7928. // separate tooltip and general mouse events
  7929. if (hoverSeries && hoverSeries.tracker) { // only use for line-type series with common tracker
  7930. // get the point
  7931. point = hoverSeries.tooltipPoints[index];
  7932. // a new point is hovered, refresh the tooltip
  7933. if (point && point !== hoverPoint) {
  7934. // trigger the events
  7935. point.onMouseOver(e);
  7936. }
  7937. } else if (tooltip && tooltip.followPointer && !tooltip.isHidden) {
  7938. anchor = tooltip.getAnchor([{}], e);
  7939. tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] });
  7940. }
  7941. },
  7942. /**
  7943. * Reset the tracking by hiding the tooltip, the hover series state and the hover point
  7944. *
  7945. * @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible
  7946. */
  7947. reset: function (allowMove) {
  7948. var pointer = this,
  7949. chart = pointer.chart,
  7950. hoverSeries = chart.hoverSeries,
  7951. hoverPoint = chart.hoverPoint,
  7952. tooltip = chart.tooltip,
  7953. tooltipPoints = tooltip && tooltip.shared ? chart.hoverPoints : hoverPoint;
  7954. // Narrow in allowMove
  7955. allowMove = allowMove && tooltip && tooltipPoints;
  7956. // Check if the points have moved outside the plot area, #1003
  7957. if (allowMove && splat(tooltipPoints)[0].plotX === UNDEFINED) {
  7958. allowMove = false;
  7959. }
  7960. // Just move the tooltip, #349
  7961. if (allowMove) {
  7962. tooltip.refresh(tooltipPoints);
  7963. // Full reset
  7964. } else {
  7965. if (hoverPoint) {
  7966. hoverPoint.onMouseOut();
  7967. }
  7968. if (hoverSeries) {
  7969. hoverSeries.onMouseOut();
  7970. }
  7971. if (tooltip) {
  7972. tooltip.hide();
  7973. tooltip.hideCrosshairs();
  7974. }
  7975. pointer.hoverX = null;
  7976. }
  7977. },
  7978. /**
  7979. * Scale series groups to a certain scale and translation
  7980. */
  7981. scaleGroups: function (attribs, clip) {
  7982. var chart = this.chart,
  7983. seriesAttribs;
  7984. // Scale each series
  7985. each(chart.series, function (series) {
  7986. seriesAttribs = attribs || series.getPlotBox(); // #1701
  7987. if (series.xAxis && series.xAxis.zoomEnabled) {
  7988. series.group.attr(seriesAttribs);
  7989. if (series.markerGroup) {
  7990. series.markerGroup.attr(seriesAttribs);
  7991. series.markerGroup.clip(clip ? chart.clipRect : null);
  7992. }
  7993. if (series.dataLabelsGroup) {
  7994. series.dataLabelsGroup.attr(seriesAttribs);
  7995. }
  7996. }
  7997. });
  7998. // Clip
  7999. chart.clipRect.attr(clip || chart.clipBox);
  8000. },
  8001. /**
  8002. * Run translation operations for each direction (horizontal and vertical) independently
  8003. */
  8004. pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) {
  8005. var chart = this.chart,
  8006. xy = horiz ? 'x' : 'y',
  8007. XY = horiz ? 'X' : 'Y',
  8008. sChartXY = 'chart' + XY,
  8009. wh = horiz ? 'width' : 'height',
  8010. plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')],
  8011. selectionWH,
  8012. selectionXY,
  8013. clipXY,
  8014. scale = 1,
  8015. inverted = chart.inverted,
  8016. bounds = chart.bounds[horiz ? 'h' : 'v'],
  8017. singleTouch = pinchDown.length === 1,
  8018. touch0Start = pinchDown[0][sChartXY],
  8019. touch0Now = touches[0][sChartXY],
  8020. touch1Start = !singleTouch && pinchDown[1][sChartXY],
  8021. touch1Now = !singleTouch && touches[1][sChartXY],
  8022. outOfBounds,
  8023. transformScale,
  8024. scaleKey,
  8025. setScale = function () {
  8026. if (!singleTouch && mathAbs(touch0Start - touch1Start) > 20) { // Don't zoom if fingers are too close on this axis
  8027. scale = mathAbs(touch0Now - touch1Now) / mathAbs(touch0Start - touch1Start);
  8028. }
  8029. clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start;
  8030. selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale;
  8031. };
  8032. // Set the scale, first pass
  8033. setScale();
  8034. selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not
  8035. // Out of bounds
  8036. if (selectionXY < bounds.min) {
  8037. selectionXY = bounds.min;
  8038. outOfBounds = true;
  8039. } else if (selectionXY + selectionWH > bounds.max) {
  8040. selectionXY = bounds.max - selectionWH;
  8041. outOfBounds = true;
  8042. }
  8043. // Is the chart dragged off its bounds, determined by dataMin and dataMax?
  8044. if (outOfBounds) {
  8045. // Modify the touchNow position in order to create an elastic drag movement. This indicates
  8046. // to the user that the chart is responsive but can't be dragged further.
  8047. touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]);
  8048. if (!singleTouch) {
  8049. touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]);
  8050. }
  8051. // Set the scale, second pass to adapt to the modified touchNow positions
  8052. setScale();
  8053. } else {
  8054. lastValidTouch[xy] = [touch0Now, touch1Now];
  8055. }
  8056. // Set geometry for clipping, selection and transformation
  8057. if (!inverted) { // TODO: implement clipping for inverted charts
  8058. clip[xy] = clipXY - plotLeftTop;
  8059. clip[wh] = selectionWH;
  8060. }
  8061. scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY;
  8062. transformScale = inverted ? 1 / scale : scale;
  8063. selectionMarker[wh] = selectionWH;
  8064. selectionMarker[xy] = selectionXY;
  8065. transform[scaleKey] = scale;
  8066. transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start));
  8067. },
  8068. /**
  8069. * Handle touch events with two touches
  8070. */
  8071. pinch: function (e) {
  8072. var self = this,
  8073. chart = self.chart,
  8074. pinchDown = self.pinchDown,
  8075. followTouchMove = chart.tooltip && chart.tooltip.options.followTouchMove,
  8076. touches = e.touches,
  8077. touchesLength = touches.length,
  8078. lastValidTouch = self.lastValidTouch,
  8079. zoomHor = self.zoomHor || self.pinchHor,
  8080. zoomVert = self.zoomVert || self.pinchVert,
  8081. hasZoom = zoomHor || zoomVert,
  8082. selectionMarker = self.selectionMarker,
  8083. transform = {},
  8084. fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, PREFIX + 'tracker') &&
  8085. chart.runTrackerClick) || chart.runChartClick),
  8086. clip = {};
  8087. // On touch devices, only proceed to trigger click if a handler is defined
  8088. if ((hasZoom || followTouchMove) && !fireClickEvent) {
  8089. e.preventDefault();
  8090. }
  8091. // Normalize each touch
  8092. map(touches, function (e) {
  8093. return self.normalize(e);
  8094. });
  8095. // Register the touch start position
  8096. if (e.type === 'touchstart') {
  8097. each(touches, function (e, i) {
  8098. pinchDown[i] = { chartX: e.chartX, chartY: e.chartY };
  8099. });
  8100. lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX];
  8101. lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY];
  8102. // Identify the data bounds in pixels
  8103. each(chart.axes, function (axis) {
  8104. if (axis.zoomEnabled) {
  8105. var bounds = chart.bounds[axis.horiz ? 'h' : 'v'],
  8106. minPixelPadding = axis.minPixelPadding,
  8107. min = axis.toPixels(axis.dataMin),
  8108. max = axis.toPixels(axis.dataMax),
  8109. absMin = mathMin(min, max),
  8110. absMax = mathMax(min, max);
  8111. // Store the bounds for use in the touchmove handler
  8112. bounds.min = mathMin(axis.pos, absMin - minPixelPadding);
  8113. bounds.max = mathMax(axis.pos + axis.len, absMax + minPixelPadding);
  8114. }
  8115. });
  8116. // Event type is touchmove, handle panning and pinching
  8117. } else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first
  8118. // Set the marker
  8119. if (!selectionMarker) {
  8120. self.selectionMarker = selectionMarker = extend({
  8121. destroy: noop
  8122. }, chart.plotBox);
  8123. }
  8124. if (zoomHor) {
  8125. self.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
  8126. }
  8127. if (zoomVert) {
  8128. self.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
  8129. }
  8130. self.hasPinched = hasZoom;
  8131. // Scale and translate the groups to provide visual feedback during pinching
  8132. self.scaleGroups(transform, clip);
  8133. // Optionally move the tooltip on touchmove
  8134. if (!hasZoom && followTouchMove && touchesLength === 1) {
  8135. this.runPointActions(self.normalize(e));
  8136. }
  8137. }
  8138. },
  8139. /**
  8140. * Start a drag operation
  8141. */
  8142. dragStart: function (e) {
  8143. var chart = this.chart;
  8144. // Record the start position
  8145. chart.mouseIsDown = e.type;
  8146. chart.cancelClick = false;
  8147. chart.mouseDownX = this.mouseDownX = e.chartX;
  8148. chart.mouseDownY = this.mouseDownY = e.chartY;
  8149. },
  8150. /**
  8151. * Perform a drag operation in response to a mousemove event while the mouse is down
  8152. */
  8153. drag: function (e) {
  8154. var chart = this.chart,
  8155. chartOptions = chart.options.chart,
  8156. chartX = e.chartX,
  8157. chartY = e.chartY,
  8158. zoomHor = this.zoomHor,
  8159. zoomVert = this.zoomVert,
  8160. plotLeft = chart.plotLeft,
  8161. plotTop = chart.plotTop,
  8162. plotWidth = chart.plotWidth,
  8163. plotHeight = chart.plotHeight,
  8164. clickedInside,
  8165. size,
  8166. mouseDownX = this.mouseDownX,
  8167. mouseDownY = this.mouseDownY;
  8168. // If the mouse is outside the plot area, adjust to cooordinates
  8169. // inside to prevent the selection marker from going outside
  8170. if (chartX < plotLeft) {
  8171. chartX = plotLeft;
  8172. } else if (chartX > plotLeft + plotWidth) {
  8173. chartX = plotLeft + plotWidth;
  8174. }
  8175. if (chartY < plotTop) {
  8176. chartY = plotTop;
  8177. } else if (chartY > plotTop + plotHeight) {
  8178. chartY = plotTop + plotHeight;
  8179. }
  8180. // determine if the mouse has moved more than 10px
  8181. this.hasDragged = Math.sqrt(
  8182. Math.pow(mouseDownX - chartX, 2) +
  8183. Math.pow(mouseDownY - chartY, 2)
  8184. );
  8185. if (this.hasDragged > 10) {
  8186. clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop);
  8187. // make a selection
  8188. if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside) {
  8189. if (!this.selectionMarker) {
  8190. this.selectionMarker = chart.renderer.rect(
  8191. plotLeft,
  8192. plotTop,
  8193. zoomHor ? 1 : plotWidth,
  8194. zoomVert ? 1 : plotHeight,
  8195. 0
  8196. )
  8197. .attr({
  8198. fill: chartOptions.selectionMarkerFill || 'rgba(69,114,167,0.25)',
  8199. zIndex: 7
  8200. })
  8201. .add();
  8202. }
  8203. }
  8204. // adjust the width of the selection marker
  8205. if (this.selectionMarker && zoomHor) {
  8206. size = chartX - mouseDownX;
  8207. this.selectionMarker.attr({
  8208. width: mathAbs(size),
  8209. x: (size > 0 ? 0 : size) + mouseDownX
  8210. });
  8211. }
  8212. // adjust the height of the selection marker
  8213. if (this.selectionMarker && zoomVert) {
  8214. size = chartY - mouseDownY;
  8215. this.selectionMarker.attr({
  8216. height: mathAbs(size),
  8217. y: (size > 0 ? 0 : size) + mouseDownY
  8218. });
  8219. }
  8220. // panning
  8221. if (clickedInside && !this.selectionMarker && chartOptions.panning) {
  8222. chart.pan(e, chartOptions.panning);
  8223. }
  8224. }
  8225. },
  8226. /**
  8227. * On mouse up or touch end across the entire document, drop the selection.
  8228. */
  8229. drop: function (e) {
  8230. var chart = this.chart,
  8231. hasPinched = this.hasPinched;
  8232. if (this.selectionMarker) {
  8233. var selectionData = {
  8234. xAxis: [],
  8235. yAxis: [],
  8236. originalEvent: e.originalEvent || e
  8237. },
  8238. selectionBox = this.selectionMarker,
  8239. selectionLeft = selectionBox.x,
  8240. selectionTop = selectionBox.y,
  8241. runZoom;
  8242. // a selection has been made
  8243. if (this.hasDragged || hasPinched) {
  8244. // record each axis' min and max
  8245. each(chart.axes, function (axis) {
  8246. if (axis.zoomEnabled) {
  8247. var horiz = axis.horiz,
  8248. selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop)),
  8249. selectionMax = axis.toValue((horiz ? selectionLeft + selectionBox.width : selectionTop + selectionBox.height));
  8250. if (!isNaN(selectionMin) && !isNaN(selectionMax)) { // #859
  8251. selectionData[axis.xOrY + 'Axis'].push({
  8252. axis: axis,
  8253. min: mathMin(selectionMin, selectionMax), // for reversed axes,
  8254. max: mathMax(selectionMin, selectionMax)
  8255. });
  8256. runZoom = true;
  8257. }
  8258. }
  8259. });
  8260. if (runZoom) {
  8261. fireEvent(chart, 'selection', selectionData, function (args) {
  8262. chart.zoom(extend(args, hasPinched ? { animation: false } : null));
  8263. });
  8264. }
  8265. }
  8266. this.selectionMarker = this.selectionMarker.destroy();
  8267. // Reset scaling preview
  8268. if (hasPinched) {
  8269. this.scaleGroups();
  8270. }
  8271. }
  8272. // Reset all
  8273. if (chart) { // it may be destroyed on mouse up - #877
  8274. css(chart.container, { cursor: chart._cursor });
  8275. chart.cancelClick = this.hasDragged > 10; // #370
  8276. chart.mouseIsDown = this.hasDragged = this.hasPinched = false;
  8277. this.pinchDown = [];
  8278. }
  8279. },
  8280. onContainerMouseDown: function (e) {
  8281. e = this.normalize(e);
  8282. // issue #295, dragging not always working in Firefox
  8283. if (e.preventDefault) {
  8284. e.preventDefault();
  8285. }
  8286. this.dragStart(e);
  8287. },
  8288. onDocumentMouseUp: function (e) {
  8289. this.drop(e);
  8290. },
  8291. /**
  8292. * Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea.
  8293. * Issue #149 workaround. The mouseleave event does not always fire.
  8294. */
  8295. onDocumentMouseMove: function (e) {
  8296. var chart = this.chart,
  8297. chartPosition = this.chartPosition,
  8298. hoverSeries = chart.hoverSeries;
  8299. e = this.normalize(e, chartPosition);
  8300. // If we're outside, hide the tooltip
  8301. if (chartPosition && hoverSeries && !this.inClass(e.target, 'highcharts-tracker') &&
  8302. !chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
  8303. this.reset();
  8304. }
  8305. },
  8306. /**
  8307. * When mouse leaves the container, hide the tooltip.
  8308. */
  8309. onContainerMouseLeave: function () {
  8310. this.reset();
  8311. this.chartPosition = null; // also reset the chart position, used in #149 fix
  8312. },
  8313. // The mousemove, touchmove and touchstart event handler
  8314. onContainerMouseMove: function (e) {
  8315. var chart = this.chart;
  8316. // normalize
  8317. e = this.normalize(e);
  8318. // #295
  8319. e.returnValue = false;
  8320. if (chart.mouseIsDown === 'mousedown') {
  8321. this.drag(e);
  8322. }
  8323. // Show the tooltip and run mouse over events (#977)
  8324. if ((this.inClass(e.target, 'highcharts-tracker') ||
  8325. chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) {
  8326. this.runPointActions(e);
  8327. }
  8328. },
  8329. /**
  8330. * Utility to detect whether an element has, or has a parent with, a specific
  8331. * class name. Used on detection of tracker objects and on deciding whether
  8332. * hovering the tooltip should cause the active series to mouse out.
  8333. */
  8334. inClass: function (element, className) {
  8335. var elemClassName;
  8336. while (element) {
  8337. elemClassName = attr(element, 'class');
  8338. if (elemClassName) {
  8339. if (elemClassName.indexOf(className) !== -1) {
  8340. return true;
  8341. } else if (elemClassName.indexOf(PREFIX + 'container') !== -1) {
  8342. return false;
  8343. }
  8344. }
  8345. element = element.parentNode;
  8346. }
  8347. },
  8348. onTrackerMouseOut: function (e) {
  8349. var series = this.chart.hoverSeries;
  8350. if (series && !series.options.stickyTracking && !this.inClass(e.toElement || e.relatedTarget, PREFIX + 'tooltip')) {
  8351. series.onMouseOut();
  8352. }
  8353. },
  8354. onContainerClick: function (e) {
  8355. var chart = this.chart,
  8356. hoverPoint = chart.hoverPoint,
  8357. plotLeft = chart.plotLeft,
  8358. plotTop = chart.plotTop,
  8359. inverted = chart.inverted,
  8360. chartPosition,
  8361. plotX,
  8362. plotY;
  8363. e = this.normalize(e);
  8364. e.cancelBubble = true; // IE specific
  8365. if (!chart.cancelClick) {
  8366. // On tracker click, fire the series and point events. #783, #1583
  8367. if (hoverPoint && this.inClass(e.target, PREFIX + 'tracker')) {
  8368. chartPosition = this.chartPosition;
  8369. plotX = hoverPoint.plotX;
  8370. plotY = hoverPoint.plotY;
  8371. // add page position info
  8372. extend(hoverPoint, {
  8373. pageX: chartPosition.left + plotLeft +
  8374. (inverted ? chart.plotWidth - plotY : plotX),
  8375. pageY: chartPosition.top + plotTop +
  8376. (inverted ? chart.plotHeight - plotX : plotY)
  8377. });
  8378. // the series click event
  8379. fireEvent(hoverPoint.series, 'click', extend(e, {
  8380. point: hoverPoint
  8381. }));
  8382. // the point click event
  8383. if (chart.hoverPoint) { // it may be destroyed (#1844)
  8384. hoverPoint.firePointEvent('click', e);
  8385. }
  8386. // When clicking outside a tracker, fire a chart event
  8387. } else {
  8388. extend(e, this.getCoordinates(e));
  8389. // fire a click event in the chart
  8390. if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) {
  8391. fireEvent(chart, 'click', e);
  8392. }
  8393. }
  8394. }
  8395. },
  8396. onContainerTouchStart: function (e) {
  8397. var chart = this.chart;
  8398. if (e.touches.length === 1) {
  8399. e = this.normalize(e);
  8400. if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
  8401. // Prevent the click pseudo event from firing unless it is set in the options
  8402. /*if (!chart.runChartClick) {
  8403. e.preventDefault();
  8404. }*/
  8405. // Run mouse events and display tooltip etc
  8406. this.runPointActions(e);
  8407. this.pinch(e);
  8408. } else {
  8409. // Hide the tooltip on touching outside the plot area (#1203)
  8410. this.reset();
  8411. }
  8412. } else if (e.touches.length === 2) {
  8413. this.pinch(e);
  8414. }
  8415. },
  8416. onContainerTouchMove: function (e) {
  8417. if (e.touches.length === 1 || e.touches.length === 2) {
  8418. this.pinch(e);
  8419. }
  8420. },
  8421. onDocumentTouchEnd: function (e) {
  8422. this.drop(e);
  8423. },
  8424. /**
  8425. * Set the JS DOM events on the container and document. This method should contain
  8426. * a one-to-one assignment between methods and their handlers. Any advanced logic should
  8427. * be moved to the handler reflecting the event's name.
  8428. */
  8429. setDOMEvents: function () {
  8430. var pointer = this,
  8431. container = pointer.chart.container,
  8432. events;
  8433. this._events = events = [
  8434. [container, 'onmousedown', 'onContainerMouseDown'],
  8435. [container, 'onmousemove', 'onContainerMouseMove'],
  8436. [container, 'onclick', 'onContainerClick'],
  8437. [container, 'mouseleave', 'onContainerMouseLeave'],
  8438. [doc, 'mousemove', 'onDocumentMouseMove'],
  8439. [doc, 'mouseup', 'onDocumentMouseUp']
  8440. ];
  8441. if (hasTouch) {
  8442. events.push(
  8443. [container, 'ontouchstart', 'onContainerTouchStart'],
  8444. [container, 'ontouchmove', 'onContainerTouchMove'],
  8445. [doc, 'touchend', 'onDocumentTouchEnd']
  8446. );
  8447. }
  8448. each(events, function (eventConfig) {
  8449. // First, create the callback function that in turn calls the method on Pointer
  8450. pointer['_' + eventConfig[2]] = function (e) {
  8451. pointer[eventConfig[2]](e);
  8452. };
  8453. // Now attach the function, either as a direct property or through addEvent
  8454. if (eventConfig[1].indexOf('on') === 0) {
  8455. eventConfig[0][eventConfig[1]] = pointer['_' + eventConfig[2]];
  8456. } else {
  8457. addEvent(eventConfig[0], eventConfig[1], pointer['_' + eventConfig[2]]);
  8458. }
  8459. });
  8460. },
  8461. /**
  8462. * Destroys the Pointer object and disconnects DOM events.
  8463. */
  8464. destroy: function () {
  8465. var pointer = this;
  8466. // Release all DOM events
  8467. each(pointer._events, function (eventConfig) {
  8468. if (eventConfig[1].indexOf('on') === 0) {
  8469. eventConfig[0][eventConfig[1]] = null; // delete breaks oldIE
  8470. } else {
  8471. removeEvent(eventConfig[0], eventConfig[1], pointer['_' + eventConfig[2]]);
  8472. }
  8473. });
  8474. delete pointer._events;
  8475. // memory and CPU leak
  8476. clearInterval(pointer.tooltipTimeout);
  8477. }
  8478. };
  8479. /**
  8480. * The overview of the chart's series
  8481. */
  8482. function Legend(chart, options) {
  8483. this.init(chart, options);
  8484. }
  8485. Legend.prototype = {
  8486. /**
  8487. * Initialize the legend
  8488. */
  8489. init: function (chart, options) {
  8490. var legend = this,
  8491. itemStyle = options.itemStyle,
  8492. padding = pick(options.padding, 8),
  8493. itemMarginTop = options.itemMarginTop || 0;
  8494. this.options = options;
  8495. if (!options.enabled) {
  8496. return;
  8497. }
  8498. legend.baseline = pInt(itemStyle.fontSize) + 3 + itemMarginTop; // used in Series prototype
  8499. legend.itemStyle = itemStyle;
  8500. legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle);
  8501. legend.itemMarginTop = itemMarginTop;
  8502. legend.padding = padding;
  8503. legend.initialItemX = padding;
  8504. legend.initialItemY = padding - 5; // 5 is the number of pixels above the text
  8505. legend.maxItemWidth = 0;
  8506. legend.chart = chart;
  8507. legend.itemHeight = 0;
  8508. legend.lastLineHeight = 0;
  8509. // Render it
  8510. legend.render();
  8511. // move checkboxes
  8512. addEvent(legend.chart, 'endResize', function () {
  8513. legend.positionCheckboxes();
  8514. });
  8515. },
  8516. /**
  8517. * Set the colors for the legend item
  8518. * @param {Object} item A Series or Point instance
  8519. * @param {Object} visible Dimmed or colored
  8520. */
  8521. colorizeItem: function (item, visible) {
  8522. var legend = this,
  8523. options = legend.options,
  8524. legendItem = item.legendItem,
  8525. legendLine = item.legendLine,
  8526. legendSymbol = item.legendSymbol,
  8527. hiddenColor = legend.itemHiddenStyle.color,
  8528. textColor = visible ? options.itemStyle.color : hiddenColor,
  8529. symbolColor = visible ? item.color : hiddenColor,
  8530. markerOptions = item.options && item.options.marker,
  8531. symbolAttr = {
  8532. stroke: symbolColor,
  8533. fill: symbolColor
  8534. },
  8535. key,
  8536. val;
  8537. if (legendItem) {
  8538. legendItem.css({ fill: textColor, color: textColor }); // color for #1553, oldIE
  8539. }
  8540. if (legendLine) {
  8541. legendLine.attr({ stroke: symbolColor });
  8542. }
  8543. if (legendSymbol) {
  8544. // Apply marker options
  8545. if (markerOptions && legendSymbol.isMarker) { // #585
  8546. markerOptions = item.convertAttribs(markerOptions);
  8547. for (key in markerOptions) {
  8548. val = markerOptions[key];
  8549. if (val !== UNDEFINED) {
  8550. symbolAttr[key] = val;
  8551. }
  8552. }
  8553. }
  8554. legendSymbol.attr(symbolAttr);
  8555. }
  8556. },
  8557. /**
  8558. * Position the legend item
  8559. * @param {Object} item A Series or Point instance
  8560. */
  8561. positionItem: function (item) {
  8562. var legend = this,
  8563. options = legend.options,
  8564. symbolPadding = options.symbolPadding,
  8565. ltr = !options.rtl,
  8566. legendItemPos = item._legendItemPos,
  8567. itemX = legendItemPos[0],
  8568. itemY = legendItemPos[1],
  8569. checkbox = item.checkbox;
  8570. if (item.legendGroup) {
  8571. item.legendGroup.translate(
  8572. ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4,
  8573. itemY
  8574. );
  8575. }
  8576. if (checkbox) {
  8577. checkbox.x = itemX;
  8578. checkbox.y = itemY;
  8579. }
  8580. },
  8581. /**
  8582. * Destroy a single legend item
  8583. * @param {Object} item The series or point
  8584. */
  8585. destroyItem: function (item) {
  8586. var checkbox = item.checkbox;
  8587. // destroy SVG elements
  8588. each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) {
  8589. if (item[key]) {
  8590. item[key] = item[key].destroy();
  8591. }
  8592. });
  8593. if (checkbox) {
  8594. discardElement(item.checkbox);
  8595. }
  8596. },
  8597. /**
  8598. * Destroys the legend.
  8599. */
  8600. destroy: function () {
  8601. var legend = this,
  8602. legendGroup = legend.group,
  8603. box = legend.box;
  8604. if (box) {
  8605. legend.box = box.destroy();
  8606. }
  8607. if (legendGroup) {
  8608. legend.group = legendGroup.destroy();
  8609. }
  8610. },
  8611. /**
  8612. * Position the checkboxes after the width is determined
  8613. */
  8614. positionCheckboxes: function (scrollOffset) {
  8615. var alignAttr = this.group.alignAttr,
  8616. translateY,
  8617. clipHeight = this.clipHeight || this.legendHeight;
  8618. if (alignAttr) {
  8619. translateY = alignAttr.translateY;
  8620. each(this.allItems, function (item) {
  8621. var checkbox = item.checkbox,
  8622. top;
  8623. if (checkbox) {
  8624. top = (translateY + checkbox.y + (scrollOffset || 0) + 3);
  8625. css(checkbox, {
  8626. left: (alignAttr.translateX + item.legendItemWidth + checkbox.x - 20) + PX,
  8627. top: top + PX,
  8628. display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE
  8629. });
  8630. }
  8631. });
  8632. }
  8633. },
  8634. /**
  8635. * Render the legend title on top of the legend
  8636. */
  8637. renderTitle: function () {
  8638. var options = this.options,
  8639. padding = this.padding,
  8640. titleOptions = options.title,
  8641. titleHeight = 0,
  8642. bBox;
  8643. if (titleOptions.text) {
  8644. if (!this.title) {
  8645. this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title')
  8646. .attr({ zIndex: 1 })
  8647. .css(titleOptions.style)
  8648. .add(this.group);
  8649. }
  8650. bBox = this.title.getBBox();
  8651. titleHeight = bBox.height;
  8652. this.offsetWidth = bBox.width; // #1717
  8653. this.contentGroup.attr({ translateY: titleHeight });
  8654. }
  8655. this.titleHeight = titleHeight;
  8656. },
  8657. /**
  8658. * Render a single specific legend item
  8659. * @param {Object} item A series or point
  8660. */
  8661. renderItem: function (item) {
  8662. var legend = this,
  8663. chart = legend.chart,
  8664. renderer = chart.renderer,
  8665. options = legend.options,
  8666. horizontal = options.layout === 'horizontal',
  8667. symbolWidth = options.symbolWidth,
  8668. symbolPadding = options.symbolPadding,
  8669. itemStyle = legend.itemStyle,
  8670. itemHiddenStyle = legend.itemHiddenStyle,
  8671. padding = legend.padding,
  8672. itemDistance = horizontal ? pick(options.itemDistance, 8) : 0,
  8673. ltr = !options.rtl,
  8674. itemHeight,
  8675. widthOption = options.width,
  8676. itemMarginBottom = options.itemMarginBottom || 0,
  8677. itemMarginTop = legend.itemMarginTop,
  8678. initialItemX = legend.initialItemX,
  8679. bBox,
  8680. itemWidth,
  8681. li = item.legendItem,
  8682. series = item.series || item,
  8683. itemOptions = series.options,
  8684. showCheckbox = itemOptions.showCheckbox,
  8685. useHTML = options.useHTML;
  8686. if (!li) { // generate it once, later move it
  8687. // Generate the group box
  8688. // A group to hold the symbol and text. Text is to be appended in Legend class.
  8689. item.legendGroup = renderer.g('legend-item')
  8690. .attr({ zIndex: 1 })
  8691. .add(legend.scrollGroup);
  8692. // Draw the legend symbol inside the group box
  8693. series.drawLegendSymbol(legend, item);
  8694. // Generate the list item text and add it to the group
  8695. item.legendItem = li = renderer.text(
  8696. options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item),
  8697. ltr ? symbolWidth + symbolPadding : -symbolPadding,
  8698. legend.baseline,
  8699. useHTML
  8700. )
  8701. .css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021)
  8702. .attr({
  8703. align: ltr ? 'left' : 'right',
  8704. zIndex: 2
  8705. })
  8706. .add(item.legendGroup);
  8707. // Set the events on the item group, or in case of useHTML, the item itself (#1249)
  8708. (useHTML ? li : item.legendGroup).on('mouseover', function () {
  8709. item.setState(HOVER_STATE);
  8710. li.css(legend.options.itemHoverStyle);
  8711. })
  8712. .on('mouseout', function () {
  8713. li.css(item.visible ? itemStyle : itemHiddenStyle);
  8714. item.setState();
  8715. })
  8716. .on('click', function (event) {
  8717. var strLegendItemClick = 'legendItemClick',
  8718. fnLegendItemClick = function () {
  8719. item.setVisible();
  8720. };
  8721. // Pass over the click/touch event. #4.
  8722. event = {
  8723. browserEvent: event
  8724. };
  8725. // click the name or symbol
  8726. if (item.firePointEvent) { // point
  8727. item.firePointEvent(strLegendItemClick, event, fnLegendItemClick);
  8728. } else {
  8729. fireEvent(item, strLegendItemClick, event, fnLegendItemClick);
  8730. }
  8731. });
  8732. // Colorize the items
  8733. legend.colorizeItem(item, item.visible);
  8734. // add the HTML checkbox on top
  8735. if (itemOptions && showCheckbox) {
  8736. item.checkbox = createElement('input', {
  8737. type: 'checkbox',
  8738. checked: item.selected,
  8739. defaultChecked: item.selected // required by IE7
  8740. }, options.itemCheckboxStyle, chart.container);
  8741. addEvent(item.checkbox, 'click', function (event) {
  8742. var target = event.target;
  8743. fireEvent(item, 'checkboxClick', {
  8744. checked: target.checked
  8745. },
  8746. function () {
  8747. item.select();
  8748. }
  8749. );
  8750. });
  8751. }
  8752. }
  8753. // calculate the positions for the next line
  8754. bBox = li.getBBox();
  8755. itemWidth = item.legendItemWidth =
  8756. options.itemWidth || symbolWidth + symbolPadding + bBox.width + itemDistance +
  8757. (showCheckbox ? 20 : 0);
  8758. legend.itemHeight = itemHeight = bBox.height;
  8759. // if the item exceeds the width, start a new line
  8760. if (horizontal && legend.itemX - initialItemX + itemWidth >
  8761. (widthOption || (chart.chartWidth - 2 * padding - initialItemX))) {
  8762. legend.itemX = initialItemX;
  8763. legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom;
  8764. legend.lastLineHeight = 0; // reset for next line
  8765. }
  8766. // If the item exceeds the height, start a new column
  8767. /*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) {
  8768. legend.itemY = legend.initialItemY;
  8769. legend.itemX += legend.maxItemWidth;
  8770. legend.maxItemWidth = 0;
  8771. }*/
  8772. // Set the edge positions
  8773. legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth);
  8774. legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom;
  8775. legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915
  8776. // cache the position of the newly generated or reordered items
  8777. item._legendItemPos = [legend.itemX, legend.itemY];
  8778. // advance
  8779. if (horizontal) {
  8780. legend.itemX += itemWidth;
  8781. } else {
  8782. legend.itemY += itemMarginTop + itemHeight + itemMarginBottom;
  8783. legend.lastLineHeight = itemHeight;
  8784. }
  8785. // the width of the widest item
  8786. legend.offsetWidth = widthOption || mathMax(
  8787. (horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding,
  8788. legend.offsetWidth
  8789. );
  8790. },
  8791. /**
  8792. * Render the legend. This method can be called both before and after
  8793. * chart.render. If called after, it will only rearrange items instead
  8794. * of creating new ones.
  8795. */
  8796. render: function () {
  8797. var legend = this,
  8798. chart = legend.chart,
  8799. renderer = chart.renderer,
  8800. legendGroup = legend.group,
  8801. allItems,
  8802. display,
  8803. legendWidth,
  8804. legendHeight,
  8805. box = legend.box,
  8806. options = legend.options,
  8807. padding = legend.padding,
  8808. legendBorderWidth = options.borderWidth,
  8809. legendBackgroundColor = options.backgroundColor;
  8810. legend.itemX = legend.initialItemX;
  8811. legend.itemY = legend.initialItemY;
  8812. legend.offsetWidth = 0;
  8813. legend.lastItemY = 0;
  8814. if (!legendGroup) {
  8815. legend.group = legendGroup = renderer.g('legend')
  8816. .attr({ zIndex: 7 })
  8817. .add();
  8818. legend.contentGroup = renderer.g()
  8819. .attr({ zIndex: 1 }) // above background
  8820. .add(legendGroup);
  8821. legend.scrollGroup = renderer.g()
  8822. .add(legend.contentGroup);
  8823. }
  8824. legend.renderTitle();
  8825. // add each series or point
  8826. allItems = [];
  8827. each(chart.series, function (serie) {
  8828. var seriesOptions = serie.options;
  8829. if (!seriesOptions.showInLegend || defined(seriesOptions.linkedTo)) {
  8830. return;
  8831. }
  8832. // use points or series for the legend item depending on legendType
  8833. allItems = allItems.concat(
  8834. serie.legendItems ||
  8835. (seriesOptions.legendType === 'point' ?
  8836. serie.data :
  8837. serie)
  8838. );
  8839. });
  8840. // sort by legendIndex
  8841. stableSort(allItems, function (a, b) {
  8842. return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0);
  8843. });
  8844. // reversed legend
  8845. if (options.reversed) {
  8846. allItems.reverse();
  8847. }
  8848. legend.allItems = allItems;
  8849. legend.display = display = !!allItems.length;
  8850. // render the items
  8851. each(allItems, function (item) {
  8852. legend.renderItem(item);
  8853. });
  8854. // Draw the border
  8855. legendWidth = options.width || legend.offsetWidth;
  8856. legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight;
  8857. legendHeight = legend.handleOverflow(legendHeight);
  8858. if (legendBorderWidth || legendBackgroundColor) {
  8859. legendWidth += padding;
  8860. legendHeight += padding;
  8861. if (!box) {
  8862. legend.box = box = renderer.rect(
  8863. 0,
  8864. 0,
  8865. legendWidth,
  8866. legendHeight,
  8867. options.borderRadius,
  8868. legendBorderWidth || 0
  8869. ).attr({
  8870. stroke: options.borderColor,
  8871. 'stroke-width': legendBorderWidth || 0,
  8872. fill: legendBackgroundColor || NONE
  8873. })
  8874. .add(legendGroup)
  8875. .shadow(options.shadow);
  8876. box.isNew = true;
  8877. } else if (legendWidth > 0 && legendHeight > 0) {
  8878. box[box.isNew ? 'attr' : 'animate'](
  8879. box.crisp(null, null, null, legendWidth, legendHeight)
  8880. );
  8881. box.isNew = false;
  8882. }
  8883. // hide the border if no items
  8884. box[display ? 'show' : 'hide']();
  8885. }
  8886. legend.legendWidth = legendWidth;
  8887. legend.legendHeight = legendHeight;
  8888. // Now that the legend width and height are established, put the items in the
  8889. // final position
  8890. each(allItems, function (item) {
  8891. legend.positionItem(item);
  8892. });
  8893. // 1.x compatibility: positioning based on style
  8894. /*var props = ['left', 'right', 'top', 'bottom'],
  8895. prop,
  8896. i = 4;
  8897. while (i--) {
  8898. prop = props[i];
  8899. if (options.style[prop] && options.style[prop] !== 'auto') {
  8900. options[i < 2 ? 'align' : 'verticalAlign'] = prop;
  8901. options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1);
  8902. }
  8903. }*/
  8904. if (display) {
  8905. legendGroup.align(extend({
  8906. width: legendWidth,
  8907. height: legendHeight
  8908. }, options), true, 'spacingBox');
  8909. }
  8910. if (!chart.isResizing) {
  8911. this.positionCheckboxes();
  8912. }
  8913. },
  8914. /**
  8915. * Set up the overflow handling by adding navigation with up and down arrows below the
  8916. * legend.
  8917. */
  8918. handleOverflow: function (legendHeight) {
  8919. var legend = this,
  8920. chart = this.chart,
  8921. renderer = chart.renderer,
  8922. pageCount,
  8923. options = this.options,
  8924. optionsY = options.y,
  8925. alignTop = options.verticalAlign === 'top',
  8926. spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding,
  8927. maxHeight = options.maxHeight,
  8928. clipHeight,
  8929. clipRect = this.clipRect,
  8930. navOptions = options.navigation,
  8931. animation = pick(navOptions.animation, true),
  8932. arrowSize = navOptions.arrowSize || 12,
  8933. nav = this.nav;
  8934. // Adjust the height
  8935. if (options.layout === 'horizontal') {
  8936. spaceHeight /= 2;
  8937. }
  8938. if (maxHeight) {
  8939. spaceHeight = mathMin(spaceHeight, maxHeight);
  8940. }
  8941. // Reset the legend height and adjust the clipping rectangle
  8942. if (legendHeight > spaceHeight && !options.useHTML) {
  8943. this.clipHeight = clipHeight = spaceHeight - 20 - this.titleHeight;
  8944. this.pageCount = pageCount = mathCeil(legendHeight / clipHeight);
  8945. this.currentPage = pick(this.currentPage, 1);
  8946. this.fullHeight = legendHeight;
  8947. // Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787)
  8948. if (!clipRect) {
  8949. clipRect = legend.clipRect = renderer.clipRect(0, 0, 9999, 0);
  8950. legend.contentGroup.clip(clipRect);
  8951. }
  8952. clipRect.attr({
  8953. height: clipHeight
  8954. });
  8955. // Add navigation elements
  8956. if (!nav) {
  8957. this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group);
  8958. this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize)
  8959. .on('click', function () {
  8960. legend.scroll(-1, animation);
  8961. })
  8962. .add(nav);
  8963. this.pager = renderer.text('', 15, 10)
  8964. .css(navOptions.style)
  8965. .add(nav);
  8966. this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize)
  8967. .on('click', function () {
  8968. legend.scroll(1, animation);
  8969. })
  8970. .add(nav);
  8971. }
  8972. // Set initial position
  8973. legend.scroll(0);
  8974. legendHeight = spaceHeight;
  8975. } else if (nav) {
  8976. clipRect.attr({
  8977. height: chart.chartHeight
  8978. });
  8979. nav.hide();
  8980. this.scrollGroup.attr({
  8981. translateY: 1
  8982. });
  8983. this.clipHeight = 0; // #1379
  8984. }
  8985. return legendHeight;
  8986. },
  8987. /**
  8988. * Scroll the legend by a number of pages
  8989. * @param {Object} scrollBy
  8990. * @param {Object} animation
  8991. */
  8992. scroll: function (scrollBy, animation) {
  8993. var pageCount = this.pageCount,
  8994. currentPage = this.currentPage + scrollBy,
  8995. clipHeight = this.clipHeight,
  8996. navOptions = this.options.navigation,
  8997. activeColor = navOptions.activeColor,
  8998. inactiveColor = navOptions.inactiveColor,
  8999. pager = this.pager,
  9000. padding = this.padding,
  9001. scrollOffset;
  9002. // When resizing while looking at the last page
  9003. if (currentPage > pageCount) {
  9004. currentPage = pageCount;
  9005. }
  9006. if (currentPage > 0) {
  9007. if (animation !== UNDEFINED) {
  9008. setAnimation(animation, this.chart);
  9009. }
  9010. this.nav.attr({
  9011. translateX: padding,
  9012. translateY: clipHeight + 7 + this.titleHeight,
  9013. visibility: VISIBLE
  9014. });
  9015. this.up.attr({
  9016. fill: currentPage === 1 ? inactiveColor : activeColor
  9017. })
  9018. .css({
  9019. cursor: currentPage === 1 ? 'default' : 'pointer'
  9020. });
  9021. pager.attr({
  9022. text: currentPage + '/' + this.pageCount
  9023. });
  9024. this.down.attr({
  9025. x: 18 + this.pager.getBBox().width, // adjust to text width
  9026. fill: currentPage === pageCount ? inactiveColor : activeColor
  9027. })
  9028. .css({
  9029. cursor: currentPage === pageCount ? 'default' : 'pointer'
  9030. });
  9031. scrollOffset = -mathMin(clipHeight * (currentPage - 1), this.fullHeight - clipHeight + padding) + 1;
  9032. this.scrollGroup.animate({
  9033. translateY: scrollOffset
  9034. });
  9035. pager.attr({
  9036. text: currentPage + '/' + pageCount
  9037. });
  9038. this.currentPage = currentPage;
  9039. this.positionCheckboxes(scrollOffset);
  9040. }
  9041. }
  9042. };
  9043. // Workaround for #2030, horizontal legend items not displaying in IE11 Preview.
  9044. // TODO: When IE11 is released, check again for this bug, and remove the fix
  9045. // or make a better one.
  9046. if (/Trident.*?11\.0/.test(userAgent)) {
  9047. wrap(Legend.prototype, 'positionItem', function (proceed, item) {
  9048. var legend = this;
  9049. setTimeout(function () {
  9050. proceed.call(legend, item);
  9051. });
  9052. });
  9053. }
  9054. /**
  9055. * The chart class
  9056. * @param {Object} options
  9057. * @param {Function} callback Function to run when the chart has loaded
  9058. */
  9059. function Chart() {
  9060. this.init.apply(this, arguments);
  9061. }
  9062. Chart.prototype = {
  9063. /**
  9064. * Initialize the chart
  9065. */
  9066. init: function (userOptions, callback) {
  9067. // Handle regular options
  9068. var options,
  9069. seriesOptions = userOptions.series; // skip merging data points to increase performance
  9070. userOptions.series = null;
  9071. options = merge(defaultOptions, userOptions); // do the merge
  9072. options.series = userOptions.series = seriesOptions; // set back the series data
  9073. var optionsChart = options.chart;
  9074. // Create margin & spacing array
  9075. this.margin = this.splashArray('margin', optionsChart);
  9076. this.spacing = this.splashArray('spacing', optionsChart);
  9077. var chartEvents = optionsChart.events;
  9078. //this.runChartClick = chartEvents && !!chartEvents.click;
  9079. this.bounds = { h: {}, v: {} }; // Pixel data bounds for touch zoom
  9080. this.callback = callback;
  9081. this.isResizing = 0;
  9082. this.options = options;
  9083. //chartTitleOptions = UNDEFINED;
  9084. //chartSubtitleOptions = UNDEFINED;
  9085. this.axes = [];
  9086. this.series = [];
  9087. this.hasCartesianSeries = optionsChart.showAxes;
  9088. //this.axisOffset = UNDEFINED;
  9089. //this.maxTicks = UNDEFINED; // handle the greatest amount of ticks on grouped axes
  9090. //this.inverted = UNDEFINED;
  9091. //this.loadingShown = UNDEFINED;
  9092. //this.container = UNDEFINED;
  9093. //this.chartWidth = UNDEFINED;
  9094. //this.chartHeight = UNDEFINED;
  9095. //this.marginRight = UNDEFINED;
  9096. //this.marginBottom = UNDEFINED;
  9097. //this.containerWidth = UNDEFINED;
  9098. //this.containerHeight = UNDEFINED;
  9099. //this.oldChartWidth = UNDEFINED;
  9100. //this.oldChartHeight = UNDEFINED;
  9101. //this.renderTo = UNDEFINED;
  9102. //this.renderToClone = UNDEFINED;
  9103. //this.spacingBox = UNDEFINED
  9104. //this.legend = UNDEFINED;
  9105. // Elements
  9106. //this.chartBackground = UNDEFINED;
  9107. //this.plotBackground = UNDEFINED;
  9108. //this.plotBGImage = UNDEFINED;
  9109. //this.plotBorder = UNDEFINED;
  9110. //this.loadingDiv = UNDEFINED;
  9111. //this.loadingSpan = UNDEFINED;
  9112. var chart = this,
  9113. eventType;
  9114. // Add the chart to the global lookup
  9115. chart.index = charts.length;
  9116. charts.push(chart);
  9117. // Set up auto resize
  9118. if (optionsChart.reflow !== false) {
  9119. addEvent(chart, 'load', function () {
  9120. chart.initReflow();
  9121. });
  9122. }
  9123. // Chart event handlers
  9124. if (chartEvents) {
  9125. for (eventType in chartEvents) {
  9126. addEvent(chart, eventType, chartEvents[eventType]);
  9127. }
  9128. }
  9129. chart.xAxis = [];
  9130. chart.yAxis = [];
  9131. // Expose methods and variables
  9132. chart.animation = useCanVG ? false : pick(optionsChart.animation, true);
  9133. chart.pointCount = 0;
  9134. chart.counters = new ChartCounters();
  9135. chart.firstRender();
  9136. },
  9137. /**
  9138. * Initialize an individual series, called internally before render time
  9139. */
  9140. initSeries: function (options) {
  9141. var chart = this,
  9142. optionsChart = chart.options.chart,
  9143. type = options.type || optionsChart.type || optionsChart.defaultSeriesType,
  9144. series,
  9145. constr = seriesTypes[type];
  9146. // No such series type
  9147. if (!constr) {
  9148. error(17, true);
  9149. }
  9150. series = new constr();
  9151. series.init(this, options);
  9152. return series;
  9153. },
  9154. /**
  9155. * Add a series dynamically after time
  9156. *
  9157. * @param {Object} options The config options
  9158. * @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true.
  9159. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  9160. * configuration
  9161. *
  9162. * @return {Object} series The newly created series object
  9163. */
  9164. addSeries: function (options, redraw, animation) {
  9165. var series,
  9166. chart = this;
  9167. if (options) {
  9168. redraw = pick(redraw, true); // defaults to true
  9169. fireEvent(chart, 'addSeries', { options: options }, function () {
  9170. series = chart.initSeries(options);
  9171. chart.isDirtyLegend = true; // the series array is out of sync with the display
  9172. chart.linkSeries();
  9173. if (redraw) {
  9174. chart.redraw(animation);
  9175. }
  9176. });
  9177. }
  9178. return series;
  9179. },
  9180. /**
  9181. * Add an axis to the chart
  9182. * @param {Object} options The axis option
  9183. * @param {Boolean} isX Whether it is an X axis or a value axis
  9184. */
  9185. addAxis: function (options, isX, redraw, animation) {
  9186. var key = isX ? 'xAxis' : 'yAxis',
  9187. chartOptions = this.options,
  9188. axis;
  9189. /*jslint unused: false*/
  9190. axis = new Axis(this, merge(options, {
  9191. index: this[key].length,
  9192. isX: isX
  9193. }));
  9194. /*jslint unused: true*/
  9195. // Push the new axis options to the chart options
  9196. chartOptions[key] = splat(chartOptions[key] || {});
  9197. chartOptions[key].push(options);
  9198. if (pick(redraw, true)) {
  9199. this.redraw(animation);
  9200. }
  9201. },
  9202. /**
  9203. * Check whether a given point is within the plot area
  9204. *
  9205. * @param {Number} plotX Pixel x relative to the plot area
  9206. * @param {Number} plotY Pixel y relative to the plot area
  9207. * @param {Boolean} inverted Whether the chart is inverted
  9208. */
  9209. isInsidePlot: function (plotX, plotY, inverted) {
  9210. var x = inverted ? plotY : plotX,
  9211. y = inverted ? plotX : plotY;
  9212. return x >= 0 &&
  9213. x <= this.plotWidth &&
  9214. y >= 0 &&
  9215. y <= this.plotHeight;
  9216. },
  9217. /**
  9218. * Adjust all axes tick amounts
  9219. */
  9220. adjustTickAmounts: function () {
  9221. if (this.options.chart.alignTicks !== false) {
  9222. each(this.axes, function (axis) {
  9223. axis.adjustTickAmount();
  9224. });
  9225. }
  9226. this.maxTicks = null;
  9227. },
  9228. /**
  9229. * Redraw legend, axes or series based on updated data
  9230. *
  9231. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  9232. * configuration
  9233. */
  9234. redraw: function (animation) {
  9235. var chart = this,
  9236. axes = chart.axes,
  9237. series = chart.series,
  9238. pointer = chart.pointer,
  9239. legend = chart.legend,
  9240. redrawLegend = chart.isDirtyLegend,
  9241. hasStackedSeries,
  9242. hasDirtyStacks,
  9243. isDirtyBox = chart.isDirtyBox, // todo: check if it has actually changed?
  9244. seriesLength = series.length,
  9245. i = seriesLength,
  9246. serie,
  9247. renderer = chart.renderer,
  9248. isHiddenChart = renderer.isHidden(),
  9249. afterRedraw = [];
  9250. setAnimation(animation, chart);
  9251. if (isHiddenChart) {
  9252. chart.cloneRenderTo();
  9253. }
  9254. // Adjust title layout (reflow multiline text)
  9255. chart.layOutTitles();
  9256. // link stacked series
  9257. while (i--) {
  9258. serie = series[i];
  9259. if (serie.options.stacking) {
  9260. hasStackedSeries = true;
  9261. if (serie.isDirty) {
  9262. hasDirtyStacks = true;
  9263. break;
  9264. }
  9265. }
  9266. }
  9267. if (hasDirtyStacks) { // mark others as dirty
  9268. i = seriesLength;
  9269. while (i--) {
  9270. serie = series[i];
  9271. if (serie.options.stacking) {
  9272. serie.isDirty = true;
  9273. }
  9274. }
  9275. }
  9276. // handle updated data in the series
  9277. each(series, function (serie) {
  9278. if (serie.isDirty) { // prepare the data so axis can read it
  9279. if (serie.options.legendType === 'point') {
  9280. redrawLegend = true;
  9281. }
  9282. }
  9283. });
  9284. // handle added or removed series
  9285. if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed
  9286. // draw legend graphics
  9287. legend.render();
  9288. chart.isDirtyLegend = false;
  9289. }
  9290. // reset stacks
  9291. if (hasStackedSeries) {
  9292. chart.getStacks();
  9293. }
  9294. if (chart.hasCartesianSeries) {
  9295. if (!chart.isResizing) {
  9296. // reset maxTicks
  9297. chart.maxTicks = null;
  9298. // set axes scales
  9299. each(axes, function (axis) {
  9300. axis.setScale();
  9301. });
  9302. }
  9303. chart.adjustTickAmounts();
  9304. chart.getMargins();
  9305. // If one axis is dirty, all axes must be redrawn (#792, #2169)
  9306. each(axes, function (axis) {
  9307. if (axis.isDirty) {
  9308. isDirtyBox = true;
  9309. }
  9310. });
  9311. // redraw axes
  9312. each(axes, function (axis) {
  9313. // Fire 'afterSetExtremes' only if extremes are set
  9314. if (axis.isDirtyExtremes) { // #821
  9315. axis.isDirtyExtremes = false;
  9316. afterRedraw.push(function () { // prevent a recursive call to chart.redraw() (#1119)
  9317. fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751
  9318. delete axis.eventArgs;
  9319. });
  9320. }
  9321. if (isDirtyBox || hasStackedSeries) {
  9322. axis.redraw();
  9323. }
  9324. });
  9325. }
  9326. // the plot areas size has changed
  9327. if (isDirtyBox) {
  9328. chart.drawChartBox();
  9329. }
  9330. // redraw affected series
  9331. each(series, function (serie) {
  9332. if (serie.isDirty && serie.visible &&
  9333. (!serie.isCartesian || serie.xAxis)) { // issue #153
  9334. serie.redraw();
  9335. }
  9336. });
  9337. // move tooltip or reset
  9338. if (pointer && pointer.reset) {
  9339. pointer.reset(true);
  9340. }
  9341. // redraw if canvas
  9342. renderer.draw();
  9343. // fire the event
  9344. fireEvent(chart, 'redraw'); // jQuery breaks this when calling it from addEvent. Overwrites chart.redraw
  9345. if (isHiddenChart) {
  9346. chart.cloneRenderTo(true);
  9347. }
  9348. // Fire callbacks that are put on hold until after the redraw
  9349. each(afterRedraw, function (callback) {
  9350. callback.call();
  9351. });
  9352. },
  9353. /**
  9354. * Dim the chart and show a loading text or symbol
  9355. * @param {String} str An optional text to show in the loading label instead of the default one
  9356. */
  9357. showLoading: function (str) {
  9358. var chart = this,
  9359. options = chart.options,
  9360. loadingDiv = chart.loadingDiv;
  9361. var loadingOptions = options.loading;
  9362. // create the layer at the first call
  9363. if (!loadingDiv) {
  9364. chart.loadingDiv = loadingDiv = createElement(DIV, {
  9365. className: PREFIX + 'loading'
  9366. }, extend(loadingOptions.style, {
  9367. zIndex: 10,
  9368. display: NONE
  9369. }), chart.container);
  9370. chart.loadingSpan = createElement(
  9371. 'span',
  9372. null,
  9373. loadingOptions.labelStyle,
  9374. loadingDiv
  9375. );
  9376. }
  9377. // update text
  9378. chart.loadingSpan.innerHTML = str || options.lang.loading;
  9379. // show it
  9380. if (!chart.loadingShown) {
  9381. css(loadingDiv, {
  9382. opacity: 0,
  9383. display: '',
  9384. left: chart.plotLeft + PX,
  9385. top: chart.plotTop + PX,
  9386. width: chart.plotWidth + PX,
  9387. height: chart.plotHeight + PX
  9388. });
  9389. animate(loadingDiv, {
  9390. opacity: loadingOptions.style.opacity
  9391. }, {
  9392. duration: loadingOptions.showDuration || 0
  9393. });
  9394. chart.loadingShown = true;
  9395. }
  9396. },
  9397. /**
  9398. * Hide the loading layer
  9399. */
  9400. hideLoading: function () {
  9401. var options = this.options,
  9402. loadingDiv = this.loadingDiv;
  9403. if (loadingDiv) {
  9404. animate(loadingDiv, {
  9405. opacity: 0
  9406. }, {
  9407. duration: options.loading.hideDuration || 100,
  9408. complete: function () {
  9409. css(loadingDiv, { display: NONE });
  9410. }
  9411. });
  9412. }
  9413. this.loadingShown = false;
  9414. },
  9415. /**
  9416. * Get an axis, series or point object by id.
  9417. * @param id {String} The id as given in the configuration options
  9418. */
  9419. get: function (id) {
  9420. var chart = this,
  9421. axes = chart.axes,
  9422. series = chart.series;
  9423. var i,
  9424. j,
  9425. points;
  9426. // search axes
  9427. for (i = 0; i < axes.length; i++) {
  9428. if (axes[i].options.id === id) {
  9429. return axes[i];
  9430. }
  9431. }
  9432. // search series
  9433. for (i = 0; i < series.length; i++) {
  9434. if (series[i].options.id === id) {
  9435. return series[i];
  9436. }
  9437. }
  9438. // search points
  9439. for (i = 0; i < series.length; i++) {
  9440. points = series[i].points || [];
  9441. for (j = 0; j < points.length; j++) {
  9442. if (points[j].id === id) {
  9443. return points[j];
  9444. }
  9445. }
  9446. }
  9447. return null;
  9448. },
  9449. /**
  9450. * Create the Axis instances based on the config options
  9451. */
  9452. getAxes: function () {
  9453. var chart = this,
  9454. options = this.options,
  9455. xAxisOptions = options.xAxis = splat(options.xAxis || {}),
  9456. yAxisOptions = options.yAxis = splat(options.yAxis || {}),
  9457. optionsArray,
  9458. axis;
  9459. // make sure the options are arrays and add some members
  9460. each(xAxisOptions, function (axis, i) {
  9461. axis.index = i;
  9462. axis.isX = true;
  9463. });
  9464. each(yAxisOptions, function (axis, i) {
  9465. axis.index = i;
  9466. });
  9467. // concatenate all axis options into one array
  9468. optionsArray = xAxisOptions.concat(yAxisOptions);
  9469. each(optionsArray, function (axisOptions) {
  9470. axis = new Axis(chart, axisOptions);
  9471. });
  9472. chart.adjustTickAmounts();
  9473. },
  9474. /**
  9475. * Get the currently selected points from all series
  9476. */
  9477. getSelectedPoints: function () {
  9478. var points = [];
  9479. each(this.series, function (serie) {
  9480. points = points.concat(grep(serie.points || [], function (point) {
  9481. return point.selected;
  9482. }));
  9483. });
  9484. return points;
  9485. },
  9486. /**
  9487. * Get the currently selected series
  9488. */
  9489. getSelectedSeries: function () {
  9490. return grep(this.series, function (serie) {
  9491. return serie.selected;
  9492. });
  9493. },
  9494. /**
  9495. * Generate stacks for each series and calculate stacks total values
  9496. */
  9497. getStacks: function () {
  9498. var chart = this;
  9499. // reset stacks for each yAxis
  9500. each(chart.yAxis, function (axis) {
  9501. if (axis.stacks && axis.hasVisibleSeries) {
  9502. axis.oldStacks = axis.stacks;
  9503. }
  9504. });
  9505. each(chart.series, function (series) {
  9506. if (series.options.stacking && (series.visible === true || chart.options.chart.ignoreHiddenSeries === false)) {
  9507. series.stackKey = series.type + pick(series.options.stack, '');
  9508. }
  9509. });
  9510. },
  9511. /**
  9512. * Display the zoom button
  9513. */
  9514. showResetZoom: function () {
  9515. var chart = this,
  9516. lang = defaultOptions.lang,
  9517. btnOptions = chart.options.chart.resetZoomButton,
  9518. theme = btnOptions.theme,
  9519. states = theme.states,
  9520. alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox';
  9521. this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, function () { chart.zoomOut(); }, theme, states && states.hover)
  9522. .attr({
  9523. align: btnOptions.position.align,
  9524. title: lang.resetZoomTitle
  9525. })
  9526. .add()
  9527. .align(btnOptions.position, false, alignTo);
  9528. },
  9529. /**
  9530. * Zoom out to 1:1
  9531. */
  9532. zoomOut: function () {
  9533. var chart = this;
  9534. fireEvent(chart, 'selection', { resetSelection: true }, function () {
  9535. chart.zoom();
  9536. });
  9537. },
  9538. /**
  9539. * Zoom into a given portion of the chart given by axis coordinates
  9540. * @param {Object} event
  9541. */
  9542. zoom: function (event) {
  9543. var chart = this,
  9544. hasZoomed,
  9545. pointer = chart.pointer,
  9546. displayButton = false,
  9547. resetZoomButton;
  9548. // If zoom is called with no arguments, reset the axes
  9549. if (!event || event.resetSelection) {
  9550. each(chart.axes, function (axis) {
  9551. hasZoomed = axis.zoom();
  9552. });
  9553. } else { // else, zoom in on all axes
  9554. each(event.xAxis.concat(event.yAxis), function (axisData) {
  9555. var axis = axisData.axis,
  9556. isXAxis = axis.isXAxis;
  9557. // don't zoom more than minRange
  9558. if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) {
  9559. hasZoomed = axis.zoom(axisData.min, axisData.max);
  9560. if (axis.displayBtn) {
  9561. displayButton = true;
  9562. }
  9563. }
  9564. });
  9565. }
  9566. // Show or hide the Reset zoom button
  9567. resetZoomButton = chart.resetZoomButton;
  9568. if (displayButton && !resetZoomButton) {
  9569. chart.showResetZoom();
  9570. } else if (!displayButton && isObject(resetZoomButton)) {
  9571. chart.resetZoomButton = resetZoomButton.destroy();
  9572. }
  9573. // Redraw
  9574. if (hasZoomed) {
  9575. chart.redraw(
  9576. pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation
  9577. );
  9578. }
  9579. },
  9580. /**
  9581. * Pan the chart by dragging the mouse across the pane. This function is called
  9582. * on mouse move, and the distance to pan is computed from chartX compared to
  9583. * the first chartX position in the dragging operation.
  9584. */
  9585. pan: function (e, panning) {
  9586. var chart = this,
  9587. hoverPoints = chart.hoverPoints,
  9588. doRedraw;
  9589. // remove active points for shared tooltip
  9590. if (hoverPoints) {
  9591. each(hoverPoints, function (point) {
  9592. point.setState();
  9593. });
  9594. }
  9595. each(panning === 'xy' ? [1, 0] : [1], function (isX) { // xy is used in maps
  9596. var mousePos = e[isX ? 'chartX' : 'chartY'],
  9597. axis = chart[isX ? 'xAxis' : 'yAxis'][0],
  9598. startPos = chart[isX ? 'mouseDownX' : 'mouseDownY'],
  9599. halfPointRange = (axis.pointRange || 0) / 2,
  9600. extremes = axis.getExtremes(),
  9601. newMin = axis.toValue(startPos - mousePos, true) + halfPointRange,
  9602. newMax = axis.toValue(startPos + chart[isX ? 'plotWidth' : 'plotHeight'] - mousePos, true) - halfPointRange;
  9603. if (axis.series.length && newMin > mathMin(extremes.dataMin, extremes.min) && newMax < mathMax(extremes.dataMax, extremes.max)) {
  9604. axis.setExtremes(newMin, newMax, false, false, { trigger: 'pan' });
  9605. doRedraw = true;
  9606. }
  9607. chart[isX ? 'mouseDownX' : 'mouseDownY'] = mousePos; // set new reference for next run
  9608. });
  9609. if (doRedraw) {
  9610. chart.redraw(false);
  9611. }
  9612. css(chart.container, { cursor: 'move' });
  9613. },
  9614. /**
  9615. * Show the title and subtitle of the chart
  9616. *
  9617. * @param titleOptions {Object} New title options
  9618. * @param subtitleOptions {Object} New subtitle options
  9619. *
  9620. */
  9621. setTitle: function (titleOptions, subtitleOptions) {
  9622. var chart = this,
  9623. options = chart.options,
  9624. chartTitleOptions,
  9625. chartSubtitleOptions;
  9626. chartTitleOptions = options.title = merge(options.title, titleOptions);
  9627. chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions);
  9628. // add title and subtitle
  9629. each([
  9630. ['title', titleOptions, chartTitleOptions],
  9631. ['subtitle', subtitleOptions, chartSubtitleOptions]
  9632. ], function (arr) {
  9633. var name = arr[0],
  9634. title = chart[name],
  9635. titleOptions = arr[1],
  9636. chartTitleOptions = arr[2];
  9637. if (title && titleOptions) {
  9638. chart[name] = title = title.destroy(); // remove old
  9639. }
  9640. if (chartTitleOptions && chartTitleOptions.text && !title) {
  9641. chart[name] = chart.renderer.text(
  9642. chartTitleOptions.text,
  9643. 0,
  9644. 0,
  9645. chartTitleOptions.useHTML
  9646. )
  9647. .attr({
  9648. align: chartTitleOptions.align,
  9649. 'class': PREFIX + name,
  9650. zIndex: chartTitleOptions.zIndex || 4
  9651. })
  9652. .css(chartTitleOptions.style)
  9653. .add();
  9654. }
  9655. });
  9656. chart.layOutTitles();
  9657. },
  9658. /**
  9659. * Lay out the chart titles and cache the full offset height for use in getMargins
  9660. */
  9661. layOutTitles: function () {
  9662. var titleOffset = 0,
  9663. title = this.title,
  9664. subtitle = this.subtitle,
  9665. options = this.options,
  9666. titleOptions = options.title,
  9667. subtitleOptions = options.subtitle,
  9668. autoWidth = this.spacingBox.width - 44; // 44 makes room for default context button
  9669. if (title) {
  9670. title
  9671. .css({ width: (titleOptions.width || autoWidth) + PX })
  9672. .align(extend({ y: 15 }, titleOptions), false, 'spacingBox');
  9673. if (!titleOptions.floating && !titleOptions.verticalAlign) {
  9674. titleOffset = title.getBBox().height;
  9675. // Adjust for browser consistency + backwards compat after #776 fix
  9676. if (titleOffset >= 18 && titleOffset <= 25) {
  9677. titleOffset = 15;
  9678. }
  9679. }
  9680. }
  9681. if (subtitle) {
  9682. subtitle
  9683. .css({ width: (subtitleOptions.width || autoWidth) + PX })
  9684. .align(extend({ y: titleOffset + titleOptions.margin }, subtitleOptions), false, 'spacingBox');
  9685. if (!subtitleOptions.floating && !subtitleOptions.verticalAlign) {
  9686. titleOffset = mathCeil(titleOffset + subtitle.getBBox().height);
  9687. }
  9688. }
  9689. this.titleOffset = titleOffset; // used in getMargins
  9690. },
  9691. /**
  9692. * Get chart width and height according to options and container size
  9693. */
  9694. getChartSize: function () {
  9695. var chart = this,
  9696. optionsChart = chart.options.chart,
  9697. renderTo = chart.renderToClone || chart.renderTo;
  9698. // get inner width and height from jQuery (#824)
  9699. chart.containerWidth = adapterRun(renderTo, 'width');
  9700. chart.containerHeight = adapterRun(renderTo, 'height');
  9701. chart.chartWidth = mathMax(0, optionsChart.width || chart.containerWidth || 600); // #1393, 1460
  9702. chart.chartHeight = mathMax(0, pick(optionsChart.height,
  9703. // the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7:
  9704. chart.containerHeight > 19 ? chart.containerHeight : 400));
  9705. },
  9706. /**
  9707. * Create a clone of the chart's renderTo div and place it outside the viewport to allow
  9708. * size computation on chart.render and chart.redraw
  9709. */
  9710. cloneRenderTo: function (revert) {
  9711. var clone = this.renderToClone,
  9712. container = this.container;
  9713. // Destroy the clone and bring the container back to the real renderTo div
  9714. if (revert) {
  9715. if (clone) {
  9716. this.renderTo.appendChild(container);
  9717. discardElement(clone);
  9718. delete this.renderToClone;
  9719. }
  9720. // Set up the clone
  9721. } else {
  9722. if (container && container.parentNode === this.renderTo) {
  9723. this.renderTo.removeChild(container); // do not clone this
  9724. }
  9725. this.renderToClone = clone = this.renderTo.cloneNode(0);
  9726. css(clone, {
  9727. position: ABSOLUTE,
  9728. top: '-9999px',
  9729. display: 'block' // #833
  9730. });
  9731. doc.body.appendChild(clone);
  9732. if (container) {
  9733. clone.appendChild(container);
  9734. }
  9735. }
  9736. },
  9737. /**
  9738. * Get the containing element, determine the size and create the inner container
  9739. * div to hold the chart
  9740. */
  9741. getContainer: function () {
  9742. var chart = this,
  9743. container,
  9744. optionsChart = chart.options.chart,
  9745. chartWidth,
  9746. chartHeight,
  9747. renderTo,
  9748. indexAttrName = 'data-highcharts-chart',
  9749. oldChartIndex,
  9750. containerId;
  9751. chart.renderTo = renderTo = optionsChart.renderTo;
  9752. containerId = PREFIX + idCounter++;
  9753. if (isString(renderTo)) {
  9754. chart.renderTo = renderTo = doc.getElementById(renderTo);
  9755. }
  9756. // Display an error if the renderTo is wrong
  9757. if (!renderTo) {
  9758. error(13, true);
  9759. }
  9760. // If the container already holds a chart, destroy it
  9761. oldChartIndex = pInt(attr(renderTo, indexAttrName));
  9762. if (!isNaN(oldChartIndex) && charts[oldChartIndex]) {
  9763. charts[oldChartIndex].destroy();
  9764. }
  9765. // Make a reference to the chart from the div
  9766. attr(renderTo, indexAttrName, chart.index);
  9767. // remove previous chart
  9768. renderTo.innerHTML = '';
  9769. // If the container doesn't have an offsetWidth, it has or is a child of a node
  9770. // that has display:none. We need to temporarily move it out to a visible
  9771. // state to determine the size, else the legend and tooltips won't render
  9772. // properly
  9773. if (!renderTo.offsetWidth) {
  9774. chart.cloneRenderTo();
  9775. }
  9776. // get the width and height
  9777. chart.getChartSize();
  9778. chartWidth = chart.chartWidth;
  9779. chartHeight = chart.chartHeight;
  9780. // create the inner container
  9781. chart.container = container = createElement(DIV, {
  9782. className: PREFIX + 'container' +
  9783. (optionsChart.className ? ' ' + optionsChart.className : ''),
  9784. id: containerId
  9785. }, extend({
  9786. position: RELATIVE,
  9787. overflow: HIDDEN, // needed for context menu (avoid scrollbars) and
  9788. // content overflow in IE
  9789. width: chartWidth + PX,
  9790. height: chartHeight + PX,
  9791. textAlign: 'left',
  9792. lineHeight: 'normal', // #427
  9793. zIndex: 0, // #1072
  9794. '-webkit-tap-highlight-color': 'rgba(0,0,0,0)'
  9795. }, optionsChart.style),
  9796. chart.renderToClone || renderTo
  9797. );
  9798. // cache the cursor (#1650)
  9799. chart._cursor = container.style.cursor;
  9800. chart.renderer =
  9801. optionsChart.forExport ? // force SVG, used for SVG export
  9802. new SVGRenderer(container, chartWidth, chartHeight, true) :
  9803. new Renderer(container, chartWidth, chartHeight);
  9804. if (useCanVG) {
  9805. // If we need canvg library, extend and configure the renderer
  9806. // to get the tracker for translating mouse events
  9807. chart.renderer.create(chart, container, chartWidth, chartHeight);
  9808. }
  9809. },
  9810. /**
  9811. * Calculate margins by rendering axis labels in a preliminary position. Title,
  9812. * subtitle and legend have already been rendered at this stage, but will be
  9813. * moved into their final positions
  9814. */
  9815. getMargins: function () {
  9816. var chart = this,
  9817. spacing = chart.spacing,
  9818. axisOffset,
  9819. legend = chart.legend,
  9820. margin = chart.margin,
  9821. legendOptions = chart.options.legend,
  9822. legendMargin = pick(legendOptions.margin, 10),
  9823. legendX = legendOptions.x,
  9824. legendY = legendOptions.y,
  9825. align = legendOptions.align,
  9826. verticalAlign = legendOptions.verticalAlign,
  9827. titleOffset = chart.titleOffset;
  9828. chart.resetMargins();
  9829. axisOffset = chart.axisOffset;
  9830. // Adjust for title and subtitle
  9831. if (titleOffset && !defined(margin[0])) {
  9832. chart.plotTop = mathMax(chart.plotTop, titleOffset + chart.options.title.margin + spacing[0]);
  9833. }
  9834. // Adjust for legend
  9835. if (legend.display && !legendOptions.floating) {
  9836. if (align === 'right') { // horizontal alignment handled first
  9837. if (!defined(margin[1])) {
  9838. chart.marginRight = mathMax(
  9839. chart.marginRight,
  9840. legend.legendWidth - legendX + legendMargin + spacing[1]
  9841. );
  9842. }
  9843. } else if (align === 'left') {
  9844. if (!defined(margin[3])) {
  9845. chart.plotLeft = mathMax(
  9846. chart.plotLeft,
  9847. legend.legendWidth + legendX + legendMargin + spacing[3]
  9848. );
  9849. }
  9850. } else if (verticalAlign === 'top') {
  9851. if (!defined(margin[0])) {
  9852. chart.plotTop = mathMax(
  9853. chart.plotTop,
  9854. legend.legendHeight + legendY + legendMargin + spacing[0]
  9855. );
  9856. }
  9857. } else if (verticalAlign === 'bottom') {
  9858. if (!defined(margin[2])) {
  9859. chart.marginBottom = mathMax(
  9860. chart.marginBottom,
  9861. legend.legendHeight - legendY + legendMargin + spacing[2]
  9862. );
  9863. }
  9864. }
  9865. }
  9866. // adjust for scroller
  9867. if (chart.extraBottomMargin) {
  9868. chart.marginBottom += chart.extraBottomMargin;
  9869. }
  9870. if (chart.extraTopMargin) {
  9871. chart.plotTop += chart.extraTopMargin;
  9872. }
  9873. // pre-render axes to get labels offset width
  9874. if (chart.hasCartesianSeries) {
  9875. each(chart.axes, function (axis) {
  9876. axis.getOffset();
  9877. });
  9878. }
  9879. if (!defined(margin[3])) {
  9880. chart.plotLeft += axisOffset[3];
  9881. }
  9882. if (!defined(margin[0])) {
  9883. chart.plotTop += axisOffset[0];
  9884. }
  9885. if (!defined(margin[2])) {
  9886. chart.marginBottom += axisOffset[2];
  9887. }
  9888. if (!defined(margin[1])) {
  9889. chart.marginRight += axisOffset[1];
  9890. }
  9891. chart.setChartSize();
  9892. },
  9893. /**
  9894. * Add the event handlers necessary for auto resizing
  9895. *
  9896. */
  9897. initReflow: function () {
  9898. var chart = this,
  9899. optionsChart = chart.options.chart,
  9900. renderTo = chart.renderTo,
  9901. reflowTimeout;
  9902. function reflow(e) {
  9903. var width = optionsChart.width || adapterRun(renderTo, 'width'),
  9904. height = optionsChart.height || adapterRun(renderTo, 'height'),
  9905. target = e ? e.target : win; // #805 - MooTools doesn't supply e
  9906. // Width and height checks for display:none. Target is doc in IE8 and Opera,
  9907. // win in Firefox, Chrome and IE9.
  9908. if (!chart.hasUserSize && width && height && (target === win || target === doc)) {
  9909. if (width !== chart.containerWidth || height !== chart.containerHeight) {
  9910. clearTimeout(reflowTimeout);
  9911. chart.reflowTimeout = reflowTimeout = setTimeout(function () {
  9912. if (chart.container) { // It may have been destroyed in the meantime (#1257)
  9913. chart.setSize(width, height, false);
  9914. chart.hasUserSize = null;
  9915. }
  9916. }, 100);
  9917. }
  9918. chart.containerWidth = width;
  9919. chart.containerHeight = height;
  9920. }
  9921. }
  9922. chart.reflow = reflow;
  9923. addEvent(win, 'resize', reflow);
  9924. addEvent(chart, 'destroy', function () {
  9925. removeEvent(win, 'resize', reflow);
  9926. });
  9927. },
  9928. /**
  9929. * Resize the chart to a given width and height
  9930. * @param {Number} width
  9931. * @param {Number} height
  9932. * @param {Object|Boolean} animation
  9933. */
  9934. setSize: function (width, height, animation) {
  9935. var chart = this,
  9936. chartWidth,
  9937. chartHeight,
  9938. fireEndResize;
  9939. // Handle the isResizing counter
  9940. chart.isResizing += 1;
  9941. fireEndResize = function () {
  9942. if (chart) {
  9943. fireEvent(chart, 'endResize', null, function () {
  9944. chart.isResizing -= 1;
  9945. });
  9946. }
  9947. };
  9948. // set the animation for the current process
  9949. setAnimation(animation, chart);
  9950. chart.oldChartHeight = chart.chartHeight;
  9951. chart.oldChartWidth = chart.chartWidth;
  9952. if (defined(width)) {
  9953. chart.chartWidth = chartWidth = mathMax(0, mathRound(width));
  9954. chart.hasUserSize = !!chartWidth;
  9955. }
  9956. if (defined(height)) {
  9957. chart.chartHeight = chartHeight = mathMax(0, mathRound(height));
  9958. }
  9959. css(chart.container, {
  9960. width: chartWidth + PX,
  9961. height: chartHeight + PX
  9962. });
  9963. chart.setChartSize(true);
  9964. chart.renderer.setSize(chartWidth, chartHeight, animation);
  9965. // handle axes
  9966. chart.maxTicks = null;
  9967. each(chart.axes, function (axis) {
  9968. axis.isDirty = true;
  9969. axis.setScale();
  9970. });
  9971. // make sure non-cartesian series are also handled
  9972. each(chart.series, function (serie) {
  9973. serie.isDirty = true;
  9974. });
  9975. chart.isDirtyLegend = true; // force legend redraw
  9976. chart.isDirtyBox = true; // force redraw of plot and chart border
  9977. chart.getMargins();
  9978. chart.redraw(animation);
  9979. chart.oldChartHeight = null;
  9980. fireEvent(chart, 'resize');
  9981. // fire endResize and set isResizing back
  9982. // If animation is disabled, fire without delay
  9983. if (globalAnimation === false) {
  9984. fireEndResize();
  9985. } else { // else set a timeout with the animation duration
  9986. setTimeout(fireEndResize, (globalAnimation && globalAnimation.duration) || 500);
  9987. }
  9988. },
  9989. /**
  9990. * Set the public chart properties. This is done before and after the pre-render
  9991. * to determine margin sizes
  9992. */
  9993. setChartSize: function (skipAxes) {
  9994. var chart = this,
  9995. inverted = chart.inverted,
  9996. renderer = chart.renderer,
  9997. chartWidth = chart.chartWidth,
  9998. chartHeight = chart.chartHeight,
  9999. optionsChart = chart.options.chart,
  10000. spacing = chart.spacing,
  10001. clipOffset = chart.clipOffset,
  10002. clipX,
  10003. clipY,
  10004. plotLeft,
  10005. plotTop,
  10006. plotWidth,
  10007. plotHeight,
  10008. plotBorderWidth;
  10009. chart.plotLeft = plotLeft = mathRound(chart.plotLeft);
  10010. chart.plotTop = plotTop = mathRound(chart.plotTop);
  10011. chart.plotWidth = plotWidth = mathMax(0, mathRound(chartWidth - plotLeft - chart.marginRight));
  10012. chart.plotHeight = plotHeight = mathMax(0, mathRound(chartHeight - plotTop - chart.marginBottom));
  10013. chart.plotSizeX = inverted ? plotHeight : plotWidth;
  10014. chart.plotSizeY = inverted ? plotWidth : plotHeight;
  10015. chart.plotBorderWidth = optionsChart.plotBorderWidth || 0;
  10016. // Set boxes used for alignment
  10017. chart.spacingBox = renderer.spacingBox = {
  10018. x: spacing[3],
  10019. y: spacing[0],
  10020. width: chartWidth - spacing[3] - spacing[1],
  10021. height: chartHeight - spacing[0] - spacing[2]
  10022. };
  10023. chart.plotBox = renderer.plotBox = {
  10024. x: plotLeft,
  10025. y: plotTop,
  10026. width: plotWidth,
  10027. height: plotHeight
  10028. };
  10029. plotBorderWidth = 2 * mathFloor(chart.plotBorderWidth / 2);
  10030. clipX = mathCeil(mathMax(plotBorderWidth, clipOffset[3]) / 2);
  10031. clipY = mathCeil(mathMax(plotBorderWidth, clipOffset[0]) / 2);
  10032. chart.clipBox = {
  10033. x: clipX,
  10034. y: clipY,
  10035. width: mathFloor(chart.plotSizeX - mathMax(plotBorderWidth, clipOffset[1]) / 2 - clipX),
  10036. height: mathFloor(chart.plotSizeY - mathMax(plotBorderWidth, clipOffset[2]) / 2 - clipY)
  10037. };
  10038. if (!skipAxes) {
  10039. each(chart.axes, function (axis) {
  10040. axis.setAxisSize();
  10041. axis.setAxisTranslation();
  10042. });
  10043. }
  10044. },
  10045. /**
  10046. * Initial margins before auto size margins are applied
  10047. */
  10048. resetMargins: function () {
  10049. var chart = this,
  10050. spacing = chart.spacing,
  10051. margin = chart.margin;
  10052. chart.plotTop = pick(margin[0], spacing[0]);
  10053. chart.marginRight = pick(margin[1], spacing[1]);
  10054. chart.marginBottom = pick(margin[2], spacing[2]);
  10055. chart.plotLeft = pick(margin[3], spacing[3]);
  10056. chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left
  10057. chart.clipOffset = [0, 0, 0, 0];
  10058. },
  10059. /**
  10060. * Draw the borders and backgrounds for chart and plot area
  10061. */
  10062. drawChartBox: function () {
  10063. var chart = this,
  10064. optionsChart = chart.options.chart,
  10065. renderer = chart.renderer,
  10066. chartWidth = chart.chartWidth,
  10067. chartHeight = chart.chartHeight,
  10068. chartBackground = chart.chartBackground,
  10069. plotBackground = chart.plotBackground,
  10070. plotBorder = chart.plotBorder,
  10071. plotBGImage = chart.plotBGImage,
  10072. chartBorderWidth = optionsChart.borderWidth || 0,
  10073. chartBackgroundColor = optionsChart.backgroundColor,
  10074. plotBackgroundColor = optionsChart.plotBackgroundColor,
  10075. plotBackgroundImage = optionsChart.plotBackgroundImage,
  10076. plotBorderWidth = optionsChart.plotBorderWidth || 0,
  10077. mgn,
  10078. bgAttr,
  10079. plotLeft = chart.plotLeft,
  10080. plotTop = chart.plotTop,
  10081. plotWidth = chart.plotWidth,
  10082. plotHeight = chart.plotHeight,
  10083. plotBox = chart.plotBox,
  10084. clipRect = chart.clipRect,
  10085. clipBox = chart.clipBox;
  10086. // Chart area
  10087. mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0);
  10088. if (chartBorderWidth || chartBackgroundColor) {
  10089. if (!chartBackground) {
  10090. bgAttr = {
  10091. fill: chartBackgroundColor || NONE
  10092. };
  10093. if (chartBorderWidth) { // #980
  10094. bgAttr.stroke = optionsChart.borderColor;
  10095. bgAttr['stroke-width'] = chartBorderWidth;
  10096. }
  10097. chart.chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn,
  10098. optionsChart.borderRadius, chartBorderWidth)
  10099. .attr(bgAttr)
  10100. .add()
  10101. .shadow(optionsChart.shadow);
  10102. } else { // resize
  10103. chartBackground.animate(
  10104. chartBackground.crisp(null, null, null, chartWidth - mgn, chartHeight - mgn)
  10105. );
  10106. }
  10107. }
  10108. // Plot background
  10109. if (plotBackgroundColor) {
  10110. if (!plotBackground) {
  10111. chart.plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0)
  10112. .attr({
  10113. fill: plotBackgroundColor
  10114. })
  10115. .add()
  10116. .shadow(optionsChart.plotShadow);
  10117. } else {
  10118. plotBackground.animate(plotBox);
  10119. }
  10120. }
  10121. if (plotBackgroundImage) {
  10122. if (!plotBGImage) {
  10123. chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight)
  10124. .add();
  10125. } else {
  10126. plotBGImage.animate(plotBox);
  10127. }
  10128. }
  10129. // Plot clip
  10130. if (!clipRect) {
  10131. chart.clipRect = renderer.clipRect(clipBox);
  10132. } else {
  10133. clipRect.animate({
  10134. width: clipBox.width,
  10135. height: clipBox.height
  10136. });
  10137. }
  10138. // Plot area border
  10139. if (plotBorderWidth) {
  10140. if (!plotBorder) {
  10141. chart.plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, -plotBorderWidth)
  10142. .attr({
  10143. stroke: optionsChart.plotBorderColor,
  10144. 'stroke-width': plotBorderWidth,
  10145. zIndex: 1
  10146. })
  10147. .add();
  10148. } else {
  10149. plotBorder.animate(
  10150. plotBorder.crisp(null, plotLeft, plotTop, plotWidth, plotHeight)
  10151. );
  10152. }
  10153. }
  10154. // reset
  10155. chart.isDirtyBox = false;
  10156. },
  10157. /**
  10158. * Detect whether a certain chart property is needed based on inspecting its options
  10159. * and series. This mainly applies to the chart.invert property, and in extensions to
  10160. * the chart.angular and chart.polar properties.
  10161. */
  10162. propFromSeries: function () {
  10163. var chart = this,
  10164. optionsChart = chart.options.chart,
  10165. klass,
  10166. seriesOptions = chart.options.series,
  10167. i,
  10168. value;
  10169. each(['inverted', 'angular', 'polar'], function (key) {
  10170. // The default series type's class
  10171. klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType];
  10172. // Get the value from available chart-wide properties
  10173. value = (
  10174. chart[key] || // 1. it is set before
  10175. optionsChart[key] || // 2. it is set in the options
  10176. (klass && klass.prototype[key]) // 3. it's default series class requires it
  10177. );
  10178. // 4. Check if any the chart's series require it
  10179. i = seriesOptions && seriesOptions.length;
  10180. while (!value && i--) {
  10181. klass = seriesTypes[seriesOptions[i].type];
  10182. if (klass && klass.prototype[key]) {
  10183. value = true;
  10184. }
  10185. }
  10186. // Set the chart property
  10187. chart[key] = value;
  10188. });
  10189. },
  10190. /**
  10191. * Link two or more series together. This is done initially from Chart.render,
  10192. * and after Chart.addSeries and Series.remove.
  10193. */
  10194. linkSeries: function () {
  10195. var chart = this,
  10196. chartSeries = chart.series;
  10197. // Reset links
  10198. each(chartSeries, function (series) {
  10199. series.linkedSeries.length = 0;
  10200. });
  10201. // Apply new links
  10202. each(chartSeries, function (series) {
  10203. var linkedTo = series.options.linkedTo;
  10204. if (isString(linkedTo)) {
  10205. if (linkedTo === ':previous') {
  10206. linkedTo = chart.series[series.index - 1];
  10207. } else {
  10208. linkedTo = chart.get(linkedTo);
  10209. }
  10210. if (linkedTo) {
  10211. linkedTo.linkedSeries.push(series);
  10212. series.linkedParent = linkedTo;
  10213. }
  10214. }
  10215. });
  10216. },
  10217. /**
  10218. * Render all graphics for the chart
  10219. */
  10220. render: function () {
  10221. var chart = this,
  10222. axes = chart.axes,
  10223. renderer = chart.renderer,
  10224. options = chart.options;
  10225. var labels = options.labels,
  10226. credits = options.credits,
  10227. creditsHref;
  10228. // Title
  10229. chart.setTitle();
  10230. // Legend
  10231. chart.legend = new Legend(chart, options.legend);
  10232. chart.getStacks(); // render stacks
  10233. // Get margins by pre-rendering axes
  10234. // set axes scales
  10235. each(axes, function (axis) {
  10236. axis.setScale();
  10237. });
  10238. chart.getMargins();
  10239. chart.maxTicks = null; // reset for second pass
  10240. each(axes, function (axis) {
  10241. axis.setTickPositions(true); // update to reflect the new margins
  10242. axis.setMaxTicks();
  10243. });
  10244. chart.adjustTickAmounts();
  10245. chart.getMargins(); // second pass to check for new labels
  10246. // Draw the borders and backgrounds
  10247. chart.drawChartBox();
  10248. // Axes
  10249. if (chart.hasCartesianSeries) {
  10250. each(axes, function (axis) {
  10251. axis.render();
  10252. });
  10253. }
  10254. // The series
  10255. if (!chart.seriesGroup) {
  10256. chart.seriesGroup = renderer.g('series-group')
  10257. .attr({ zIndex: 3 })
  10258. .add();
  10259. }
  10260. each(chart.series, function (serie) {
  10261. serie.translate();
  10262. serie.setTooltipPoints();
  10263. serie.render();
  10264. });
  10265. // Labels
  10266. if (labels.items) {
  10267. each(labels.items, function (label) {
  10268. var style = extend(labels.style, label.style),
  10269. x = pInt(style.left) + chart.plotLeft,
  10270. y = pInt(style.top) + chart.plotTop + 12;
  10271. // delete to prevent rewriting in IE
  10272. delete style.left;
  10273. delete style.top;
  10274. renderer.text(
  10275. label.html,
  10276. x,
  10277. y
  10278. )
  10279. .attr({ zIndex: 2 })
  10280. .css(style)
  10281. .add();
  10282. });
  10283. }
  10284. // Credits
  10285. if (credits.enabled && !chart.credits) {
  10286. creditsHref = credits.href;
  10287. chart.credits = renderer.text(
  10288. credits.text,
  10289. 0,
  10290. 0
  10291. )
  10292. .on('click', function () {
  10293. if (creditsHref) {
  10294. location.href = creditsHref;
  10295. }
  10296. })
  10297. .attr({
  10298. align: credits.position.align,
  10299. zIndex: 8
  10300. })
  10301. .css(credits.style)
  10302. .add()
  10303. .align(credits.position);
  10304. }
  10305. // Set flag
  10306. chart.hasRendered = true;
  10307. },
  10308. /**
  10309. * Clean up memory usage
  10310. */
  10311. destroy: function () {
  10312. var chart = this,
  10313. axes = chart.axes,
  10314. series = chart.series,
  10315. container = chart.container,
  10316. i,
  10317. parentNode = container && container.parentNode;
  10318. // fire the chart.destoy event
  10319. fireEvent(chart, 'destroy');
  10320. // Delete the chart from charts lookup array
  10321. charts[chart.index] = UNDEFINED;
  10322. chart.renderTo.removeAttribute('data-highcharts-chart');
  10323. // remove events
  10324. removeEvent(chart);
  10325. // ==== Destroy collections:
  10326. // Destroy axes
  10327. i = axes.length;
  10328. while (i--) {
  10329. axes[i] = axes[i].destroy();
  10330. }
  10331. // Destroy each series
  10332. i = series.length;
  10333. while (i--) {
  10334. series[i] = series[i].destroy();
  10335. }
  10336. // ==== Destroy chart properties:
  10337. each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage',
  10338. 'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer', 'scroller',
  10339. 'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'], function (name) {
  10340. var prop = chart[name];
  10341. if (prop && prop.destroy) {
  10342. chart[name] = prop.destroy();
  10343. }
  10344. });
  10345. // remove container and all SVG
  10346. if (container) { // can break in IE when destroyed before finished loading
  10347. container.innerHTML = '';
  10348. removeEvent(container);
  10349. if (parentNode) {
  10350. discardElement(container);
  10351. }
  10352. }
  10353. // clean it all up
  10354. for (i in chart) {
  10355. delete chart[i];
  10356. }
  10357. },
  10358. /**
  10359. * VML namespaces can't be added until after complete. Listening
  10360. * for Perini's doScroll hack is not enough.
  10361. */
  10362. isReadyToRender: function () {
  10363. var chart = this;
  10364. // Note: in spite of JSLint's complaints, win == win.top is required
  10365. /*jslint eqeq: true*/
  10366. if ((!hasSVG && (win == win.top && doc.readyState !== 'complete')) || (useCanVG && !win.canvg)) {
  10367. /*jslint eqeq: false*/
  10368. if (useCanVG) {
  10369. // Delay rendering until canvg library is downloaded and ready
  10370. CanVGController.push(function () { chart.firstRender(); }, chart.options.global.canvasToolsURL);
  10371. } else {
  10372. doc.attachEvent('onreadystatechange', function () {
  10373. doc.detachEvent('onreadystatechange', chart.firstRender);
  10374. if (doc.readyState === 'complete') {
  10375. chart.firstRender();
  10376. }
  10377. });
  10378. }
  10379. return false;
  10380. }
  10381. return true;
  10382. },
  10383. /**
  10384. * Prepare for first rendering after all data are loaded
  10385. */
  10386. firstRender: function () {
  10387. var chart = this,
  10388. options = chart.options,
  10389. callback = chart.callback;
  10390. // Check whether the chart is ready to render
  10391. if (!chart.isReadyToRender()) {
  10392. return;
  10393. }
  10394. // Create the container
  10395. chart.getContainer();
  10396. // Run an early event after the container and renderer are established
  10397. fireEvent(chart, 'init');
  10398. chart.resetMargins();
  10399. chart.setChartSize();
  10400. // Set the common chart properties (mainly invert) from the given series
  10401. chart.propFromSeries();
  10402. // get axes
  10403. chart.getAxes();
  10404. // Initialize the series
  10405. each(options.series || [], function (serieOptions) {
  10406. chart.initSeries(serieOptions);
  10407. });
  10408. chart.linkSeries();
  10409. // Run an event after axes and series are initialized, but before render. At this stage,
  10410. // the series data is indexed and cached in the xData and yData arrays, so we can access
  10411. // those before rendering. Used in Highstock.
  10412. fireEvent(chart, 'beforeRender');
  10413. // depends on inverted and on margins being set
  10414. chart.pointer = new Pointer(chart, options);
  10415. chart.render();
  10416. // add canvas
  10417. chart.renderer.draw();
  10418. // run callbacks
  10419. if (callback) {
  10420. callback.apply(chart, [chart]);
  10421. }
  10422. each(chart.callbacks, function (fn) {
  10423. fn.apply(chart, [chart]);
  10424. });
  10425. // If the chart was rendered outside the top container, put it back in
  10426. chart.cloneRenderTo(true);
  10427. fireEvent(chart, 'load');
  10428. },
  10429. /**
  10430. * Creates arrays for spacing and margin from given options.
  10431. */
  10432. splashArray: function (target, options) {
  10433. var oVar = options[target],
  10434. tArray = isObject(oVar) ? oVar : [oVar, oVar, oVar, oVar];
  10435. return [pick(options[target + 'Top'], tArray[0]),
  10436. pick(options[target + 'Right'], tArray[1]),
  10437. pick(options[target + 'Bottom'], tArray[2]),
  10438. pick(options[target + 'Left'], tArray[3])];
  10439. }
  10440. }; // end Chart
  10441. // Hook for exporting module
  10442. Chart.prototype.callbacks = [];
  10443. /**
  10444. * The Point object and prototype. Inheritable and used as base for PiePoint
  10445. */
  10446. var Point = function () {};
  10447. Point.prototype = {
  10448. /**
  10449. * Initialize the point
  10450. * @param {Object} series The series object containing this point
  10451. * @param {Object} options The data in either number, array or object format
  10452. */
  10453. init: function (series, options, x) {
  10454. var point = this,
  10455. colors;
  10456. point.series = series;
  10457. point.applyOptions(options, x);
  10458. point.pointAttr = {};
  10459. if (series.options.colorByPoint) {
  10460. colors = series.options.colors || series.chart.options.colors;
  10461. point.color = point.color || colors[series.colorCounter++];
  10462. // loop back to zero
  10463. if (series.colorCounter === colors.length) {
  10464. series.colorCounter = 0;
  10465. }
  10466. }
  10467. series.chart.pointCount++;
  10468. return point;
  10469. },
  10470. /**
  10471. * Apply the options containing the x and y data and possible some extra properties.
  10472. * This is called on point init or from point.update.
  10473. *
  10474. * @param {Object} options
  10475. */
  10476. applyOptions: function (options, x) {
  10477. var point = this,
  10478. series = point.series,
  10479. pointValKey = series.pointValKey;
  10480. options = Point.prototype.optionsToObject.call(this, options);
  10481. // copy options directly to point
  10482. extend(point, options);
  10483. point.options = point.options ? extend(point.options, options) : options;
  10484. // For higher dimension series types. For instance, for ranges, point.y is mapped to point.low.
  10485. if (pointValKey) {
  10486. point.y = point[pointValKey];
  10487. }
  10488. // If no x is set by now, get auto incremented value. All points must have an
  10489. // x value, however the y value can be null to create a gap in the series
  10490. if (point.x === UNDEFINED && series) {
  10491. point.x = x === UNDEFINED ? series.autoIncrement() : x;
  10492. }
  10493. return point;
  10494. },
  10495. /**
  10496. * Transform number or array configs into objects
  10497. */
  10498. optionsToObject: function (options) {
  10499. var ret,
  10500. series = this.series,
  10501. pointArrayMap = series.pointArrayMap || ['y'],
  10502. valueCount = pointArrayMap.length,
  10503. firstItemType,
  10504. i = 0,
  10505. j = 0;
  10506. if (typeof options === 'number' || options === null) {
  10507. ret = { y: options };
  10508. } else if (isArray(options)) {
  10509. ret = {};
  10510. // with leading x value
  10511. if (options.length > valueCount) {
  10512. firstItemType = typeof options[0];
  10513. if (firstItemType === 'string') {
  10514. ret.name = options[0];
  10515. } else if (firstItemType === 'number') {
  10516. ret.x = options[0];
  10517. }
  10518. i++;
  10519. }
  10520. while (j < valueCount) {
  10521. ret[pointArrayMap[j++]] = options[i++];
  10522. }
  10523. } else if (typeof options === 'object') {
  10524. ret = options;
  10525. // This is the fastest way to detect if there are individual point dataLabels that need
  10526. // to be considered in drawDataLabels. These can only occur in object configs.
  10527. if (options.dataLabels) {
  10528. series._hasPointLabels = true;
  10529. }
  10530. // Same approach as above for markers
  10531. if (options.marker) {
  10532. series._hasPointMarkers = true;
  10533. }
  10534. }
  10535. return ret;
  10536. },
  10537. /**
  10538. * Destroy a point to clear memory. Its reference still stays in series.data.
  10539. */
  10540. destroy: function () {
  10541. var point = this,
  10542. series = point.series,
  10543. chart = series.chart,
  10544. hoverPoints = chart.hoverPoints,
  10545. prop;
  10546. chart.pointCount--;
  10547. if (hoverPoints) {
  10548. point.setState();
  10549. erase(hoverPoints, point);
  10550. if (!hoverPoints.length) {
  10551. chart.hoverPoints = null;
  10552. }
  10553. }
  10554. if (point === chart.hoverPoint) {
  10555. point.onMouseOut();
  10556. }
  10557. // remove all events
  10558. if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive
  10559. removeEvent(point);
  10560. point.destroyElements();
  10561. }
  10562. if (point.legendItem) { // pies have legend items
  10563. chart.legend.destroyItem(point);
  10564. }
  10565. for (prop in point) {
  10566. point[prop] = null;
  10567. }
  10568. },
  10569. /**
  10570. * Destroy SVG elements associated with the point
  10571. */
  10572. destroyElements: function () {
  10573. var point = this,
  10574. props = ['graphic', 'dataLabel', 'dataLabelUpper', 'group', 'connector', 'shadowGroup'],
  10575. prop,
  10576. i = 6;
  10577. while (i--) {
  10578. prop = props[i];
  10579. if (point[prop]) {
  10580. point[prop] = point[prop].destroy();
  10581. }
  10582. }
  10583. },
  10584. /**
  10585. * Return the configuration hash needed for the data label and tooltip formatters
  10586. */
  10587. getLabelConfig: function () {
  10588. var point = this;
  10589. return {
  10590. x: point.category,
  10591. y: point.y,
  10592. key: point.name || point.category,
  10593. series: point.series,
  10594. point: point,
  10595. percentage: point.percentage,
  10596. total: point.total || point.stackTotal
  10597. };
  10598. },
  10599. /**
  10600. * Toggle the selection status of a point
  10601. * @param {Boolean} selected Whether to select or unselect the point.
  10602. * @param {Boolean} accumulate Whether to add to the previous selection. By default,
  10603. * this happens if the control key (Cmd on Mac) was pressed during clicking.
  10604. */
  10605. select: function (selected, accumulate) {
  10606. var point = this,
  10607. series = point.series,
  10608. chart = series.chart;
  10609. selected = pick(selected, !point.selected);
  10610. // fire the event with the defalut handler
  10611. point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () {
  10612. point.selected = point.options.selected = selected;
  10613. series.options.data[inArray(point, series.data)] = point.options;
  10614. point.setState(selected && SELECT_STATE);
  10615. // unselect all other points unless Ctrl or Cmd + click
  10616. if (!accumulate) {
  10617. each(chart.getSelectedPoints(), function (loopPoint) {
  10618. if (loopPoint.selected && loopPoint !== point) {
  10619. loopPoint.selected = loopPoint.options.selected = false;
  10620. series.options.data[inArray(loopPoint, series.data)] = loopPoint.options;
  10621. loopPoint.setState(NORMAL_STATE);
  10622. loopPoint.firePointEvent('unselect');
  10623. }
  10624. });
  10625. }
  10626. });
  10627. },
  10628. /**
  10629. * Runs on mouse over the point
  10630. */
  10631. onMouseOver: function (e) {
  10632. var point = this,
  10633. series = point.series,
  10634. chart = series.chart,
  10635. tooltip = chart.tooltip,
  10636. hoverPoint = chart.hoverPoint;
  10637. // set normal state to previous series
  10638. if (hoverPoint && hoverPoint !== point) {
  10639. hoverPoint.onMouseOut();
  10640. }
  10641. // trigger the event
  10642. point.firePointEvent('mouseOver');
  10643. // update the tooltip
  10644. if (tooltip && (!tooltip.shared || series.noSharedTooltip)) {
  10645. tooltip.refresh(point, e);
  10646. }
  10647. // hover this
  10648. point.setState(HOVER_STATE);
  10649. chart.hoverPoint = point;
  10650. },
  10651. /**
  10652. * Runs on mouse out from the point
  10653. */
  10654. onMouseOut: function () {
  10655. var chart = this.series.chart,
  10656. hoverPoints = chart.hoverPoints;
  10657. if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887
  10658. this.firePointEvent('mouseOut');
  10659. this.setState();
  10660. chart.hoverPoint = null;
  10661. }
  10662. },
  10663. /**
  10664. * Extendable method for formatting each point's tooltip line
  10665. *
  10666. * @return {String} A string to be concatenated in to the common tooltip text
  10667. */
  10668. tooltipFormatter: function (pointFormat) {
  10669. // Insert options for valueDecimals, valuePrefix, and valueSuffix
  10670. var series = this.series,
  10671. seriesTooltipOptions = series.tooltipOptions,
  10672. valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''),
  10673. valuePrefix = seriesTooltipOptions.valuePrefix || '',
  10674. valueSuffix = seriesTooltipOptions.valueSuffix || '';
  10675. // Loop over the point array map and replace unformatted values with sprintf formatting markup
  10676. each(series.pointArrayMap || ['y'], function (key) {
  10677. key = '{point.' + key; // without the closing bracket
  10678. if (valuePrefix || valueSuffix) {
  10679. pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix);
  10680. }
  10681. pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}');
  10682. });
  10683. return format(pointFormat, {
  10684. point: this,
  10685. series: this.series
  10686. });
  10687. },
  10688. /**
  10689. * Update the point with new options (typically x/y data) and optionally redraw the series.
  10690. *
  10691. * @param {Object} options Point options as defined in the series.data array
  10692. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  10693. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  10694. * configuration
  10695. *
  10696. */
  10697. update: function (options, redraw, animation) {
  10698. var point = this,
  10699. series = point.series,
  10700. graphic = point.graphic,
  10701. i,
  10702. data = series.data,
  10703. chart = series.chart,
  10704. seriesOptions = series.options;
  10705. redraw = pick(redraw, true);
  10706. // fire the event with a default handler of doing the update
  10707. point.firePointEvent('update', { options: options }, function () {
  10708. point.applyOptions(options);
  10709. // update visuals
  10710. if (isObject(options)) {
  10711. series.getAttribs();
  10712. if (graphic) {
  10713. if (options.marker && options.marker.symbol) {
  10714. point.graphic = graphic.destroy();
  10715. } else {
  10716. graphic.attr(point.pointAttr[point.state || '']);
  10717. }
  10718. }
  10719. }
  10720. // record changes in the parallel arrays
  10721. i = inArray(point, data);
  10722. series.xData[i] = point.x;
  10723. series.yData[i] = series.toYData ? series.toYData(point) : point.y;
  10724. series.zData[i] = point.z;
  10725. seriesOptions.data[i] = point.options;
  10726. // redraw
  10727. series.isDirty = series.isDirtyData = true;
  10728. if (!series.fixedBox && series.hasCartesianSeries) { // #1906, #2320
  10729. chart.isDirtyBox = true;
  10730. }
  10731. if (seriesOptions.legendType === 'point') { // #1831, #1885
  10732. chart.legend.destroyItem(point);
  10733. }
  10734. if (redraw) {
  10735. chart.redraw(animation);
  10736. }
  10737. });
  10738. },
  10739. /**
  10740. * Remove a point and optionally redraw the series and if necessary the axes
  10741. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  10742. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  10743. * configuration
  10744. */
  10745. remove: function (redraw, animation) {
  10746. var point = this,
  10747. series = point.series,
  10748. points = series.points,
  10749. chart = series.chart,
  10750. i,
  10751. data = series.data;
  10752. setAnimation(animation, chart);
  10753. redraw = pick(redraw, true);
  10754. // fire the event with a default handler of removing the point
  10755. point.firePointEvent('remove', null, function () {
  10756. // splice all the parallel arrays
  10757. i = inArray(point, data);
  10758. if (data.length === points.length) {
  10759. points.splice(i, 1);
  10760. }
  10761. data.splice(i, 1);
  10762. series.options.data.splice(i, 1);
  10763. series.xData.splice(i, 1);
  10764. series.yData.splice(i, 1);
  10765. series.zData.splice(i, 1);
  10766. point.destroy();
  10767. // redraw
  10768. series.isDirty = true;
  10769. series.isDirtyData = true;
  10770. if (redraw) {
  10771. chart.redraw();
  10772. }
  10773. });
  10774. },
  10775. /**
  10776. * Fire an event on the Point object. Must not be renamed to fireEvent, as this
  10777. * causes a name clash in MooTools
  10778. * @param {String} eventType
  10779. * @param {Object} eventArgs Additional event arguments
  10780. * @param {Function} defaultFunction Default event handler
  10781. */
  10782. firePointEvent: function (eventType, eventArgs, defaultFunction) {
  10783. var point = this,
  10784. series = this.series,
  10785. seriesOptions = series.options;
  10786. // load event handlers on demand to save time on mouseover/out
  10787. if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) {
  10788. this.importEvents();
  10789. }
  10790. // add default handler if in selection mode
  10791. if (eventType === 'click' && seriesOptions.allowPointSelect) {
  10792. defaultFunction = function (event) {
  10793. // Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera
  10794. point.select(null, event.ctrlKey || event.metaKey || event.shiftKey);
  10795. };
  10796. }
  10797. fireEvent(this, eventType, eventArgs, defaultFunction);
  10798. },
  10799. /**
  10800. * Import events from the series' and point's options. Only do it on
  10801. * demand, to save processing time on hovering.
  10802. */
  10803. importEvents: function () {
  10804. if (!this.hasImportedEvents) {
  10805. var point = this,
  10806. options = merge(point.series.options.point, point.options),
  10807. events = options.events,
  10808. eventType;
  10809. point.events = events;
  10810. for (eventType in events) {
  10811. addEvent(point, eventType, events[eventType]);
  10812. }
  10813. this.hasImportedEvents = true;
  10814. }
  10815. },
  10816. /**
  10817. * Set the point's state
  10818. * @param {String} state
  10819. */
  10820. setState: function (state) {
  10821. var point = this,
  10822. plotX = point.plotX,
  10823. plotY = point.plotY,
  10824. series = point.series,
  10825. stateOptions = series.options.states,
  10826. markerOptions = defaultPlotOptions[series.type].marker && series.options.marker,
  10827. normalDisabled = markerOptions && !markerOptions.enabled,
  10828. markerStateOptions = markerOptions && markerOptions.states[state],
  10829. stateDisabled = markerStateOptions && markerStateOptions.enabled === false,
  10830. stateMarkerGraphic = series.stateMarkerGraphic,
  10831. pointMarker = point.marker || {},
  10832. chart = series.chart,
  10833. radius,
  10834. newSymbol,
  10835. pointAttr = point.pointAttr;
  10836. state = state || NORMAL_STATE; // empty string
  10837. if (
  10838. // already has this state
  10839. state === point.state ||
  10840. // selected points don't respond to hover
  10841. (point.selected && state !== SELECT_STATE) ||
  10842. // series' state options is disabled
  10843. (stateOptions[state] && stateOptions[state].enabled === false) ||
  10844. // point marker's state options is disabled
  10845. (state && (stateDisabled || (normalDisabled && !markerStateOptions.enabled)))
  10846. ) {
  10847. return;
  10848. }
  10849. // apply hover styles to the existing point
  10850. if (point.graphic) {
  10851. radius = markerOptions && point.graphic.symbolName && pointAttr[state].r;
  10852. point.graphic.attr(merge(
  10853. pointAttr[state],
  10854. radius ? { // new symbol attributes (#507, #612)
  10855. x: plotX - radius,
  10856. y: plotY - radius,
  10857. width: 2 * radius,
  10858. height: 2 * radius
  10859. } : {}
  10860. ));
  10861. } else {
  10862. // if a graphic is not applied to each point in the normal state, create a shared
  10863. // graphic for the hover state
  10864. if (state && markerStateOptions) {
  10865. radius = markerStateOptions.radius;
  10866. newSymbol = pointMarker.symbol || series.symbol;
  10867. // If the point has another symbol than the previous one, throw away the
  10868. // state marker graphic and force a new one (#1459)
  10869. if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) {
  10870. stateMarkerGraphic = stateMarkerGraphic.destroy();
  10871. }
  10872. // Add a new state marker graphic
  10873. if (!stateMarkerGraphic) {
  10874. series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol(
  10875. newSymbol,
  10876. plotX - radius,
  10877. plotY - radius,
  10878. 2 * radius,
  10879. 2 * radius
  10880. )
  10881. .attr(pointAttr[state])
  10882. .add(series.markerGroup);
  10883. stateMarkerGraphic.currentSymbol = newSymbol;
  10884. // Move the existing graphic
  10885. } else {
  10886. stateMarkerGraphic.attr({ // #1054
  10887. x: plotX - radius,
  10888. y: plotY - radius
  10889. });
  10890. }
  10891. }
  10892. if (stateMarkerGraphic) {
  10893. stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY) ? 'show' : 'hide']();
  10894. }
  10895. }
  10896. point.state = state;
  10897. }
  10898. };
  10899. /**
  10900. * @classDescription The base function which all other series types inherit from. The data in the series is stored
  10901. * in various arrays.
  10902. *
  10903. * - First, series.options.data contains all the original config options for
  10904. * each point whether added by options or methods like series.addPoint.
  10905. * - Next, series.data contains those values converted to points, but in case the series data length
  10906. * exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It
  10907. * only contains the points that have been created on demand.
  10908. * - Then there's series.points that contains all currently visible point objects. In case of cropping,
  10909. * the cropped-away points are not part of this array. The series.points array starts at series.cropStart
  10910. * compared to series.data and series.options.data. If however the series data is grouped, these can't
  10911. * be correlated one to one.
  10912. * - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points.
  10913. * - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points.
  10914. *
  10915. * @param {Object} chart
  10916. * @param {Object} options
  10917. */
  10918. var Series = function () {};
  10919. Series.prototype = {
  10920. isCartesian: true,
  10921. type: 'line',
  10922. pointClass: Point,
  10923. sorted: true, // requires the data to be sorted
  10924. requireSorting: true,
  10925. pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
  10926. stroke: 'lineColor',
  10927. 'stroke-width': 'lineWidth',
  10928. fill: 'fillColor',
  10929. r: 'radius'
  10930. },
  10931. colorCounter: 0,
  10932. init: function (chart, options) {
  10933. var series = this,
  10934. eventType,
  10935. events,
  10936. chartSeries = chart.series;
  10937. series.chart = chart;
  10938. series.options = options = series.setOptions(options); // merge with plotOptions
  10939. series.linkedSeries = [];
  10940. // bind the axes
  10941. series.bindAxes();
  10942. // set some variables
  10943. extend(series, {
  10944. name: options.name,
  10945. state: NORMAL_STATE,
  10946. pointAttr: {},
  10947. visible: options.visible !== false, // true by default
  10948. selected: options.selected === true // false by default
  10949. });
  10950. // special
  10951. if (useCanVG) {
  10952. options.animation = false;
  10953. }
  10954. // register event listeners
  10955. events = options.events;
  10956. for (eventType in events) {
  10957. addEvent(series, eventType, events[eventType]);
  10958. }
  10959. if (
  10960. (events && events.click) ||
  10961. (options.point && options.point.events && options.point.events.click) ||
  10962. options.allowPointSelect
  10963. ) {
  10964. chart.runTrackerClick = true;
  10965. }
  10966. series.getColor();
  10967. series.getSymbol();
  10968. // set the data
  10969. series.setData(options.data, false);
  10970. // Mark cartesian
  10971. if (series.isCartesian) {
  10972. chart.hasCartesianSeries = true;
  10973. }
  10974. // Register it in the chart
  10975. chartSeries.push(series);
  10976. series._i = chartSeries.length - 1;
  10977. // Sort series according to index option (#248, #1123)
  10978. stableSort(chartSeries, function (a, b) {
  10979. return pick(a.options.index, a._i) - pick(b.options.index, a._i);
  10980. });
  10981. each(chartSeries, function (series, i) {
  10982. series.index = i;
  10983. series.name = series.name || 'Series ' + (i + 1);
  10984. });
  10985. },
  10986. /**
  10987. * Set the xAxis and yAxis properties of cartesian series, and register the series
  10988. * in the axis.series array
  10989. */
  10990. bindAxes: function () {
  10991. var series = this,
  10992. seriesOptions = series.options,
  10993. chart = series.chart,
  10994. axisOptions;
  10995. if (series.isCartesian) {
  10996. each(['xAxis', 'yAxis'], function (AXIS) { // repeat for xAxis and yAxis
  10997. each(chart[AXIS], function (axis) { // loop through the chart's axis objects
  10998. axisOptions = axis.options;
  10999. // apply if the series xAxis or yAxis option mathches the number of the
  11000. // axis, or if undefined, use the first axis
  11001. if ((seriesOptions[AXIS] === axisOptions.index) ||
  11002. (seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) ||
  11003. (seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) {
  11004. // register this series in the axis.series lookup
  11005. axis.series.push(series);
  11006. // set this series.xAxis or series.yAxis reference
  11007. series[AXIS] = axis;
  11008. // mark dirty for redraw
  11009. axis.isDirty = true;
  11010. }
  11011. });
  11012. // The series needs an X and an Y axis
  11013. if (!series[AXIS]) {
  11014. error(18, true);
  11015. }
  11016. });
  11017. }
  11018. },
  11019. /**
  11020. * Return an auto incremented x value based on the pointStart and pointInterval options.
  11021. * This is only used if an x value is not given for the point that calls autoIncrement.
  11022. */
  11023. autoIncrement: function () {
  11024. var series = this,
  11025. options = series.options,
  11026. xIncrement = series.xIncrement;
  11027. xIncrement = pick(xIncrement, options.pointStart, 0);
  11028. series.pointInterval = pick(series.pointInterval, options.pointInterval, 1);
  11029. series.xIncrement = xIncrement + series.pointInterval;
  11030. return xIncrement;
  11031. },
  11032. /**
  11033. * Divide the series data into segments divided by null values.
  11034. */
  11035. getSegments: function () {
  11036. var series = this,
  11037. lastNull = -1,
  11038. segments = [],
  11039. i,
  11040. points = series.points,
  11041. pointsLength = points.length;
  11042. if (pointsLength) { // no action required for []
  11043. // if connect nulls, just remove null points
  11044. if (series.options.connectNulls) {
  11045. i = pointsLength;
  11046. while (i--) {
  11047. if (points[i].y === null) {
  11048. points.splice(i, 1);
  11049. }
  11050. }
  11051. if (points.length) {
  11052. segments = [points];
  11053. }
  11054. // else, split on null points
  11055. } else {
  11056. each(points, function (point, i) {
  11057. if (point.y === null) {
  11058. if (i > lastNull + 1) {
  11059. segments.push(points.slice(lastNull + 1, i));
  11060. }
  11061. lastNull = i;
  11062. } else if (i === pointsLength - 1) { // last value
  11063. segments.push(points.slice(lastNull + 1, i + 1));
  11064. }
  11065. });
  11066. }
  11067. }
  11068. // register it
  11069. series.segments = segments;
  11070. },
  11071. /**
  11072. * Set the series options by merging from the options tree
  11073. * @param {Object} itemOptions
  11074. */
  11075. setOptions: function (itemOptions) {
  11076. var chart = this.chart,
  11077. chartOptions = chart.options,
  11078. plotOptions = chartOptions.plotOptions,
  11079. typeOptions = plotOptions[this.type],
  11080. options;
  11081. this.userOptions = itemOptions;
  11082. options = merge(
  11083. typeOptions,
  11084. plotOptions.series,
  11085. itemOptions
  11086. );
  11087. // the tooltip options are merged between global and series specific options
  11088. this.tooltipOptions = merge(chartOptions.tooltip, options.tooltip);
  11089. // Delte marker object if not allowed (#1125)
  11090. if (typeOptions.marker === null) {
  11091. delete options.marker;
  11092. }
  11093. return options;
  11094. },
  11095. /**
  11096. * Get the series' color
  11097. */
  11098. getColor: function () {
  11099. var options = this.options,
  11100. userOptions = this.userOptions,
  11101. defaultColors = this.chart.options.colors,
  11102. counters = this.chart.counters,
  11103. color,
  11104. colorIndex;
  11105. color = options.color || defaultPlotOptions[this.type].color;
  11106. if (!color && !options.colorByPoint) {
  11107. if (defined(userOptions._colorIndex)) { // after Series.update()
  11108. colorIndex = userOptions._colorIndex;
  11109. } else {
  11110. userOptions._colorIndex = counters.color;
  11111. colorIndex = counters.color++;
  11112. }
  11113. color = defaultColors[colorIndex];
  11114. }
  11115. this.color = color;
  11116. counters.wrapColor(defaultColors.length);
  11117. },
  11118. /**
  11119. * Get the series' symbol
  11120. */
  11121. getSymbol: function () {
  11122. var series = this,
  11123. userOptions = series.userOptions,
  11124. seriesMarkerOption = series.options.marker,
  11125. chart = series.chart,
  11126. defaultSymbols = chart.options.symbols,
  11127. counters = chart.counters,
  11128. symbolIndex;
  11129. series.symbol = seriesMarkerOption.symbol;
  11130. if (!series.symbol) {
  11131. if (defined(userOptions._symbolIndex)) { // after Series.update()
  11132. symbolIndex = userOptions._symbolIndex;
  11133. } else {
  11134. userOptions._symbolIndex = counters.symbol;
  11135. symbolIndex = counters.symbol++;
  11136. }
  11137. series.symbol = defaultSymbols[symbolIndex];
  11138. }
  11139. // don't substract radius in image symbols (#604)
  11140. if (/^url/.test(series.symbol)) {
  11141. seriesMarkerOption.radius = 0;
  11142. }
  11143. counters.wrapSymbol(defaultSymbols.length);
  11144. },
  11145. /**
  11146. * Get the series' symbol in the legend. This method should be overridable to create custom
  11147. * symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols.
  11148. *
  11149. * @param {Object} legend The legend object
  11150. */
  11151. drawLegendSymbol: function (legend) {
  11152. var options = this.options,
  11153. markerOptions = options.marker,
  11154. radius,
  11155. legendOptions = legend.options,
  11156. legendSymbol,
  11157. symbolWidth = legendOptions.symbolWidth,
  11158. renderer = this.chart.renderer,
  11159. legendItemGroup = this.legendGroup,
  11160. verticalCenter = legend.baseline - mathRound(renderer.fontMetrics(legendOptions.itemStyle.fontSize).b * 0.3),
  11161. attr;
  11162. // Draw the line
  11163. if (options.lineWidth) {
  11164. attr = {
  11165. 'stroke-width': options.lineWidth
  11166. };
  11167. if (options.dashStyle) {
  11168. attr.dashstyle = options.dashStyle;
  11169. }
  11170. this.legendLine = renderer.path([
  11171. M,
  11172. 0,
  11173. verticalCenter,
  11174. L,
  11175. symbolWidth,
  11176. verticalCenter
  11177. ])
  11178. .attr(attr)
  11179. .add(legendItemGroup);
  11180. }
  11181. // Draw the marker
  11182. if (markerOptions && markerOptions.enabled) {
  11183. radius = markerOptions.radius;
  11184. this.legendSymbol = legendSymbol = renderer.symbol(
  11185. this.symbol,
  11186. (symbolWidth / 2) - radius,
  11187. verticalCenter - radius,
  11188. 2 * radius,
  11189. 2 * radius
  11190. )
  11191. .add(legendItemGroup);
  11192. legendSymbol.isMarker = true;
  11193. }
  11194. },
  11195. /**
  11196. * Add a point dynamically after chart load time
  11197. * @param {Object} options Point options as given in series.data
  11198. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  11199. * @param {Boolean} shift If shift is true, a point is shifted off the start
  11200. * of the series as one is appended to the end.
  11201. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  11202. * configuration
  11203. */
  11204. addPoint: function (options, redraw, shift, animation) {
  11205. var series = this,
  11206. seriesOptions = series.options,
  11207. data = series.data,
  11208. graph = series.graph,
  11209. area = series.area,
  11210. chart = series.chart,
  11211. xData = series.xData,
  11212. yData = series.yData,
  11213. zData = series.zData,
  11214. names = series.names,
  11215. currentShift = (graph && graph.shift) || 0,
  11216. dataOptions = seriesOptions.data,
  11217. point,
  11218. isInTheMiddle,
  11219. x,
  11220. i;
  11221. setAnimation(animation, chart);
  11222. // Make graph animate sideways
  11223. if (shift) {
  11224. each([graph, area, series.graphNeg, series.areaNeg], function (shape) {
  11225. if (shape) {
  11226. shape.shift = currentShift + 1;
  11227. }
  11228. });
  11229. }
  11230. if (area) {
  11231. area.isArea = true; // needed in animation, both with and without shift
  11232. }
  11233. // Optional redraw, defaults to true
  11234. redraw = pick(redraw, true);
  11235. // Get options and push the point to xData, yData and series.options. In series.generatePoints
  11236. // the Point instance will be created on demand and pushed to the series.data array.
  11237. point = { series: series };
  11238. series.pointClass.prototype.applyOptions.apply(point, [options]);
  11239. x = point.x;
  11240. // Get the insertion point
  11241. i = xData.length;
  11242. if (series.requireSorting && x < xData[i - 1]) {
  11243. isInTheMiddle = true;
  11244. while (i && xData[i - 1] > x) {
  11245. i--;
  11246. }
  11247. }
  11248. xData.splice(i, 0, x);
  11249. yData.splice(i, 0, series.toYData ? series.toYData(point) : point.y);
  11250. zData.splice(i, 0, point.z);
  11251. if (names) {
  11252. names[x] = point.name;
  11253. }
  11254. dataOptions.splice(i, 0, options);
  11255. if (isInTheMiddle) {
  11256. series.data.splice(i, 0, null);
  11257. series.processData();
  11258. }
  11259. // Generate points to be added to the legend (#1329)
  11260. if (seriesOptions.legendType === 'point') {
  11261. series.generatePoints();
  11262. }
  11263. // Shift the first point off the parallel arrays
  11264. // todo: consider series.removePoint(i) method
  11265. if (shift) {
  11266. if (data[0] && data[0].remove) {
  11267. data[0].remove(false);
  11268. } else {
  11269. data.shift();
  11270. xData.shift();
  11271. yData.shift();
  11272. zData.shift();
  11273. dataOptions.shift();
  11274. }
  11275. }
  11276. // redraw
  11277. series.isDirty = true;
  11278. series.isDirtyData = true;
  11279. if (redraw) {
  11280. series.getAttribs(); // #1937
  11281. chart.redraw();
  11282. }
  11283. },
  11284. /**
  11285. * Replace the series data with a new set of data
  11286. * @param {Object} data
  11287. * @param {Object} redraw
  11288. */
  11289. setData: function (data, redraw) {
  11290. var series = this,
  11291. oldData = series.points,
  11292. options = series.options,
  11293. chart = series.chart,
  11294. firstPoint = null,
  11295. xAxis = series.xAxis,
  11296. names = xAxis && xAxis.categories && !xAxis.categories.length ? [] : null,
  11297. i;
  11298. // reset properties
  11299. series.xIncrement = null;
  11300. series.pointRange = xAxis && xAxis.categories ? 1 : options.pointRange;
  11301. series.colorCounter = 0; // for series with colorByPoint (#1547)
  11302. // parallel arrays
  11303. var xData = [],
  11304. yData = [],
  11305. zData = [],
  11306. dataLength = data ? data.length : [],
  11307. turboThreshold = pick(options.turboThreshold, 1000),
  11308. pt,
  11309. pointArrayMap = series.pointArrayMap,
  11310. valueCount = pointArrayMap && pointArrayMap.length,
  11311. hasToYData = !!series.toYData;
  11312. // In turbo mode, only one- or twodimensional arrays of numbers are allowed. The
  11313. // first value is tested, and we assume that all the rest are defined the same
  11314. // way. Although the 'for' loops are similar, they are repeated inside each
  11315. // if-else conditional for max performance.
  11316. if (turboThreshold && dataLength > turboThreshold) {
  11317. // find the first non-null point
  11318. i = 0;
  11319. while (firstPoint === null && i < dataLength) {
  11320. firstPoint = data[i];
  11321. i++;
  11322. }
  11323. if (isNumber(firstPoint)) { // assume all points are numbers
  11324. var x = pick(options.pointStart, 0),
  11325. pointInterval = pick(options.pointInterval, 1);
  11326. for (i = 0; i < dataLength; i++) {
  11327. xData[i] = x;
  11328. yData[i] = data[i];
  11329. x += pointInterval;
  11330. }
  11331. series.xIncrement = x;
  11332. } else if (isArray(firstPoint)) { // assume all points are arrays
  11333. if (valueCount) { // [x, low, high] or [x, o, h, l, c]
  11334. for (i = 0; i < dataLength; i++) {
  11335. pt = data[i];
  11336. xData[i] = pt[0];
  11337. yData[i] = pt.slice(1, valueCount + 1);
  11338. }
  11339. } else { // [x, y]
  11340. for (i = 0; i < dataLength; i++) {
  11341. pt = data[i];
  11342. xData[i] = pt[0];
  11343. yData[i] = pt[1];
  11344. }
  11345. }
  11346. } else {
  11347. error(12); // Highcharts expects configs to be numbers or arrays in turbo mode
  11348. }
  11349. } else {
  11350. for (i = 0; i < dataLength; i++) {
  11351. if (data[i] !== UNDEFINED) { // stray commas in oldIE
  11352. pt = { series: series };
  11353. series.pointClass.prototype.applyOptions.apply(pt, [data[i]]);
  11354. xData[i] = pt.x;
  11355. yData[i] = hasToYData ? series.toYData(pt) : pt.y;
  11356. zData[i] = pt.z;
  11357. if (names && pt.name) {
  11358. names[pt.x] = pt.name; // #2046
  11359. }
  11360. }
  11361. }
  11362. }
  11363. // Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON
  11364. if (isString(yData[0])) {
  11365. error(14, true);
  11366. }
  11367. series.data = [];
  11368. series.options.data = data;
  11369. series.xData = xData;
  11370. series.yData = yData;
  11371. series.zData = zData;
  11372. series.names = names;
  11373. // destroy old points
  11374. i = (oldData && oldData.length) || 0;
  11375. while (i--) {
  11376. if (oldData[i] && oldData[i].destroy) {
  11377. oldData[i].destroy();
  11378. }
  11379. }
  11380. // reset minRange (#878)
  11381. if (xAxis) {
  11382. xAxis.minRange = xAxis.userMinRange;
  11383. }
  11384. // redraw
  11385. series.isDirty = series.isDirtyData = chart.isDirtyBox = true;
  11386. if (pick(redraw, true)) {
  11387. chart.redraw(false);
  11388. }
  11389. },
  11390. /**
  11391. * Remove a series and optionally redraw the chart
  11392. *
  11393. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  11394. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  11395. * configuration
  11396. */
  11397. remove: function (redraw, animation) {
  11398. var series = this,
  11399. chart = series.chart;
  11400. redraw = pick(redraw, true);
  11401. if (!series.isRemoving) { /* prevent triggering native event in jQuery
  11402. (calling the remove function from the remove event) */
  11403. series.isRemoving = true;
  11404. // fire the event with a default handler of removing the point
  11405. fireEvent(series, 'remove', null, function () {
  11406. // destroy elements
  11407. series.destroy();
  11408. // redraw
  11409. chart.isDirtyLegend = chart.isDirtyBox = true;
  11410. chart.linkSeries();
  11411. if (redraw) {
  11412. chart.redraw(animation);
  11413. }
  11414. });
  11415. }
  11416. series.isRemoving = false;
  11417. },
  11418. /**
  11419. * Process the data by cropping away unused data points if the series is longer
  11420. * than the crop threshold. This saves computing time for lage series.
  11421. */
  11422. processData: function (force) {
  11423. var series = this,
  11424. processedXData = series.xData, // copied during slice operation below
  11425. processedYData = series.yData,
  11426. dataLength = processedXData.length,
  11427. croppedData,
  11428. cropStart = 0,
  11429. cropped,
  11430. distance,
  11431. closestPointRange,
  11432. xAxis = series.xAxis,
  11433. i, // loop variable
  11434. options = series.options,
  11435. cropThreshold = options.cropThreshold,
  11436. isCartesian = series.isCartesian;
  11437. // If the series data or axes haven't changed, don't go through this. Return false to pass
  11438. // the message on to override methods like in data grouping.
  11439. if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) {
  11440. return false;
  11441. }
  11442. // optionally filter out points outside the plot area
  11443. if (isCartesian && series.sorted && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) {
  11444. var min = xAxis.min,
  11445. max = xAxis.max;
  11446. // it's outside current extremes
  11447. if (processedXData[dataLength - 1] < min || processedXData[0] > max) {
  11448. processedXData = [];
  11449. processedYData = [];
  11450. // only crop if it's actually spilling out
  11451. } else if (processedXData[0] < min || processedXData[dataLength - 1] > max) {
  11452. croppedData = this.cropData(series.xData, series.yData, min, max);
  11453. processedXData = croppedData.xData;
  11454. processedYData = croppedData.yData;
  11455. cropStart = croppedData.start;
  11456. cropped = true;
  11457. }
  11458. }
  11459. // Find the closest distance between processed points
  11460. for (i = processedXData.length - 1; i >= 0; i--) {
  11461. distance = processedXData[i] - processedXData[i - 1];
  11462. if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) {
  11463. closestPointRange = distance;
  11464. // Unsorted data is not supported by the line tooltip, as well as data grouping and
  11465. // navigation in Stock charts (#725) and width calculation of columns (#1900)
  11466. } else if (distance < 0 && series.requireSorting) {
  11467. error(15);
  11468. }
  11469. }
  11470. // Record the properties
  11471. series.cropped = cropped; // undefined or true
  11472. series.cropStart = cropStart;
  11473. series.processedXData = processedXData;
  11474. series.processedYData = processedYData;
  11475. if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC
  11476. series.pointRange = closestPointRange || 1;
  11477. }
  11478. series.closestPointRange = closestPointRange;
  11479. },
  11480. /**
  11481. * Iterate over xData and crop values between min and max. Returns object containing crop start/end
  11482. * cropped xData with corresponding part of yData, dataMin and dataMax within the cropped range
  11483. */
  11484. cropData: function (xData, yData, min, max) {
  11485. var dataLength = xData.length,
  11486. cropStart = 0,
  11487. cropEnd = dataLength,
  11488. cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside
  11489. i;
  11490. // iterate up to find slice start
  11491. for (i = 0; i < dataLength; i++) {
  11492. if (xData[i] >= min) {
  11493. cropStart = mathMax(0, i - cropShoulder);
  11494. break;
  11495. }
  11496. }
  11497. // proceed to find slice end
  11498. for (; i < dataLength; i++) {
  11499. if (xData[i] > max) {
  11500. cropEnd = i + cropShoulder;
  11501. break;
  11502. }
  11503. }
  11504. return {
  11505. xData: xData.slice(cropStart, cropEnd),
  11506. yData: yData.slice(cropStart, cropEnd),
  11507. start: cropStart,
  11508. end: cropEnd
  11509. };
  11510. },
  11511. /**
  11512. * Generate the data point after the data has been processed by cropping away
  11513. * unused points and optionally grouped in Highcharts Stock.
  11514. */
  11515. generatePoints: function () {
  11516. var series = this,
  11517. options = series.options,
  11518. dataOptions = options.data,
  11519. data = series.data,
  11520. dataLength,
  11521. processedXData = series.processedXData,
  11522. processedYData = series.processedYData,
  11523. pointClass = series.pointClass,
  11524. processedDataLength = processedXData.length,
  11525. cropStart = series.cropStart || 0,
  11526. cursor,
  11527. hasGroupedData = series.hasGroupedData,
  11528. point,
  11529. points = [],
  11530. i;
  11531. if (!data && !hasGroupedData) {
  11532. var arr = [];
  11533. arr.length = dataOptions.length;
  11534. data = series.data = arr;
  11535. }
  11536. for (i = 0; i < processedDataLength; i++) {
  11537. cursor = cropStart + i;
  11538. if (!hasGroupedData) {
  11539. if (data[cursor]) {
  11540. point = data[cursor];
  11541. } else if (dataOptions[cursor] !== UNDEFINED) { // #970
  11542. data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]);
  11543. }
  11544. points[i] = point;
  11545. } else {
  11546. // splat the y data in case of ohlc data array
  11547. points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i])));
  11548. }
  11549. }
  11550. // Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when
  11551. // swithching view from non-grouped data to grouped data (#637)
  11552. if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) {
  11553. for (i = 0; i < dataLength; i++) {
  11554. if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points
  11555. i += processedDataLength;
  11556. }
  11557. if (data[i]) {
  11558. data[i].destroyElements();
  11559. data[i].plotX = UNDEFINED; // #1003
  11560. }
  11561. }
  11562. }
  11563. series.data = data;
  11564. series.points = points;
  11565. },
  11566. /**
  11567. * Adds series' points value to corresponding stack
  11568. */
  11569. setStackedPoints: function () {
  11570. if (!this.options.stacking || (this.visible !== true && this.chart.options.chart.ignoreHiddenSeries !== false)) {
  11571. return;
  11572. }
  11573. var series = this,
  11574. xData = series.processedXData,
  11575. yData = series.processedYData,
  11576. stackedYData = [],
  11577. yDataLength = yData.length,
  11578. seriesOptions = series.options,
  11579. threshold = seriesOptions.threshold,
  11580. stackOption = seriesOptions.stack,
  11581. stacking = seriesOptions.stacking,
  11582. stackKey = series.stackKey,
  11583. negKey = '-' + stackKey,
  11584. negStacks = series.negStacks,
  11585. yAxis = series.yAxis,
  11586. stacks = yAxis.stacks,
  11587. oldStacks = yAxis.oldStacks,
  11588. isNegative,
  11589. stack,
  11590. other,
  11591. key,
  11592. i,
  11593. x,
  11594. y;
  11595. // loop over the non-null y values and read them into a local array
  11596. for (i = 0; i < yDataLength; i++) {
  11597. x = xData[i];
  11598. y = yData[i];
  11599. // Read stacked values into a stack based on the x value,
  11600. // the sign of y and the stack key. Stacking is also handled for null values (#739)
  11601. isNegative = negStacks && y < threshold;
  11602. key = isNegative ? negKey : stackKey;
  11603. // Create empty object for this stack if it doesn't exist yet
  11604. if (!stacks[key]) {
  11605. stacks[key] = {};
  11606. }
  11607. // Initialize StackItem for this x
  11608. if (!stacks[key][x]) {
  11609. if (oldStacks[key] && oldStacks[key][x]) {
  11610. stacks[key][x] = oldStacks[key][x];
  11611. stacks[key][x].total = null;
  11612. } else {
  11613. stacks[key][x] = new StackItem(yAxis, yAxis.options.stackLabels, isNegative, x, stackOption, stacking);
  11614. }
  11615. }
  11616. // If the StackItem doesn't exist, create it first
  11617. stack = stacks[key][x];
  11618. stack.points[series.index] = [stack.cum || 0];
  11619. // Add value to the stack total
  11620. if (stacking === 'percent') {
  11621. // Percent stacked column, totals are the same for the positive and negative stacks
  11622. other = isNegative ? stackKey : negKey;
  11623. if (negStacks && stacks[other] && stacks[other][x]) {
  11624. other = stacks[other][x];
  11625. stack.total = other.total = mathMax(other.total, stack.total) + mathAbs(y) || 0;
  11626. // Percent stacked areas
  11627. } else {
  11628. stack.total += mathAbs(y) || 0;
  11629. }
  11630. } else {
  11631. stack.total += y || 0;
  11632. }
  11633. stack.cum = (stack.cum || 0) + (y || 0);
  11634. stack.points[series.index].push(stack.cum);
  11635. stackedYData[i] = stack.cum;
  11636. }
  11637. if (stacking === 'percent') {
  11638. yAxis.usePercentage = true;
  11639. }
  11640. this.stackedYData = stackedYData; // To be used in getExtremes
  11641. // Reset old stacks
  11642. yAxis.oldStacks = {};
  11643. },
  11644. /**
  11645. * Iterate over all stacks and compute the absolute values to percent
  11646. */
  11647. setPercentStacks: function () {
  11648. var series = this,
  11649. stackKey = series.stackKey,
  11650. stacks = series.yAxis.stacks;
  11651. each([stackKey, '-' + stackKey], function (key) {
  11652. var i = series.xData.length,
  11653. x,
  11654. stack,
  11655. pointExtremes,
  11656. totalFactor;
  11657. while (i--) {
  11658. x = series.xData[i];
  11659. stack = stacks[key] && stacks[key][x];
  11660. pointExtremes = stack && stack.points[series.index];
  11661. if (pointExtremes) {
  11662. totalFactor = stack.total ? 100 / stack.total : 0;
  11663. pointExtremes[0] = correctFloat(pointExtremes[0] * totalFactor); // Y bottom value
  11664. pointExtremes[1] = correctFloat(pointExtremes[1] * totalFactor); // Y value
  11665. series.stackedYData[i] = pointExtremes[1];
  11666. }
  11667. }
  11668. });
  11669. },
  11670. /**
  11671. * Calculate Y extremes for visible data
  11672. */
  11673. getExtremes: function () {
  11674. var xAxis = this.xAxis,
  11675. yAxis = this.yAxis,
  11676. xData = this.processedXData,
  11677. yData = this.stackedYData || this.processedYData,
  11678. yDataLength = yData.length,
  11679. activeYData = [],
  11680. activeCounter = 0,
  11681. xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis
  11682. xMin = xExtremes.min,
  11683. xMax = xExtremes.max,
  11684. validValue,
  11685. withinRange,
  11686. dataMin,
  11687. dataMax,
  11688. x,
  11689. y,
  11690. i,
  11691. j;
  11692. for (i = 0; i < yDataLength; i++) {
  11693. x = xData[i];
  11694. y = yData[i];
  11695. // For points within the visible range, including the first point outside the
  11696. // visible range, consider y extremes
  11697. validValue = y !== null && y !== UNDEFINED && (!yAxis.isLog || (y.length || y > 0));
  11698. withinRange = this.getExtremesFromAll || this.cropped || ((xData[i + 1] || x) >= xMin &&
  11699. (xData[i - 1] || x) <= xMax);
  11700. if (validValue && withinRange) {
  11701. j = y.length;
  11702. if (j) { // array, like ohlc or range data
  11703. while (j--) {
  11704. if (y[j] !== null) {
  11705. activeYData[activeCounter++] = y[j];
  11706. }
  11707. }
  11708. } else {
  11709. activeYData[activeCounter++] = y;
  11710. }
  11711. }
  11712. }
  11713. this.dataMin = pick(dataMin, arrayMin(activeYData));
  11714. this.dataMax = pick(dataMax, arrayMax(activeYData));
  11715. },
  11716. /**
  11717. * Translate data points from raw data values to chart specific positioning data
  11718. * needed later in drawPoints, drawGraph and drawTracker.
  11719. */
  11720. translate: function () {
  11721. if (!this.processedXData) { // hidden series
  11722. this.processData();
  11723. }
  11724. this.generatePoints();
  11725. var series = this,
  11726. options = series.options,
  11727. stacking = options.stacking,
  11728. xAxis = series.xAxis,
  11729. categories = xAxis.categories,
  11730. yAxis = series.yAxis,
  11731. points = series.points,
  11732. dataLength = points.length,
  11733. hasModifyValue = !!series.modifyValue,
  11734. i,
  11735. pointPlacement = options.pointPlacement,
  11736. dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement),
  11737. threshold = options.threshold;
  11738. // Translate each point
  11739. for (i = 0; i < dataLength; i++) {
  11740. var point = points[i],
  11741. xValue = point.x,
  11742. yValue = point.y,
  11743. yBottom = point.low,
  11744. stack = yAxis.stacks[(series.negStacks && yValue < threshold ? '-' : '') + series.stackKey],
  11745. pointStack,
  11746. stackValues;
  11747. // Discard disallowed y values for log axes
  11748. if (yAxis.isLog && yValue <= 0) {
  11749. point.y = yValue = null;
  11750. }
  11751. // Get the plotX translation
  11752. point.plotX = xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags'); // Math.round fixes #591
  11753. // Calculate the bottom y value for stacked series
  11754. if (stacking && series.visible && stack && stack[xValue]) {
  11755. pointStack = stack[xValue];
  11756. stackValues = pointStack.points[series.index];
  11757. yBottom = stackValues[0];
  11758. yValue = stackValues[1];
  11759. if (yBottom === 0) {
  11760. yBottom = pick(threshold, yAxis.min);
  11761. }
  11762. if (yAxis.isLog && yBottom <= 0) { // #1200, #1232
  11763. yBottom = null;
  11764. }
  11765. point.percentage = stacking === 'percent' && yValue;
  11766. point.total = point.stackTotal = pointStack.total;
  11767. point.stackY = yValue;
  11768. // Place the stack label
  11769. pointStack.setOffset(series.pointXOffset || 0, series.barW || 0);
  11770. }
  11771. // Set translated yBottom or remove it
  11772. point.yBottom = defined(yBottom) ?
  11773. yAxis.translate(yBottom, 0, 1, 0, 1) :
  11774. null;
  11775. // general hook, used for Highstock compare mode
  11776. if (hasModifyValue) {
  11777. yValue = series.modifyValue(yValue, point);
  11778. }
  11779. // Set the the plotY value, reset it for redraws
  11780. point.plotY = (typeof yValue === 'number' && yValue !== Infinity) ?
  11781. //mathRound(yAxis.translate(yValue, 0, 1, 0, 1) * 10) / 10 : // Math.round fixes #591
  11782. yAxis.translate(yValue, 0, 1, 0, 1) :
  11783. UNDEFINED;
  11784. // Set client related positions for mouse tracking
  11785. point.clientX = dynamicallyPlaced ? xAxis.translate(xValue, 0, 0, 0, 1) : point.plotX; // #1514
  11786. point.negative = point.y < (threshold || 0);
  11787. // some API data
  11788. point.category = categories && categories[point.x] !== UNDEFINED ?
  11789. categories[point.x] : point.x;
  11790. }
  11791. // now that we have the cropped data, build the segments
  11792. series.getSegments();
  11793. },
  11794. /**
  11795. * Memoize tooltip texts and positions
  11796. */
  11797. setTooltipPoints: function (renew) {
  11798. var series = this,
  11799. points = [],
  11800. pointsLength,
  11801. low,
  11802. high,
  11803. xAxis = series.xAxis,
  11804. xExtremes = xAxis && xAxis.getExtremes(),
  11805. axisLength = xAxis ? (xAxis.tooltipLen || xAxis.len) : series.chart.plotSizeX, // tooltipLen and tooltipPosName used in polar
  11806. point,
  11807. pointX,
  11808. nextPoint,
  11809. i,
  11810. tooltipPoints = []; // a lookup array for each pixel in the x dimension
  11811. // don't waste resources if tracker is disabled
  11812. if (series.options.enableMouseTracking === false) {
  11813. return;
  11814. }
  11815. // renew
  11816. if (renew) {
  11817. series.tooltipPoints = null;
  11818. }
  11819. // concat segments to overcome null values
  11820. each(series.segments || series.points, function (segment) {
  11821. points = points.concat(segment);
  11822. });
  11823. // Reverse the points in case the X axis is reversed
  11824. if (xAxis && xAxis.reversed) {
  11825. points = points.reverse();
  11826. }
  11827. // Polar needs additional shaping
  11828. if (series.orderTooltipPoints) {
  11829. series.orderTooltipPoints(points);
  11830. }
  11831. // Assign each pixel position to the nearest point
  11832. pointsLength = points.length;
  11833. for (i = 0; i < pointsLength; i++) {
  11834. point = points[i];
  11835. pointX = point.x;
  11836. if (pointX >= xExtremes.min && pointX <= xExtremes.max) { // #1149
  11837. nextPoint = points[i + 1];
  11838. // Set this range's low to the last range's high plus one
  11839. low = high === UNDEFINED ? 0 : high + 1;
  11840. // Now find the new high
  11841. high = points[i + 1] ?
  11842. mathMin(mathMax(0, mathFloor( // #2070
  11843. (point.clientX + (nextPoint ? (nextPoint.wrappedClientX || nextPoint.clientX) : axisLength)) / 2
  11844. )), axisLength) :
  11845. axisLength;
  11846. while (low >= 0 && low <= high) {
  11847. tooltipPoints[low++] = point;
  11848. }
  11849. }
  11850. }
  11851. series.tooltipPoints = tooltipPoints;
  11852. },
  11853. /**
  11854. * Format the header of the tooltip
  11855. */
  11856. tooltipHeaderFormatter: function (point) {
  11857. var series = this,
  11858. tooltipOptions = series.tooltipOptions,
  11859. xDateFormat = tooltipOptions.xDateFormat,
  11860. dateTimeLabelFormats = tooltipOptions.dateTimeLabelFormats,
  11861. xAxis = series.xAxis,
  11862. isDateTime = xAxis && xAxis.options.type === 'datetime',
  11863. headerFormat = tooltipOptions.headerFormat,
  11864. closestPointRange = xAxis && xAxis.closestPointRange,
  11865. n;
  11866. // Guess the best date format based on the closest point distance (#568)
  11867. if (isDateTime && !xDateFormat) {
  11868. if (closestPointRange) {
  11869. for (n in timeUnits) {
  11870. if (timeUnits[n] >= closestPointRange) {
  11871. xDateFormat = dateTimeLabelFormats[n];
  11872. break;
  11873. }
  11874. }
  11875. } else {
  11876. xDateFormat = dateTimeLabelFormats.day;
  11877. }
  11878. }
  11879. // Insert the header date format if any
  11880. if (isDateTime && xDateFormat && isNumber(point.key)) {
  11881. headerFormat = headerFormat.replace('{point.key}', '{point.key:' + xDateFormat + '}');
  11882. }
  11883. return format(headerFormat, {
  11884. point: point,
  11885. series: series
  11886. });
  11887. },
  11888. /**
  11889. * Series mouse over handler
  11890. */
  11891. onMouseOver: function () {
  11892. var series = this,
  11893. chart = series.chart,
  11894. hoverSeries = chart.hoverSeries;
  11895. // set normal state to previous series
  11896. if (hoverSeries && hoverSeries !== series) {
  11897. hoverSeries.onMouseOut();
  11898. }
  11899. // trigger the event, but to save processing time,
  11900. // only if defined
  11901. if (series.options.events.mouseOver) {
  11902. fireEvent(series, 'mouseOver');
  11903. }
  11904. // hover this
  11905. series.setState(HOVER_STATE);
  11906. chart.hoverSeries = series;
  11907. },
  11908. /**
  11909. * Series mouse out handler
  11910. */
  11911. onMouseOut: function () {
  11912. // trigger the event only if listeners exist
  11913. var series = this,
  11914. options = series.options,
  11915. chart = series.chart,
  11916. tooltip = chart.tooltip,
  11917. hoverPoint = chart.hoverPoint;
  11918. // trigger mouse out on the point, which must be in this series
  11919. if (hoverPoint) {
  11920. hoverPoint.onMouseOut();
  11921. }
  11922. // fire the mouse out event
  11923. if (series && options.events.mouseOut) {
  11924. fireEvent(series, 'mouseOut');
  11925. }
  11926. // hide the tooltip
  11927. if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) {
  11928. tooltip.hide();
  11929. }
  11930. // set normal state
  11931. series.setState();
  11932. chart.hoverSeries = null;
  11933. },
  11934. /**
  11935. * Animate in the series
  11936. */
  11937. animate: function (init) {
  11938. var series = this,
  11939. chart = series.chart,
  11940. renderer = chart.renderer,
  11941. clipRect,
  11942. markerClipRect,
  11943. animation = series.options.animation,
  11944. clipBox = chart.clipBox,
  11945. inverted = chart.inverted,
  11946. sharedClipKey;
  11947. // Animation option is set to true
  11948. if (animation && !isObject(animation)) {
  11949. animation = defaultPlotOptions[series.type].animation;
  11950. }
  11951. sharedClipKey = '_sharedClip' + animation.duration + animation.easing;
  11952. // Initialize the animation. Set up the clipping rectangle.
  11953. if (init) {
  11954. // If a clipping rectangle with the same properties is currently present in the chart, use that.
  11955. clipRect = chart[sharedClipKey];
  11956. markerClipRect = chart[sharedClipKey + 'm'];
  11957. if (!clipRect) {
  11958. chart[sharedClipKey] = clipRect = renderer.clipRect(
  11959. extend(clipBox, { width: 0 })
  11960. );
  11961. chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect(
  11962. -99, // include the width of the first marker
  11963. inverted ? -chart.plotLeft : -chart.plotTop,
  11964. 99,
  11965. inverted ? chart.chartWidth : chart.chartHeight
  11966. );
  11967. }
  11968. series.group.clip(clipRect);
  11969. series.markerGroup.clip(markerClipRect);
  11970. series.sharedClipKey = sharedClipKey;
  11971. // Run the animation
  11972. } else {
  11973. clipRect = chart[sharedClipKey];
  11974. if (clipRect) {
  11975. clipRect.animate({
  11976. width: chart.plotSizeX
  11977. }, animation);
  11978. chart[sharedClipKey + 'm'].animate({
  11979. width: chart.plotSizeX + 99
  11980. }, animation);
  11981. }
  11982. // Delete this function to allow it only once
  11983. series.animate = null;
  11984. // Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option
  11985. // which should be available to the user).
  11986. series.animationTimeout = setTimeout(function () {
  11987. series.afterAnimate();
  11988. }, animation.duration);
  11989. }
  11990. },
  11991. /**
  11992. * This runs after animation to land on the final plot clipping
  11993. */
  11994. afterAnimate: function () {
  11995. var chart = this.chart,
  11996. sharedClipKey = this.sharedClipKey,
  11997. group = this.group;
  11998. if (group && this.options.clip !== false) {
  11999. group.clip(chart.clipRect);
  12000. this.markerGroup.clip(); // no clip
  12001. }
  12002. // Remove the shared clipping rectancgle when all series are shown
  12003. setTimeout(function () {
  12004. if (sharedClipKey && chart[sharedClipKey]) {
  12005. chart[sharedClipKey] = chart[sharedClipKey].destroy();
  12006. chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy();
  12007. }
  12008. }, 100);
  12009. },
  12010. /**
  12011. * Draw the markers
  12012. */
  12013. drawPoints: function () {
  12014. var series = this,
  12015. pointAttr,
  12016. points = series.points,
  12017. chart = series.chart,
  12018. plotX,
  12019. plotY,
  12020. i,
  12021. point,
  12022. radius,
  12023. symbol,
  12024. isImage,
  12025. graphic,
  12026. options = series.options,
  12027. seriesMarkerOptions = options.marker,
  12028. pointMarkerOptions,
  12029. enabled,
  12030. isInside,
  12031. markerGroup = series.markerGroup;
  12032. if (seriesMarkerOptions.enabled || series._hasPointMarkers) {
  12033. i = points.length;
  12034. while (i--) {
  12035. point = points[i];
  12036. plotX = mathFloor(point.plotX); // #1843
  12037. plotY = point.plotY;
  12038. graphic = point.graphic;
  12039. pointMarkerOptions = point.marker || {};
  12040. enabled = (seriesMarkerOptions.enabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled;
  12041. isInside = chart.isInsidePlot(mathRound(plotX), plotY, chart.inverted); // #1858
  12042. // only draw the point if y is defined
  12043. if (enabled && plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) {
  12044. // shortcuts
  12045. pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE];
  12046. radius = pointAttr.r;
  12047. symbol = pick(pointMarkerOptions.symbol, series.symbol);
  12048. isImage = symbol.indexOf('url') === 0;
  12049. if (graphic) { // update
  12050. graphic
  12051. .attr({ // Since the marker group isn't clipped, each individual marker must be toggled
  12052. visibility: isInside ? (hasSVG ? 'inherit' : VISIBLE) : HIDDEN
  12053. })
  12054. .animate(extend({
  12055. x: plotX - radius,
  12056. y: plotY - radius
  12057. }, graphic.symbolName ? { // don't apply to image symbols #507
  12058. width: 2 * radius,
  12059. height: 2 * radius
  12060. } : {}));
  12061. } else if (isInside && (radius > 0 || isImage)) {
  12062. point.graphic = graphic = chart.renderer.symbol(
  12063. symbol,
  12064. plotX - radius,
  12065. plotY - radius,
  12066. 2 * radius,
  12067. 2 * radius
  12068. )
  12069. .attr(pointAttr)
  12070. .add(markerGroup);
  12071. }
  12072. } else if (graphic) {
  12073. point.graphic = graphic.destroy(); // #1269
  12074. }
  12075. }
  12076. }
  12077. },
  12078. /**
  12079. * Convert state properties from API naming conventions to SVG attributes
  12080. *
  12081. * @param {Object} options API options object
  12082. * @param {Object} base1 SVG attribute object to inherit from
  12083. * @param {Object} base2 Second level SVG attribute object to inherit from
  12084. */
  12085. convertAttribs: function (options, base1, base2, base3) {
  12086. var conversion = this.pointAttrToOptions,
  12087. attr,
  12088. option,
  12089. obj = {};
  12090. options = options || {};
  12091. base1 = base1 || {};
  12092. base2 = base2 || {};
  12093. base3 = base3 || {};
  12094. for (attr in conversion) {
  12095. option = conversion[attr];
  12096. obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]);
  12097. }
  12098. return obj;
  12099. },
  12100. /**
  12101. * Get the state attributes. Each series type has its own set of attributes
  12102. * that are allowed to change on a point's state change. Series wide attributes are stored for
  12103. * all series, and additionally point specific attributes are stored for all
  12104. * points with individual marker options. If such options are not defined for the point,
  12105. * a reference to the series wide attributes is stored in point.pointAttr.
  12106. */
  12107. getAttribs: function () {
  12108. var series = this,
  12109. seriesOptions = series.options,
  12110. normalOptions = defaultPlotOptions[series.type].marker ? seriesOptions.marker : seriesOptions,
  12111. stateOptions = normalOptions.states,
  12112. stateOptionsHover = stateOptions[HOVER_STATE],
  12113. pointStateOptionsHover,
  12114. seriesColor = series.color,
  12115. normalDefaults = {
  12116. stroke: seriesColor,
  12117. fill: seriesColor
  12118. },
  12119. points = series.points || [], // #927
  12120. i,
  12121. point,
  12122. seriesPointAttr = [],
  12123. pointAttr,
  12124. pointAttrToOptions = series.pointAttrToOptions,
  12125. hasPointSpecificOptions,
  12126. negativeColor = seriesOptions.negativeColor,
  12127. defaultLineColor = normalOptions.lineColor,
  12128. key;
  12129. // series type specific modifications
  12130. if (seriesOptions.marker) { // line, spline, area, areaspline, scatter
  12131. // if no hover radius is given, default to normal radius + 2
  12132. stateOptionsHover.radius = stateOptionsHover.radius || normalOptions.radius + 2;
  12133. stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + 1;
  12134. } else { // column, bar, pie
  12135. // if no hover color is given, brighten the normal color
  12136. stateOptionsHover.color = stateOptionsHover.color ||
  12137. Color(stateOptionsHover.color || seriesColor)
  12138. .brighten(stateOptionsHover.brightness).get();
  12139. }
  12140. // general point attributes for the series normal state
  12141. seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults);
  12142. // HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius
  12143. each([HOVER_STATE, SELECT_STATE], function (state) {
  12144. seriesPointAttr[state] =
  12145. series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]);
  12146. });
  12147. // set it
  12148. series.pointAttr = seriesPointAttr;
  12149. // Generate the point-specific attribute collections if specific point
  12150. // options are given. If not, create a referance to the series wide point
  12151. // attributes
  12152. i = points.length;
  12153. while (i--) {
  12154. point = points[i];
  12155. normalOptions = (point.options && point.options.marker) || point.options;
  12156. if (normalOptions && normalOptions.enabled === false) {
  12157. normalOptions.radius = 0;
  12158. }
  12159. if (point.negative && negativeColor) {
  12160. point.color = point.fillColor = negativeColor;
  12161. }
  12162. hasPointSpecificOptions = seriesOptions.colorByPoint || point.color; // #868
  12163. // check if the point has specific visual options
  12164. if (point.options) {
  12165. for (key in pointAttrToOptions) {
  12166. if (defined(normalOptions[pointAttrToOptions[key]])) {
  12167. hasPointSpecificOptions = true;
  12168. }
  12169. }
  12170. }
  12171. // a specific marker config object is defined for the individual point:
  12172. // create it's own attribute collection
  12173. if (hasPointSpecificOptions) {
  12174. normalOptions = normalOptions || {};
  12175. pointAttr = [];
  12176. stateOptions = normalOptions.states || {}; // reassign for individual point
  12177. pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {};
  12178. // Handle colors for column and pies
  12179. if (!seriesOptions.marker) { // column, bar, point
  12180. // if no hover color is given, brighten the normal color
  12181. pointStateOptionsHover.color =
  12182. Color(pointStateOptionsHover.color || point.color)
  12183. .brighten(pointStateOptionsHover.brightness ||
  12184. stateOptionsHover.brightness).get();
  12185. }
  12186. // normal point state inherits series wide normal state
  12187. pointAttr[NORMAL_STATE] = series.convertAttribs(extend({
  12188. color: point.color, // #868
  12189. fillColor: point.color, // Individual point color or negative color markers (#2219)
  12190. lineColor: defaultLineColor === null ? point.color : UNDEFINED // Bubbles take point color, line markers use white
  12191. }, normalOptions), seriesPointAttr[NORMAL_STATE]);
  12192. // inherit from point normal and series hover
  12193. pointAttr[HOVER_STATE] = series.convertAttribs(
  12194. stateOptions[HOVER_STATE],
  12195. seriesPointAttr[HOVER_STATE],
  12196. pointAttr[NORMAL_STATE]
  12197. );
  12198. // inherit from point normal and series hover
  12199. pointAttr[SELECT_STATE] = series.convertAttribs(
  12200. stateOptions[SELECT_STATE],
  12201. seriesPointAttr[SELECT_STATE],
  12202. pointAttr[NORMAL_STATE]
  12203. );
  12204. // no marker config object is created: copy a reference to the series-wide
  12205. // attribute collection
  12206. } else {
  12207. pointAttr = seriesPointAttr;
  12208. }
  12209. point.pointAttr = pointAttr;
  12210. }
  12211. },
  12212. /**
  12213. * Update the series with a new set of options
  12214. */
  12215. update: function (newOptions, redraw) {
  12216. var chart = this.chart,
  12217. // must use user options when changing type because this.options is merged
  12218. // in with type specific plotOptions
  12219. oldOptions = this.userOptions,
  12220. oldType = this.type,
  12221. proto = seriesTypes[oldType].prototype,
  12222. n;
  12223. // Do the merge, with some forced options
  12224. newOptions = merge(oldOptions, {
  12225. animation: false,
  12226. index: this.index,
  12227. pointStart: this.xData[0] // when updating after addPoint
  12228. }, { data: this.options.data }, newOptions);
  12229. // Destroy the series and reinsert methods from the type prototype
  12230. this.remove(false);
  12231. for (n in proto) { // Overwrite series-type specific methods (#2270)
  12232. if (proto.hasOwnProperty(n)) {
  12233. this[n] = UNDEFINED;
  12234. }
  12235. }
  12236. extend(this, seriesTypes[newOptions.type || oldType].prototype);
  12237. this.init(chart, newOptions);
  12238. if (pick(redraw, true)) {
  12239. chart.redraw(false);
  12240. }
  12241. },
  12242. /**
  12243. * Clear DOM objects and free up memory
  12244. */
  12245. destroy: function () {
  12246. var series = this,
  12247. chart = series.chart,
  12248. issue134 = /AppleWebKit\/533/.test(userAgent),
  12249. destroy,
  12250. i,
  12251. data = series.data || [],
  12252. point,
  12253. prop,
  12254. axis;
  12255. // add event hook
  12256. fireEvent(series, 'destroy');
  12257. // remove all events
  12258. removeEvent(series);
  12259. // erase from axes
  12260. each(['xAxis', 'yAxis'], function (AXIS) {
  12261. axis = series[AXIS];
  12262. if (axis) {
  12263. erase(axis.series, series);
  12264. axis.isDirty = axis.forceRedraw = true;
  12265. axis.stacks = {}; // Rebuild stacks when updating (#2229)
  12266. }
  12267. });
  12268. // remove legend items
  12269. if (series.legendItem) {
  12270. series.chart.legend.destroyItem(series);
  12271. }
  12272. // destroy all points with their elements
  12273. i = data.length;
  12274. while (i--) {
  12275. point = data[i];
  12276. if (point && point.destroy) {
  12277. point.destroy();
  12278. }
  12279. }
  12280. series.points = null;
  12281. // Clear the animation timeout if we are destroying the series during initial animation
  12282. clearTimeout(series.animationTimeout);
  12283. // destroy all SVGElements associated to the series
  12284. each(['area', 'graph', 'dataLabelsGroup', 'group', 'markerGroup', 'tracker',
  12285. 'graphNeg', 'areaNeg', 'posClip', 'negClip'], function (prop) {
  12286. if (series[prop]) {
  12287. // issue 134 workaround
  12288. destroy = issue134 && prop === 'group' ?
  12289. 'hide' :
  12290. 'destroy';
  12291. series[prop][destroy]();
  12292. }
  12293. });
  12294. // remove from hoverSeries
  12295. if (chart.hoverSeries === series) {
  12296. chart.hoverSeries = null;
  12297. }
  12298. erase(chart.series, series);
  12299. // clear all members
  12300. for (prop in series) {
  12301. delete series[prop];
  12302. }
  12303. },
  12304. /**
  12305. * Draw the data labels
  12306. */
  12307. drawDataLabels: function () {
  12308. var series = this,
  12309. seriesOptions = series.options,
  12310. options = seriesOptions.dataLabels,
  12311. points = series.points,
  12312. pointOptions,
  12313. generalOptions,
  12314. str,
  12315. dataLabelsGroup;
  12316. if (options.enabled || series._hasPointLabels) {
  12317. // Process default alignment of data labels for columns
  12318. if (series.dlProcessOptions) {
  12319. series.dlProcessOptions(options);
  12320. }
  12321. // Create a separate group for the data labels to avoid rotation
  12322. dataLabelsGroup = series.plotGroup(
  12323. 'dataLabelsGroup',
  12324. 'data-labels',
  12325. series.visible ? VISIBLE : HIDDEN,
  12326. options.zIndex || 6
  12327. );
  12328. // Make the labels for each point
  12329. generalOptions = options;
  12330. each(points, function (point) {
  12331. var enabled,
  12332. dataLabel = point.dataLabel,
  12333. labelConfig,
  12334. attr,
  12335. name,
  12336. rotation,
  12337. connector = point.connector,
  12338. isNew = true;
  12339. // Determine if each data label is enabled
  12340. pointOptions = point.options && point.options.dataLabels;
  12341. enabled = pick(pointOptions && pointOptions.enabled, generalOptions.enabled); // #2282
  12342. // If the point is outside the plot area, destroy it. #678, #820
  12343. if (dataLabel && !enabled) {
  12344. point.dataLabel = dataLabel.destroy();
  12345. // Individual labels are disabled if the are explicitly disabled
  12346. // in the point options, or if they fall outside the plot area.
  12347. } else if (enabled) {
  12348. // Create individual options structure that can be extended without
  12349. // affecting others
  12350. options = merge(generalOptions, pointOptions);
  12351. rotation = options.rotation;
  12352. // Get the string
  12353. labelConfig = point.getLabelConfig();
  12354. str = options.format ?
  12355. format(options.format, labelConfig) :
  12356. options.formatter.call(labelConfig, options);
  12357. // Determine the color
  12358. options.style.color = pick(options.color, options.style.color, series.color, 'black');
  12359. // update existing label
  12360. if (dataLabel) {
  12361. if (defined(str)) {
  12362. dataLabel
  12363. .attr({
  12364. text: str
  12365. });
  12366. isNew = false;
  12367. } else { // #1437 - the label is shown conditionally
  12368. point.dataLabel = dataLabel = dataLabel.destroy();
  12369. if (connector) {
  12370. point.connector = connector.destroy();
  12371. }
  12372. }
  12373. // create new label
  12374. } else if (defined(str)) {
  12375. attr = {
  12376. //align: align,
  12377. fill: options.backgroundColor,
  12378. stroke: options.borderColor,
  12379. 'stroke-width': options.borderWidth,
  12380. r: options.borderRadius || 0,
  12381. rotation: rotation,
  12382. padding: options.padding,
  12383. zIndex: 1
  12384. };
  12385. // Remove unused attributes (#947)
  12386. for (name in attr) {
  12387. if (attr[name] === UNDEFINED) {
  12388. delete attr[name];
  12389. }
  12390. }
  12391. dataLabel = point.dataLabel = series.chart.renderer[rotation ? 'text' : 'label']( // labels don't support rotation
  12392. str,
  12393. 0,
  12394. -999,
  12395. null,
  12396. null,
  12397. null,
  12398. options.useHTML
  12399. )
  12400. .attr(attr)
  12401. .css(options.style)
  12402. .add(dataLabelsGroup)
  12403. .shadow(options.shadow);
  12404. }
  12405. if (dataLabel) {
  12406. // Now the data label is created and placed at 0,0, so we need to align it
  12407. series.alignDataLabel(point, dataLabel, options, null, isNew);
  12408. }
  12409. }
  12410. });
  12411. }
  12412. },
  12413. /**
  12414. * Align each individual data label
  12415. */
  12416. alignDataLabel: function (point, dataLabel, options, alignTo, isNew) {
  12417. var chart = this.chart,
  12418. inverted = chart.inverted,
  12419. plotX = pick(point.plotX, -999),
  12420. plotY = pick(point.plotY, -999),
  12421. bBox = dataLabel.getBBox(),
  12422. visible = this.visible && chart.isInsidePlot(point.plotX, point.plotY, inverted),
  12423. alignAttr; // the final position;
  12424. if (visible) {
  12425. // The alignment box is a singular point
  12426. alignTo = extend({
  12427. x: inverted ? chart.plotWidth - plotY : plotX,
  12428. y: mathRound(inverted ? chart.plotHeight - plotX : plotY),
  12429. width: 0,
  12430. height: 0
  12431. }, alignTo);
  12432. // Add the text size for alignment calculation
  12433. extend(options, {
  12434. width: bBox.width,
  12435. height: bBox.height
  12436. });
  12437. // Allow a hook for changing alignment in the last moment, then do the alignment
  12438. if (options.rotation) { // Fancy box alignment isn't supported for rotated text
  12439. alignAttr = {
  12440. align: options.align,
  12441. x: alignTo.x + options.x + alignTo.width / 2,
  12442. y: alignTo.y + options.y + alignTo.height / 2
  12443. };
  12444. dataLabel[isNew ? 'attr' : 'animate'](alignAttr);
  12445. } else {
  12446. dataLabel.align(options, null, alignTo);
  12447. alignAttr = dataLabel.alignAttr;
  12448. // Handle justify or crop
  12449. if (pick(options.overflow, 'justify') === 'justify') { // docs: overflow: justify, also crop only applies when not justify
  12450. this.justifyDataLabel(dataLabel, options, alignAttr, bBox, alignTo, isNew);
  12451. } else if (pick(options.crop, true)) {
  12452. // Now check that the data label is within the plot area
  12453. visible = chart.isInsidePlot(alignAttr.x, alignAttr.y) && chart.isInsidePlot(alignAttr.x + bBox.width, alignAttr.y + bBox.height);
  12454. }
  12455. }
  12456. }
  12457. // Show or hide based on the final aligned position
  12458. if (!visible) {
  12459. dataLabel.attr({ y: -999 });
  12460. }
  12461. },
  12462. /**
  12463. * If data labels fall partly outside the plot area, align them back in, in a way that
  12464. * doesn't hide the point.
  12465. */
  12466. justifyDataLabel: function (dataLabel, options, alignAttr, bBox, alignTo, isNew) {
  12467. var chart = this.chart,
  12468. align = options.align,
  12469. verticalAlign = options.verticalAlign,
  12470. off,
  12471. justified;
  12472. // Off left
  12473. off = alignAttr.x;
  12474. if (off < 0) {
  12475. if (align === 'right') {
  12476. options.align = 'left';
  12477. } else {
  12478. options.x = -off;
  12479. }
  12480. justified = true;
  12481. }
  12482. // Off right
  12483. off = alignAttr.x + bBox.width;
  12484. if (off > chart.plotWidth) {
  12485. if (align === 'left') {
  12486. options.align = 'right';
  12487. } else {
  12488. options.x = chart.plotWidth - off;
  12489. }
  12490. justified = true;
  12491. }
  12492. // Off top
  12493. off = alignAttr.y;
  12494. if (off < 0) {
  12495. if (verticalAlign === 'bottom') {
  12496. options.verticalAlign = 'top';
  12497. } else {
  12498. options.y = -off;
  12499. }
  12500. justified = true;
  12501. }
  12502. // Off bottom
  12503. off = alignAttr.y + bBox.height;
  12504. if (off > chart.plotHeight) {
  12505. if (verticalAlign === 'top') {
  12506. options.verticalAlign = 'bottom';
  12507. } else {
  12508. options.y = chart.plotHeight - off;
  12509. }
  12510. justified = true;
  12511. }
  12512. if (justified) {
  12513. dataLabel.placed = !isNew;
  12514. dataLabel.align(options, null, alignTo);
  12515. }
  12516. },
  12517. /**
  12518. * Return the graph path of a segment
  12519. */
  12520. getSegmentPath: function (segment) {
  12521. var series = this,
  12522. segmentPath = [],
  12523. step = series.options.step;
  12524. // build the segment line
  12525. each(segment, function (point, i) {
  12526. var plotX = point.plotX,
  12527. plotY = point.plotY,
  12528. lastPoint;
  12529. if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object
  12530. segmentPath.push.apply(segmentPath, series.getPointSpline(segment, point, i));
  12531. } else {
  12532. // moveTo or lineTo
  12533. segmentPath.push(i ? L : M);
  12534. // step line?
  12535. if (step && i) {
  12536. lastPoint = segment[i - 1];
  12537. if (step === 'right') {
  12538. segmentPath.push(
  12539. lastPoint.plotX,
  12540. plotY
  12541. );
  12542. } else if (step === 'center') {
  12543. segmentPath.push(
  12544. (lastPoint.plotX + plotX) / 2,
  12545. lastPoint.plotY,
  12546. (lastPoint.plotX + plotX) / 2,
  12547. plotY
  12548. );
  12549. } else {
  12550. segmentPath.push(
  12551. plotX,
  12552. lastPoint.plotY
  12553. );
  12554. }
  12555. }
  12556. // normal line to next point
  12557. segmentPath.push(
  12558. point.plotX,
  12559. point.plotY
  12560. );
  12561. }
  12562. });
  12563. return segmentPath;
  12564. },
  12565. /**
  12566. * Get the graph path
  12567. */
  12568. getGraphPath: function () {
  12569. var series = this,
  12570. graphPath = [],
  12571. segmentPath,
  12572. singlePoints = []; // used in drawTracker
  12573. // Divide into segments and build graph and area paths
  12574. each(series.segments, function (segment) {
  12575. segmentPath = series.getSegmentPath(segment);
  12576. // add the segment to the graph, or a single point for tracking
  12577. if (segment.length > 1) {
  12578. graphPath = graphPath.concat(segmentPath);
  12579. } else {
  12580. singlePoints.push(segment[0]);
  12581. }
  12582. });
  12583. // Record it for use in drawGraph and drawTracker, and return graphPath
  12584. series.singlePoints = singlePoints;
  12585. series.graphPath = graphPath;
  12586. return graphPath;
  12587. },
  12588. /**
  12589. * Draw the actual graph
  12590. */
  12591. drawGraph: function () {
  12592. var series = this,
  12593. options = this.options,
  12594. props = [['graph', options.lineColor || this.color]],
  12595. lineWidth = options.lineWidth,
  12596. dashStyle = options.dashStyle,
  12597. graphPath = this.getGraphPath(),
  12598. negativeColor = options.negativeColor;
  12599. if (negativeColor) {
  12600. props.push(['graphNeg', negativeColor]);
  12601. }
  12602. // draw the graph
  12603. each(props, function (prop, i) {
  12604. var graphKey = prop[0],
  12605. graph = series[graphKey],
  12606. attribs;
  12607. if (graph) {
  12608. stop(graph); // cancel running animations, #459
  12609. graph.animate({ d: graphPath });
  12610. } else if (lineWidth && graphPath.length) { // #1487
  12611. attribs = {
  12612. stroke: prop[1],
  12613. 'stroke-width': lineWidth,
  12614. zIndex: 1 // #1069
  12615. };
  12616. if (dashStyle) {
  12617. attribs.dashstyle = dashStyle;
  12618. } else {
  12619. attribs['stroke-linecap'] = attribs['stroke-linejoin'] = 'round';
  12620. }
  12621. series[graphKey] = series.chart.renderer.path(graphPath)
  12622. .attr(attribs)
  12623. .add(series.group)
  12624. .shadow(!i && options.shadow);
  12625. }
  12626. });
  12627. },
  12628. /**
  12629. * Clip the graphs into the positive and negative coloured graphs
  12630. */
  12631. clipNeg: function () {
  12632. var options = this.options,
  12633. chart = this.chart,
  12634. renderer = chart.renderer,
  12635. negativeColor = options.negativeColor || options.negativeFillColor,
  12636. translatedThreshold,
  12637. posAttr,
  12638. negAttr,
  12639. graph = this.graph,
  12640. area = this.area,
  12641. posClip = this.posClip,
  12642. negClip = this.negClip,
  12643. chartWidth = chart.chartWidth,
  12644. chartHeight = chart.chartHeight,
  12645. chartSizeMax = mathMax(chartWidth, chartHeight),
  12646. yAxis = this.yAxis,
  12647. above,
  12648. below;
  12649. if (negativeColor && (graph || area)) {
  12650. translatedThreshold = mathRound(yAxis.toPixels(options.threshold || 0, true));
  12651. above = {
  12652. x: 0,
  12653. y: 0,
  12654. width: chartSizeMax,
  12655. height: translatedThreshold
  12656. };
  12657. below = {
  12658. x: 0,
  12659. y: translatedThreshold,
  12660. width: chartSizeMax,
  12661. height: chartSizeMax
  12662. };
  12663. if (chart.inverted) {
  12664. above.height = below.y = chart.plotWidth - translatedThreshold;
  12665. if (renderer.isVML) {
  12666. above = {
  12667. x: chart.plotWidth - translatedThreshold - chart.plotLeft,
  12668. y: 0,
  12669. width: chartWidth,
  12670. height: chartHeight
  12671. };
  12672. below = {
  12673. x: translatedThreshold + chart.plotLeft - chartWidth,
  12674. y: 0,
  12675. width: chart.plotLeft + translatedThreshold,
  12676. height: chartWidth
  12677. };
  12678. }
  12679. }
  12680. if (yAxis.reversed) {
  12681. posAttr = below;
  12682. negAttr = above;
  12683. } else {
  12684. posAttr = above;
  12685. negAttr = below;
  12686. }
  12687. if (posClip) { // update
  12688. posClip.animate(posAttr);
  12689. negClip.animate(negAttr);
  12690. } else {
  12691. this.posClip = posClip = renderer.clipRect(posAttr);
  12692. this.negClip = negClip = renderer.clipRect(negAttr);
  12693. if (graph && this.graphNeg) {
  12694. graph.clip(posClip);
  12695. this.graphNeg.clip(negClip);
  12696. }
  12697. if (area) {
  12698. area.clip(posClip);
  12699. this.areaNeg.clip(negClip);
  12700. }
  12701. }
  12702. }
  12703. },
  12704. /**
  12705. * Initialize and perform group inversion on series.group and series.markerGroup
  12706. */
  12707. invertGroups: function () {
  12708. var series = this,
  12709. chart = series.chart;
  12710. // Pie, go away (#1736)
  12711. if (!series.xAxis) {
  12712. return;
  12713. }
  12714. // A fixed size is needed for inversion to work
  12715. function setInvert() {
  12716. var size = {
  12717. width: series.yAxis.len,
  12718. height: series.xAxis.len
  12719. };
  12720. each(['group', 'markerGroup'], function (groupName) {
  12721. if (series[groupName]) {
  12722. series[groupName].attr(size).invert();
  12723. }
  12724. });
  12725. }
  12726. addEvent(chart, 'resize', setInvert); // do it on resize
  12727. addEvent(series, 'destroy', function () {
  12728. removeEvent(chart, 'resize', setInvert);
  12729. });
  12730. // Do it now
  12731. setInvert(); // do it now
  12732. // On subsequent render and redraw, just do setInvert without setting up events again
  12733. series.invertGroups = setInvert;
  12734. },
  12735. /**
  12736. * General abstraction for creating plot groups like series.group, series.dataLabelsGroup and
  12737. * series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size.
  12738. */
  12739. plotGroup: function (prop, name, visibility, zIndex, parent) {
  12740. var group = this[prop],
  12741. isNew = !group;
  12742. // Generate it on first call
  12743. if (isNew) {
  12744. this[prop] = group = this.chart.renderer.g(name)
  12745. .attr({
  12746. visibility: visibility,
  12747. zIndex: zIndex || 0.1 // IE8 needs this
  12748. })
  12749. .add(parent);
  12750. }
  12751. // Place it on first and subsequent (redraw) calls
  12752. group[isNew ? 'attr' : 'animate'](this.getPlotBox());
  12753. return group;
  12754. },
  12755. /**
  12756. * Get the translation and scale for the plot area of this series
  12757. */
  12758. getPlotBox: function () {
  12759. return {
  12760. translateX: this.xAxis ? this.xAxis.left : this.chart.plotLeft,
  12761. translateY: this.yAxis ? this.yAxis.top : this.chart.plotTop,
  12762. scaleX: 1, // #1623
  12763. scaleY: 1
  12764. };
  12765. },
  12766. /**
  12767. * Render the graph and markers
  12768. */
  12769. render: function () {
  12770. var series = this,
  12771. chart = series.chart,
  12772. group,
  12773. options = series.options,
  12774. animation = options.animation,
  12775. doAnimation = animation && !!series.animate &&
  12776. chart.renderer.isSVG, // this animation doesn't work in IE8 quirks when the group div is hidden,
  12777. // and looks bad in other oldIE
  12778. visibility = series.visible ? VISIBLE : HIDDEN,
  12779. zIndex = options.zIndex,
  12780. hasRendered = series.hasRendered,
  12781. chartSeriesGroup = chart.seriesGroup;
  12782. // the group
  12783. group = series.plotGroup(
  12784. 'group',
  12785. 'series',
  12786. visibility,
  12787. zIndex,
  12788. chartSeriesGroup
  12789. );
  12790. series.markerGroup = series.plotGroup(
  12791. 'markerGroup',
  12792. 'markers',
  12793. visibility,
  12794. zIndex,
  12795. chartSeriesGroup
  12796. );
  12797. // initiate the animation
  12798. if (doAnimation) {
  12799. series.animate(true);
  12800. }
  12801. // cache attributes for shapes
  12802. series.getAttribs();
  12803. // SVGRenderer needs to know this before drawing elements (#1089, #1795)
  12804. group.inverted = series.isCartesian ? chart.inverted : false;
  12805. // draw the graph if any
  12806. if (series.drawGraph) {
  12807. series.drawGraph();
  12808. series.clipNeg();
  12809. }
  12810. // draw the data labels (inn pies they go before the points)
  12811. series.drawDataLabels();
  12812. // draw the points
  12813. series.drawPoints();
  12814. // draw the mouse tracking area
  12815. if (series.options.enableMouseTracking !== false) {
  12816. series.drawTracker();
  12817. }
  12818. // Handle inverted series and tracker groups
  12819. if (chart.inverted) {
  12820. series.invertGroups();
  12821. }
  12822. // Initial clipping, must be defined after inverting groups for VML
  12823. if (options.clip !== false && !series.sharedClipKey && !hasRendered) {
  12824. group.clip(chart.clipRect);
  12825. }
  12826. // Run the animation
  12827. if (doAnimation) {
  12828. series.animate();
  12829. } else if (!hasRendered) {
  12830. series.afterAnimate();
  12831. }
  12832. series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
  12833. // (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
  12834. series.hasRendered = true;
  12835. },
  12836. /**
  12837. * Redraw the series after an update in the axes.
  12838. */
  12839. redraw: function () {
  12840. var series = this,
  12841. chart = series.chart,
  12842. wasDirtyData = series.isDirtyData, // cache it here as it is set to false in render, but used after
  12843. group = series.group,
  12844. xAxis = series.xAxis,
  12845. yAxis = series.yAxis;
  12846. // reposition on resize
  12847. if (group) {
  12848. if (chart.inverted) {
  12849. group.attr({
  12850. width: chart.plotWidth,
  12851. height: chart.plotHeight
  12852. });
  12853. }
  12854. group.animate({
  12855. translateX: pick(xAxis && xAxis.left, chart.plotLeft),
  12856. translateY: pick(yAxis && yAxis.top, chart.plotTop)
  12857. });
  12858. }
  12859. series.translate();
  12860. series.setTooltipPoints(true);
  12861. series.render();
  12862. if (wasDirtyData) {
  12863. fireEvent(series, 'updatedData');
  12864. }
  12865. },
  12866. /**
  12867. * Set the state of the graph
  12868. */
  12869. setState: function (state) {
  12870. var series = this,
  12871. options = series.options,
  12872. graph = series.graph,
  12873. graphNeg = series.graphNeg,
  12874. stateOptions = options.states,
  12875. lineWidth = options.lineWidth,
  12876. attribs;
  12877. state = state || NORMAL_STATE;
  12878. if (series.state !== state) {
  12879. series.state = state;
  12880. if (stateOptions[state] && stateOptions[state].enabled === false) {
  12881. return;
  12882. }
  12883. if (state) {
  12884. lineWidth = stateOptions[state].lineWidth || lineWidth + 1;
  12885. }
  12886. if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML
  12887. attribs = {
  12888. 'stroke-width': lineWidth
  12889. };
  12890. // use attr because animate will cause any other animation on the graph to stop
  12891. graph.attr(attribs);
  12892. if (graphNeg) {
  12893. graphNeg.attr(attribs);
  12894. }
  12895. }
  12896. }
  12897. },
  12898. /**
  12899. * Set the visibility of the graph
  12900. *
  12901. * @param vis {Boolean} True to show the series, false to hide. If UNDEFINED,
  12902. * the visibility is toggled.
  12903. */
  12904. setVisible: function (vis, redraw) {
  12905. var series = this,
  12906. chart = series.chart,
  12907. legendItem = series.legendItem,
  12908. showOrHide,
  12909. ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries,
  12910. oldVisibility = series.visible;
  12911. // if called without an argument, toggle visibility
  12912. series.visible = vis = series.userOptions.visible = vis === UNDEFINED ? !oldVisibility : vis;
  12913. showOrHide = vis ? 'show' : 'hide';
  12914. // show or hide elements
  12915. each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) {
  12916. if (series[key]) {
  12917. series[key][showOrHide]();
  12918. }
  12919. });
  12920. // hide tooltip (#1361)
  12921. if (chart.hoverSeries === series) {
  12922. series.onMouseOut();
  12923. }
  12924. if (legendItem) {
  12925. chart.legend.colorizeItem(series, vis);
  12926. }
  12927. // rescale or adapt to resized chart
  12928. series.isDirty = true;
  12929. // in a stack, all other series are affected
  12930. if (series.options.stacking) {
  12931. each(chart.series, function (otherSeries) {
  12932. if (otherSeries.options.stacking && otherSeries.visible) {
  12933. otherSeries.isDirty = true;
  12934. }
  12935. });
  12936. }
  12937. // show or hide linked series
  12938. each(series.linkedSeries, function (otherSeries) {
  12939. otherSeries.setVisible(vis, false);
  12940. });
  12941. if (ignoreHiddenSeries) {
  12942. chart.isDirtyBox = true;
  12943. }
  12944. if (redraw !== false) {
  12945. chart.redraw();
  12946. }
  12947. fireEvent(series, showOrHide);
  12948. },
  12949. /**
  12950. * Show the graph
  12951. */
  12952. show: function () {
  12953. this.setVisible(true);
  12954. },
  12955. /**
  12956. * Hide the graph
  12957. */
  12958. hide: function () {
  12959. this.setVisible(false);
  12960. },
  12961. /**
  12962. * Set the selected state of the graph
  12963. *
  12964. * @param selected {Boolean} True to select the series, false to unselect. If
  12965. * UNDEFINED, the selection state is toggled.
  12966. */
  12967. select: function (selected) {
  12968. var series = this;
  12969. // if called without an argument, toggle
  12970. series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected;
  12971. if (series.checkbox) {
  12972. series.checkbox.checked = selected;
  12973. }
  12974. fireEvent(series, selected ? 'select' : 'unselect');
  12975. },
  12976. /**
  12977. * Draw the tracker object that sits above all data labels and markers to
  12978. * track mouse events on the graph or points. For the line type charts
  12979. * the tracker uses the same graphPath, but with a greater stroke width
  12980. * for better control.
  12981. */
  12982. drawTracker: function () {
  12983. var series = this,
  12984. options = series.options,
  12985. trackByArea = options.trackByArea,
  12986. trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath),
  12987. trackerPathLength = trackerPath.length,
  12988. chart = series.chart,
  12989. pointer = chart.pointer,
  12990. renderer = chart.renderer,
  12991. snap = chart.options.tooltip.snap,
  12992. tracker = series.tracker,
  12993. cursor = options.cursor,
  12994. css = cursor && { cursor: cursor },
  12995. singlePoints = series.singlePoints,
  12996. singlePoint,
  12997. i,
  12998. onMouseOver = function () {
  12999. if (chart.hoverSeries !== series) {
  13000. series.onMouseOver();
  13001. }
  13002. };
  13003. // Extend end points. A better way would be to use round linecaps,
  13004. // but those are not clickable in VML.
  13005. if (trackerPathLength && !trackByArea) {
  13006. i = trackerPathLength + 1;
  13007. while (i--) {
  13008. if (trackerPath[i] === M) { // extend left side
  13009. trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L);
  13010. }
  13011. if ((i && trackerPath[i] === M) || i === trackerPathLength) { // extend right side
  13012. trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]);
  13013. }
  13014. }
  13015. }
  13016. // handle single points
  13017. for (i = 0; i < singlePoints.length; i++) {
  13018. singlePoint = singlePoints[i];
  13019. trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY,
  13020. L, singlePoint.plotX + snap, singlePoint.plotY);
  13021. }
  13022. // draw the tracker
  13023. if (tracker) {
  13024. tracker.attr({ d: trackerPath });
  13025. } else { // create
  13026. series.tracker = renderer.path(trackerPath)
  13027. .attr({
  13028. 'stroke-linejoin': 'round', // #1225
  13029. visibility: series.visible ? VISIBLE : HIDDEN,
  13030. stroke: TRACKER_FILL,
  13031. fill: trackByArea ? TRACKER_FILL : NONE,
  13032. 'stroke-width' : options.lineWidth + (trackByArea ? 0 : 2 * snap),
  13033. zIndex: 2
  13034. })
  13035. .add(series.group);
  13036. // The tracker is added to the series group, which is clipped, but is covered
  13037. // by the marker group. So the marker group also needs to capture events.
  13038. each([series.tracker, series.markerGroup], function (tracker) {
  13039. tracker.addClass(PREFIX + 'tracker')
  13040. .on('mouseover', onMouseOver)
  13041. .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); })
  13042. .css(css);
  13043. if (hasTouch) {
  13044. tracker.on('touchstart', onMouseOver);
  13045. }
  13046. });
  13047. }
  13048. }
  13049. }; // end Series prototype
  13050. /**
  13051. * LineSeries object
  13052. */
  13053. var LineSeries = extendClass(Series);
  13054. seriesTypes.line = LineSeries;
  13055. /**
  13056. * Set the default options for area
  13057. */
  13058. defaultPlotOptions.area = merge(defaultSeriesOptions, {
  13059. threshold: 0
  13060. // trackByArea: false,
  13061. // lineColor: null, // overrides color, but lets fillColor be unaltered
  13062. // fillOpacity: 0.75,
  13063. // fillColor: null
  13064. });
  13065. /**
  13066. * AreaSeries object
  13067. */
  13068. var AreaSeries = extendClass(Series, {
  13069. type: 'area',
  13070. /**
  13071. * For stacks, don't split segments on null values. Instead, draw null values with
  13072. * no marker. Also insert dummy points for any X position that exists in other series
  13073. * in the stack.
  13074. */
  13075. getSegments: function () {
  13076. var segments = [],
  13077. segment = [],
  13078. keys = [],
  13079. xAxis = this.xAxis,
  13080. yAxis = this.yAxis,
  13081. stack = yAxis.stacks[this.stackKey],
  13082. pointMap = {},
  13083. plotX,
  13084. plotY,
  13085. points = this.points,
  13086. connectNulls = this.options.connectNulls,
  13087. val,
  13088. i,
  13089. x;
  13090. if (this.options.stacking && !this.cropped) { // cropped causes artefacts in Stock, and perf issue
  13091. // Create a map where we can quickly look up the points by their X value.
  13092. for (i = 0; i < points.length; i++) {
  13093. pointMap[points[i].x] = points[i];
  13094. }
  13095. // Sort the keys (#1651)
  13096. for (x in stack) {
  13097. keys.push(+x);
  13098. }
  13099. keys.sort(function (a, b) {
  13100. return a - b;
  13101. });
  13102. each(keys, function (x) {
  13103. if (connectNulls && (!pointMap[x] || pointMap[x].y === null)) { // #1836
  13104. return;
  13105. // The point exists, push it to the segment
  13106. } else if (pointMap[x]) {
  13107. segment.push(pointMap[x]);
  13108. // There is no point for this X value in this series, so we
  13109. // insert a dummy point in order for the areas to be drawn
  13110. // correctly.
  13111. } else {
  13112. plotX = xAxis.translate(x);
  13113. val = stack[x].percent ? (stack[x].total ? stack[x].cum * 100 / stack[x].total : 0) : stack[x].cum; // #1991
  13114. plotY = yAxis.toPixels(val, true);
  13115. segment.push({
  13116. y: null,
  13117. plotX: plotX,
  13118. clientX: plotX,
  13119. plotY: plotY,
  13120. yBottom: plotY,
  13121. onMouseOver: noop
  13122. });
  13123. }
  13124. });
  13125. if (segment.length) {
  13126. segments.push(segment);
  13127. }
  13128. } else {
  13129. Series.prototype.getSegments.call(this);
  13130. segments = this.segments;
  13131. }
  13132. this.segments = segments;
  13133. },
  13134. /**
  13135. * Extend the base Series getSegmentPath method by adding the path for the area.
  13136. * This path is pushed to the series.areaPath property.
  13137. */
  13138. getSegmentPath: function (segment) {
  13139. var segmentPath = Series.prototype.getSegmentPath.call(this, segment), // call base method
  13140. areaSegmentPath = [].concat(segmentPath), // work on a copy for the area path
  13141. i,
  13142. options = this.options,
  13143. segLength = segmentPath.length,
  13144. translatedThreshold = this.yAxis.getThreshold(options.threshold), // #2181
  13145. yBottom;
  13146. if (segLength === 3) { // for animation from 1 to two points
  13147. areaSegmentPath.push(L, segmentPath[1], segmentPath[2]);
  13148. }
  13149. if (options.stacking && !this.closedStacks) {
  13150. // Follow stack back. Todo: implement areaspline. A general solution could be to
  13151. // reverse the entire graphPath of the previous series, though may be hard with
  13152. // splines and with series with different extremes
  13153. for (i = segment.length - 1; i >= 0; i--) {
  13154. yBottom = pick(segment[i].yBottom, translatedThreshold);
  13155. // step line?
  13156. if (i < segment.length - 1 && options.step) {
  13157. areaSegmentPath.push(segment[i + 1].plotX, yBottom);
  13158. }
  13159. areaSegmentPath.push(segment[i].plotX, yBottom);
  13160. }
  13161. } else { // follow zero line back
  13162. this.closeSegment(areaSegmentPath, segment, translatedThreshold);
  13163. }
  13164. this.areaPath = this.areaPath.concat(areaSegmentPath);
  13165. return segmentPath;
  13166. },
  13167. /**
  13168. * Extendable method to close the segment path of an area. This is overridden in polar
  13169. * charts.
  13170. */
  13171. closeSegment: function (path, segment, translatedThreshold) {
  13172. path.push(
  13173. L,
  13174. segment[segment.length - 1].plotX,
  13175. translatedThreshold,
  13176. L,
  13177. segment[0].plotX,
  13178. translatedThreshold
  13179. );
  13180. },
  13181. /**
  13182. * Draw the graph and the underlying area. This method calls the Series base
  13183. * function and adds the area. The areaPath is calculated in the getSegmentPath
  13184. * method called from Series.prototype.drawGraph.
  13185. */
  13186. drawGraph: function () {
  13187. // Define or reset areaPath
  13188. this.areaPath = [];
  13189. // Call the base method
  13190. Series.prototype.drawGraph.apply(this);
  13191. // Define local variables
  13192. var series = this,
  13193. areaPath = this.areaPath,
  13194. options = this.options,
  13195. negativeColor = options.negativeColor,
  13196. negativeFillColor = options.negativeFillColor,
  13197. props = [['area', this.color, options.fillColor]]; // area name, main color, fill color
  13198. if (negativeColor || negativeFillColor) {
  13199. props.push(['areaNeg', negativeColor, negativeFillColor]);
  13200. }
  13201. each(props, function (prop) {
  13202. var areaKey = prop[0],
  13203. area = series[areaKey];
  13204. // Create or update the area
  13205. if (area) { // update
  13206. area.animate({ d: areaPath });
  13207. } else { // create
  13208. series[areaKey] = series.chart.renderer.path(areaPath)
  13209. .attr({
  13210. fill: pick(
  13211. prop[2],
  13212. Color(prop[1]).setOpacity(pick(options.fillOpacity, 0.75)).get()
  13213. ),
  13214. zIndex: 0 // #1069
  13215. }).add(series.group);
  13216. }
  13217. });
  13218. },
  13219. /**
  13220. * Get the series' symbol in the legend
  13221. *
  13222. * @param {Object} legend The legend object
  13223. * @param {Object} item The series (this) or point
  13224. */
  13225. drawLegendSymbol: function (legend, item) {
  13226. item.legendSymbol = this.chart.renderer.rect(
  13227. 0,
  13228. legend.baseline - 11,
  13229. legend.options.symbolWidth,
  13230. 12,
  13231. 2
  13232. ).attr({
  13233. zIndex: 3
  13234. }).add(item.legendGroup);
  13235. }
  13236. });
  13237. seriesTypes.area = AreaSeries;/**
  13238. * Set the default options for spline
  13239. */
  13240. defaultPlotOptions.spline = merge(defaultSeriesOptions);
  13241. /**
  13242. * SplineSeries object
  13243. */
  13244. var SplineSeries = extendClass(Series, {
  13245. type: 'spline',
  13246. /**
  13247. * Get the spline segment from a given point's previous neighbour to the given point
  13248. */
  13249. getPointSpline: function (segment, point, i) {
  13250. var smoothing = 1.5, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc
  13251. denom = smoothing + 1,
  13252. plotX = point.plotX,
  13253. plotY = point.plotY,
  13254. lastPoint = segment[i - 1],
  13255. nextPoint = segment[i + 1],
  13256. leftContX,
  13257. leftContY,
  13258. rightContX,
  13259. rightContY,
  13260. ret;
  13261. // find control points
  13262. if (lastPoint && nextPoint) {
  13263. var lastX = lastPoint.plotX,
  13264. lastY = lastPoint.plotY,
  13265. nextX = nextPoint.plotX,
  13266. nextY = nextPoint.plotY,
  13267. correction;
  13268. leftContX = (smoothing * plotX + lastX) / denom;
  13269. leftContY = (smoothing * plotY + lastY) / denom;
  13270. rightContX = (smoothing * plotX + nextX) / denom;
  13271. rightContY = (smoothing * plotY + nextY) / denom;
  13272. // have the two control points make a straight line through main point
  13273. correction = ((rightContY - leftContY) * (rightContX - plotX)) /
  13274. (rightContX - leftContX) + plotY - rightContY;
  13275. leftContY += correction;
  13276. rightContY += correction;
  13277. // to prevent false extremes, check that control points are between
  13278. // neighbouring points' y values
  13279. if (leftContY > lastY && leftContY > plotY) {
  13280. leftContY = mathMax(lastY, plotY);
  13281. rightContY = 2 * plotY - leftContY; // mirror of left control point
  13282. } else if (leftContY < lastY && leftContY < plotY) {
  13283. leftContY = mathMin(lastY, plotY);
  13284. rightContY = 2 * plotY - leftContY;
  13285. }
  13286. if (rightContY > nextY && rightContY > plotY) {
  13287. rightContY = mathMax(nextY, plotY);
  13288. leftContY = 2 * plotY - rightContY;
  13289. } else if (rightContY < nextY && rightContY < plotY) {
  13290. rightContY = mathMin(nextY, plotY);
  13291. leftContY = 2 * plotY - rightContY;
  13292. }
  13293. // record for drawing in next point
  13294. point.rightContX = rightContX;
  13295. point.rightContY = rightContY;
  13296. }
  13297. // Visualize control points for debugging
  13298. /*
  13299. if (leftContX) {
  13300. this.chart.renderer.circle(leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 2)
  13301. .attr({
  13302. stroke: 'red',
  13303. 'stroke-width': 1,
  13304. fill: 'none'
  13305. })
  13306. .add();
  13307. this.chart.renderer.path(['M', leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop,
  13308. 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
  13309. .attr({
  13310. stroke: 'red',
  13311. 'stroke-width': 1
  13312. })
  13313. .add();
  13314. this.chart.renderer.circle(rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 2)
  13315. .attr({
  13316. stroke: 'green',
  13317. 'stroke-width': 1,
  13318. fill: 'none'
  13319. })
  13320. .add();
  13321. this.chart.renderer.path(['M', rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop,
  13322. 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
  13323. .attr({
  13324. stroke: 'green',
  13325. 'stroke-width': 1
  13326. })
  13327. .add();
  13328. }
  13329. */
  13330. // moveTo or lineTo
  13331. if (!i) {
  13332. ret = [M, plotX, plotY];
  13333. } else { // curve from last point to this
  13334. ret = [
  13335. 'C',
  13336. lastPoint.rightContX || lastPoint.plotX,
  13337. lastPoint.rightContY || lastPoint.plotY,
  13338. leftContX || plotX,
  13339. leftContY || plotY,
  13340. plotX,
  13341. plotY
  13342. ];
  13343. lastPoint.rightContX = lastPoint.rightContY = null; // reset for updating series later
  13344. }
  13345. return ret;
  13346. }
  13347. });
  13348. seriesTypes.spline = SplineSeries;
  13349. /**
  13350. * Set the default options for areaspline
  13351. */
  13352. defaultPlotOptions.areaspline = merge(defaultPlotOptions.area);
  13353. /**
  13354. * AreaSplineSeries object
  13355. */
  13356. var areaProto = AreaSeries.prototype,
  13357. AreaSplineSeries = extendClass(SplineSeries, {
  13358. type: 'areaspline',
  13359. closedStacks: true, // instead of following the previous graph back, follow the threshold back
  13360. // Mix in methods from the area series
  13361. getSegmentPath: areaProto.getSegmentPath,
  13362. closeSegment: areaProto.closeSegment,
  13363. drawGraph: areaProto.drawGraph,
  13364. drawLegendSymbol: areaProto.drawLegendSymbol
  13365. });
  13366. seriesTypes.areaspline = AreaSplineSeries;
  13367. /**
  13368. * Set the default options for column
  13369. */
  13370. defaultPlotOptions.column = merge(defaultSeriesOptions, {
  13371. borderColor: '#FFFFFF',
  13372. borderWidth: 1,
  13373. borderRadius: 0,
  13374. //colorByPoint: undefined,
  13375. groupPadding: 0.2,
  13376. //grouping: true,
  13377. marker: null, // point options are specified in the base options
  13378. pointPadding: 0.1,
  13379. //pointWidth: null,
  13380. minPointLength: 0,
  13381. cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes
  13382. pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories
  13383. states: {
  13384. hover: {
  13385. brightness: 0.1,
  13386. shadow: false
  13387. },
  13388. select: {
  13389. color: '#C0C0C0',
  13390. borderColor: '#000000',
  13391. shadow: false
  13392. }
  13393. },
  13394. dataLabels: {
  13395. align: null, // auto
  13396. verticalAlign: null, // auto
  13397. y: null
  13398. },
  13399. stickyTracking: false,
  13400. threshold: 0
  13401. });
  13402. /**
  13403. * ColumnSeries object
  13404. */
  13405. var ColumnSeries = extendClass(Series, {
  13406. type: 'column',
  13407. pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
  13408. stroke: 'borderColor',
  13409. 'stroke-width': 'borderWidth',
  13410. fill: 'color',
  13411. r: 'borderRadius'
  13412. },
  13413. cropShoulder: 0,
  13414. trackerGroups: ['group', 'dataLabelsGroup'],
  13415. negStacks: true, // use separate negative stacks, unlike area stacks where a negative
  13416. // point is substracted from previous (#1910)
  13417. /**
  13418. * Initialize the series
  13419. */
  13420. init: function () {
  13421. Series.prototype.init.apply(this, arguments);
  13422. var series = this,
  13423. chart = series.chart;
  13424. // if the series is added dynamically, force redraw of other
  13425. // series affected by a new column
  13426. if (chart.hasRendered) {
  13427. each(chart.series, function (otherSeries) {
  13428. if (otherSeries.type === series.type) {
  13429. otherSeries.isDirty = true;
  13430. }
  13431. });
  13432. }
  13433. },
  13434. /**
  13435. * Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding,
  13436. * pointWidth etc.
  13437. */
  13438. getColumnMetrics: function () {
  13439. var series = this,
  13440. options = series.options,
  13441. xAxis = series.xAxis,
  13442. yAxis = series.yAxis,
  13443. reversedXAxis = xAxis.reversed,
  13444. stackKey,
  13445. stackGroups = {},
  13446. columnIndex,
  13447. columnCount = 0;
  13448. // Get the total number of column type series.
  13449. // This is called on every series. Consider moving this logic to a
  13450. // chart.orderStacks() function and call it on init, addSeries and removeSeries
  13451. if (options.grouping === false) {
  13452. columnCount = 1;
  13453. } else {
  13454. each(series.chart.series, function (otherSeries) {
  13455. var otherOptions = otherSeries.options,
  13456. otherYAxis = otherSeries.yAxis;
  13457. if (otherSeries.type === series.type && otherSeries.visible &&
  13458. yAxis.len === otherYAxis.len && yAxis.pos === otherYAxis.pos) { // #642, #2086
  13459. if (otherOptions.stacking) {
  13460. stackKey = otherSeries.stackKey;
  13461. if (stackGroups[stackKey] === UNDEFINED) {
  13462. stackGroups[stackKey] = columnCount++;
  13463. }
  13464. columnIndex = stackGroups[stackKey];
  13465. } else if (otherOptions.grouping !== false) { // #1162
  13466. columnIndex = columnCount++;
  13467. }
  13468. otherSeries.columnIndex = columnIndex;
  13469. }
  13470. });
  13471. }
  13472. var categoryWidth = mathMin(
  13473. mathAbs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || 1),
  13474. xAxis.len // #1535
  13475. ),
  13476. groupPadding = categoryWidth * options.groupPadding,
  13477. groupWidth = categoryWidth - 2 * groupPadding,
  13478. pointOffsetWidth = groupWidth / columnCount,
  13479. optionPointWidth = options.pointWidth,
  13480. pointPadding = defined(optionPointWidth) ? (pointOffsetWidth - optionPointWidth) / 2 :
  13481. pointOffsetWidth * options.pointPadding,
  13482. pointWidth = pick(optionPointWidth, pointOffsetWidth - 2 * pointPadding), // exact point width, used in polar charts
  13483. colIndex = (reversedXAxis ?
  13484. columnCount - (series.columnIndex || 0) : // #1251
  13485. series.columnIndex) || 0,
  13486. pointXOffset = pointPadding + (groupPadding + colIndex *
  13487. pointOffsetWidth - (categoryWidth / 2)) *
  13488. (reversedXAxis ? -1 : 1);
  13489. // Save it for reading in linked series (Error bars particularly)
  13490. return (series.columnMetrics = {
  13491. width: pointWidth,
  13492. offset: pointXOffset
  13493. });
  13494. },
  13495. /**
  13496. * Translate each point to the plot area coordinate system and find shape positions
  13497. */
  13498. translate: function () {
  13499. var series = this,
  13500. chart = series.chart,
  13501. options = series.options,
  13502. borderWidth = options.borderWidth,
  13503. yAxis = series.yAxis,
  13504. threshold = options.threshold,
  13505. translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold),
  13506. minPointLength = pick(options.minPointLength, 5),
  13507. metrics = series.getColumnMetrics(),
  13508. pointWidth = metrics.width,
  13509. seriesBarW = series.barW = mathCeil(mathMax(pointWidth, 1 + 2 * borderWidth)), // rounded and postprocessed for border width
  13510. pointXOffset = series.pointXOffset = metrics.offset,
  13511. xCrisp = -(borderWidth % 2 ? 0.5 : 0),
  13512. yCrisp = borderWidth % 2 ? 0.5 : 1;
  13513. if (chart.renderer.isVML && chart.inverted) {
  13514. yCrisp += 1;
  13515. }
  13516. Series.prototype.translate.apply(series);
  13517. // record the new values
  13518. each(series.points, function (point) {
  13519. var yBottom = pick(point.yBottom, translatedThreshold),
  13520. plotY = mathMin(mathMax(-999 - yBottom, point.plotY), yAxis.len + 999 + yBottom), // Don't draw too far outside plot area (#1303, #2241)
  13521. barX = point.plotX + pointXOffset,
  13522. barW = seriesBarW,
  13523. barY = mathMin(plotY, yBottom),
  13524. right,
  13525. bottom,
  13526. fromTop,
  13527. fromLeft,
  13528. barH = mathMax(plotY, yBottom) - barY;
  13529. // Handle options.minPointLength
  13530. if (mathAbs(barH) < minPointLength) {
  13531. if (minPointLength) {
  13532. barH = minPointLength;
  13533. barY =
  13534. mathRound(mathAbs(barY - translatedThreshold) > minPointLength ? // stacked
  13535. yBottom - minPointLength : // keep position
  13536. translatedThreshold - (yAxis.translate(point.y, 0, 1, 0, 1) <= translatedThreshold ? minPointLength : 0)); // use exact yAxis.translation (#1485)
  13537. }
  13538. }
  13539. // Cache for access in polar
  13540. point.barX = barX;
  13541. point.pointWidth = pointWidth;
  13542. // Round off to obtain crisp edges
  13543. fromLeft = mathAbs(barX) < 0.5;
  13544. right = mathRound(barX + barW) + xCrisp;
  13545. barX = mathRound(barX) + xCrisp;
  13546. barW = right - barX;
  13547. fromTop = mathAbs(barY) < 0.5;
  13548. bottom = mathRound(barY + barH) + yCrisp;
  13549. barY = mathRound(barY) + yCrisp;
  13550. barH = bottom - barY;
  13551. // Top and left edges are exceptions
  13552. if (fromLeft) {
  13553. barX += 1;
  13554. barW -= 1;
  13555. }
  13556. if (fromTop) {
  13557. barY -= 1;
  13558. barH += 1;
  13559. }
  13560. // Register shape type and arguments to be used in drawPoints
  13561. point.shapeType = 'rect';
  13562. point.shapeArgs = {
  13563. x: barX,
  13564. y: barY,
  13565. width: barW,
  13566. height: barH
  13567. };
  13568. });
  13569. },
  13570. getSymbol: noop,
  13571. /**
  13572. * Use a solid rectangle like the area series types
  13573. */
  13574. drawLegendSymbol: AreaSeries.prototype.drawLegendSymbol,
  13575. /**
  13576. * Columns have no graph
  13577. */
  13578. drawGraph: noop,
  13579. /**
  13580. * Draw the columns. For bars, the series.group is rotated, so the same coordinates
  13581. * apply for columns and bars. This method is inherited by scatter series.
  13582. *
  13583. */
  13584. drawPoints: function () {
  13585. var series = this,
  13586. options = series.options,
  13587. renderer = series.chart.renderer,
  13588. shapeArgs;
  13589. // draw the columns
  13590. each(series.points, function (point) {
  13591. var plotY = point.plotY,
  13592. graphic = point.graphic;
  13593. if (plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) {
  13594. shapeArgs = point.shapeArgs;
  13595. if (graphic) { // update
  13596. stop(graphic);
  13597. graphic.animate(merge(shapeArgs));
  13598. } else {
  13599. point.graphic = graphic = renderer[point.shapeType](shapeArgs)
  13600. .attr(point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE])
  13601. .add(series.group)
  13602. .shadow(options.shadow, null, options.stacking && !options.borderRadius);
  13603. }
  13604. } else if (graphic) {
  13605. point.graphic = graphic.destroy(); // #1269
  13606. }
  13607. });
  13608. },
  13609. /**
  13610. * Add tracking event listener to the series group, so the point graphics
  13611. * themselves act as trackers
  13612. */
  13613. drawTracker: function () {
  13614. var series = this,
  13615. chart = series.chart,
  13616. pointer = chart.pointer,
  13617. cursor = series.options.cursor,
  13618. css = cursor && { cursor: cursor },
  13619. onMouseOver = function (e) {
  13620. var target = e.target,
  13621. point;
  13622. if (chart.hoverSeries !== series) {
  13623. series.onMouseOver();
  13624. }
  13625. while (target && !point) {
  13626. point = target.point;
  13627. target = target.parentNode;
  13628. }
  13629. if (point !== UNDEFINED && point !== chart.hoverPoint) { // undefined on graph in scatterchart
  13630. point.onMouseOver(e);
  13631. }
  13632. };
  13633. // Add reference to the point
  13634. each(series.points, function (point) {
  13635. if (point.graphic) {
  13636. point.graphic.element.point = point;
  13637. }
  13638. if (point.dataLabel) {
  13639. point.dataLabel.element.point = point;
  13640. }
  13641. });
  13642. // Add the event listeners, we need to do this only once
  13643. if (!series._hasTracking) {
  13644. each(series.trackerGroups, function (key) {
  13645. if (series[key]) { // we don't always have dataLabelsGroup
  13646. series[key]
  13647. .addClass(PREFIX + 'tracker')
  13648. .on('mouseover', onMouseOver)
  13649. .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); })
  13650. .css(css);
  13651. if (hasTouch) {
  13652. series[key].on('touchstart', onMouseOver);
  13653. }
  13654. }
  13655. });
  13656. series._hasTracking = true;
  13657. }
  13658. },
  13659. /**
  13660. * Override the basic data label alignment by adjusting for the position of the column
  13661. */
  13662. alignDataLabel: function (point, dataLabel, options, alignTo, isNew) {
  13663. var chart = this.chart,
  13664. inverted = chart.inverted,
  13665. dlBox = point.dlBox || point.shapeArgs, // data label box for alignment
  13666. below = point.below || (point.plotY > pick(this.translatedThreshold, chart.plotSizeY)),
  13667. inside = pick(options.inside, !!this.options.stacking); // draw it inside the box?
  13668. // Align to the column itself, or the top of it
  13669. if (dlBox) { // Area range uses this method but not alignTo
  13670. alignTo = merge(dlBox);
  13671. if (inverted) {
  13672. alignTo = {
  13673. x: chart.plotWidth - alignTo.y - alignTo.height,
  13674. y: chart.plotHeight - alignTo.x - alignTo.width,
  13675. width: alignTo.height,
  13676. height: alignTo.width
  13677. };
  13678. }
  13679. // Compute the alignment box
  13680. if (!inside) {
  13681. if (inverted) {
  13682. alignTo.x += below ? 0 : alignTo.width;
  13683. alignTo.width = 0;
  13684. } else {
  13685. alignTo.y += below ? alignTo.height : 0;
  13686. alignTo.height = 0;
  13687. }
  13688. }
  13689. }
  13690. // When alignment is undefined (typically columns and bars), display the individual
  13691. // point below or above the point depending on the threshold
  13692. options.align = pick(
  13693. options.align,
  13694. !inverted || inside ? 'center' : below ? 'right' : 'left'
  13695. );
  13696. options.verticalAlign = pick(
  13697. options.verticalAlign,
  13698. inverted || inside ? 'middle' : below ? 'top' : 'bottom'
  13699. );
  13700. // Call the parent method
  13701. Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew);
  13702. },
  13703. /**
  13704. * Animate the column heights one by one from zero
  13705. * @param {Boolean} init Whether to initialize the animation or run it
  13706. */
  13707. animate: function (init) {
  13708. var series = this,
  13709. yAxis = this.yAxis,
  13710. options = series.options,
  13711. inverted = this.chart.inverted,
  13712. attr = {},
  13713. translatedThreshold;
  13714. if (hasSVG) { // VML is too slow anyway
  13715. if (init) {
  13716. attr.scaleY = 0.001;
  13717. translatedThreshold = mathMin(yAxis.pos + yAxis.len, mathMax(yAxis.pos, yAxis.toPixels(options.threshold)));
  13718. if (inverted) {
  13719. attr.translateX = translatedThreshold - yAxis.len;
  13720. } else {
  13721. attr.translateY = translatedThreshold;
  13722. }
  13723. series.group.attr(attr);
  13724. } else { // run the animation
  13725. attr.scaleY = 1;
  13726. attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos;
  13727. series.group.animate(attr, series.options.animation);
  13728. // delete this function to allow it only once
  13729. series.animate = null;
  13730. }
  13731. }
  13732. },
  13733. /**
  13734. * Remove this series from the chart
  13735. */
  13736. remove: function () {
  13737. var series = this,
  13738. chart = series.chart;
  13739. // column and bar series affects other series of the same type
  13740. // as they are either stacked or grouped
  13741. if (chart.hasRendered) {
  13742. each(chart.series, function (otherSeries) {
  13743. if (otherSeries.type === series.type) {
  13744. otherSeries.isDirty = true;
  13745. }
  13746. });
  13747. }
  13748. Series.prototype.remove.apply(series, arguments);
  13749. }
  13750. });
  13751. seriesTypes.column = ColumnSeries;
  13752. /**
  13753. * Set the default options for bar
  13754. */
  13755. defaultPlotOptions.bar = merge(defaultPlotOptions.column);
  13756. /**
  13757. * The Bar series class
  13758. */
  13759. var BarSeries = extendClass(ColumnSeries, {
  13760. type: 'bar',
  13761. inverted: true
  13762. });
  13763. seriesTypes.bar = BarSeries;
  13764. /**
  13765. * Set the default options for scatter
  13766. */
  13767. defaultPlotOptions.scatter = merge(defaultSeriesOptions, {
  13768. lineWidth: 0,
  13769. tooltip: {
  13770. headerFormat: '<span style="font-size: 10px; color:{series.color}">{series.name}</span><br/>',
  13771. pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>',
  13772. followPointer: true
  13773. },
  13774. stickyTracking: false
  13775. });
  13776. /**
  13777. * The scatter series class
  13778. */
  13779. var ScatterSeries = extendClass(Series, {
  13780. type: 'scatter',
  13781. sorted: false,
  13782. requireSorting: false,
  13783. noSharedTooltip: true,
  13784. trackerGroups: ['markerGroup'],
  13785. drawTracker: ColumnSeries.prototype.drawTracker,
  13786. setTooltipPoints: noop
  13787. });
  13788. seriesTypes.scatter = ScatterSeries;
  13789. /**
  13790. * Set the default options for pie
  13791. */
  13792. defaultPlotOptions.pie = merge(defaultSeriesOptions, {
  13793. borderColor: '#FFFFFF',
  13794. borderWidth: 1,
  13795. center: [null, null],
  13796. clip: false,
  13797. colorByPoint: true, // always true for pies
  13798. dataLabels: {
  13799. // align: null,
  13800. // connectorWidth: 1,
  13801. // connectorColor: point.color,
  13802. // connectorPadding: 5,
  13803. distance: 30,
  13804. enabled: true,
  13805. formatter: function () {
  13806. return this.point.name;
  13807. }
  13808. // softConnector: true,
  13809. //y: 0
  13810. },
  13811. ignoreHiddenPoint: true,
  13812. //innerSize: 0,
  13813. legendType: 'point',
  13814. marker: null, // point options are specified in the base options
  13815. size: null,
  13816. showInLegend: false,
  13817. slicedOffset: 10,
  13818. states: {
  13819. hover: {
  13820. brightness: 0.1,
  13821. shadow: false
  13822. }
  13823. },
  13824. stickyTracking: false,
  13825. tooltip: {
  13826. followPointer: true
  13827. }
  13828. });
  13829. /**
  13830. * Extended point object for pies
  13831. */
  13832. var PiePoint = extendClass(Point, {
  13833. /**
  13834. * Initiate the pie slice
  13835. */
  13836. init: function () {
  13837. Point.prototype.init.apply(this, arguments);
  13838. var point = this,
  13839. toggleSlice;
  13840. // Disallow negative values (#1530)
  13841. if (point.y < 0) {
  13842. point.y = null;
  13843. }
  13844. //visible: options.visible !== false,
  13845. extend(point, {
  13846. visible: point.visible !== false,
  13847. name: pick(point.name, 'Slice')
  13848. });
  13849. // add event listener for select
  13850. toggleSlice = function (e) {
  13851. point.slice(e.type === 'select');
  13852. };
  13853. addEvent(point, 'select', toggleSlice);
  13854. addEvent(point, 'unselect', toggleSlice);
  13855. return point;
  13856. },
  13857. /**
  13858. * Toggle the visibility of the pie slice
  13859. * @param {Boolean} vis Whether to show the slice or not. If undefined, the
  13860. * visibility is toggled
  13861. */
  13862. setVisible: function (vis) {
  13863. var point = this,
  13864. series = point.series,
  13865. chart = series.chart,
  13866. method;
  13867. // if called without an argument, toggle visibility
  13868. point.visible = point.options.visible = vis = vis === UNDEFINED ? !point.visible : vis;
  13869. series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data
  13870. method = vis ? 'show' : 'hide';
  13871. // Show and hide associated elements
  13872. each(['graphic', 'dataLabel', 'connector', 'shadowGroup'], function (key) {
  13873. if (point[key]) {
  13874. point[key][method]();
  13875. }
  13876. });
  13877. if (point.legendItem) {
  13878. chart.legend.colorizeItem(point, vis);
  13879. }
  13880. // Handle ignore hidden slices
  13881. if (!series.isDirty && series.options.ignoreHiddenPoint) {
  13882. series.isDirty = true;
  13883. chart.redraw();
  13884. }
  13885. },
  13886. /**
  13887. * Set or toggle whether the slice is cut out from the pie
  13888. * @param {Boolean} sliced When undefined, the slice state is toggled
  13889. * @param {Boolean} redraw Whether to redraw the chart. True by default.
  13890. */
  13891. slice: function (sliced, redraw, animation) {
  13892. var point = this,
  13893. series = point.series,
  13894. chart = series.chart,
  13895. translation;
  13896. setAnimation(animation, chart);
  13897. // redraw is true by default
  13898. redraw = pick(redraw, true);
  13899. // if called without an argument, toggle
  13900. point.sliced = point.options.sliced = sliced = defined(sliced) ? sliced : !point.sliced;
  13901. series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data
  13902. translation = sliced ? point.slicedTranslation : {
  13903. translateX: 0,
  13904. translateY: 0
  13905. };
  13906. point.graphic.animate(translation);
  13907. if (point.shadowGroup) {
  13908. point.shadowGroup.animate(translation);
  13909. }
  13910. }
  13911. });
  13912. /**
  13913. * The Pie series class
  13914. */
  13915. var PieSeries = {
  13916. type: 'pie',
  13917. isCartesian: false,
  13918. pointClass: PiePoint,
  13919. requireSorting: false,
  13920. noSharedTooltip: true,
  13921. trackerGroups: ['group', 'dataLabelsGroup'],
  13922. pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
  13923. stroke: 'borderColor',
  13924. 'stroke-width': 'borderWidth',
  13925. fill: 'color'
  13926. },
  13927. /**
  13928. * Pies have one color each point
  13929. */
  13930. getColor: noop,
  13931. /**
  13932. * Animate the pies in
  13933. */
  13934. animate: function (init) {
  13935. var series = this,
  13936. points = series.points,
  13937. startAngleRad = series.startAngleRad;
  13938. if (!init) {
  13939. each(points, function (point) {
  13940. var graphic = point.graphic,
  13941. args = point.shapeArgs;
  13942. if (graphic) {
  13943. // start values
  13944. graphic.attr({
  13945. r: series.center[3] / 2, // animate from inner radius (#779)
  13946. start: startAngleRad,
  13947. end: startAngleRad
  13948. });
  13949. // animate
  13950. graphic.animate({
  13951. r: args.r,
  13952. start: args.start,
  13953. end: args.end
  13954. }, series.options.animation);
  13955. }
  13956. });
  13957. // delete this function to allow it only once
  13958. series.animate = null;
  13959. }
  13960. },
  13961. /**
  13962. * Extend the basic setData method by running processData and generatePoints immediately,
  13963. * in order to access the points from the legend.
  13964. */
  13965. setData: function (data, redraw) {
  13966. Series.prototype.setData.call(this, data, false);
  13967. this.processData();
  13968. this.generatePoints();
  13969. if (pick(redraw, true)) {
  13970. this.chart.redraw();
  13971. }
  13972. },
  13973. /**
  13974. * Extend the generatePoints method by adding total and percentage properties to each point
  13975. */
  13976. generatePoints: function () {
  13977. var i,
  13978. total = 0,
  13979. points,
  13980. len,
  13981. point,
  13982. ignoreHiddenPoint = this.options.ignoreHiddenPoint;
  13983. Series.prototype.generatePoints.call(this);
  13984. // Populate local vars
  13985. points = this.points;
  13986. len = points.length;
  13987. // Get the total sum
  13988. for (i = 0; i < len; i++) {
  13989. point = points[i];
  13990. total += (ignoreHiddenPoint && !point.visible) ? 0 : point.y;
  13991. }
  13992. this.total = total;
  13993. // Set each point's properties
  13994. for (i = 0; i < len; i++) {
  13995. point = points[i];
  13996. point.percentage = total > 0 ? (point.y / total) * 100 : 0;
  13997. point.total = total;
  13998. }
  13999. },
  14000. /**
  14001. * Get the center of the pie based on the size and center options relative to the
  14002. * plot area. Borrowed by the polar and gauge series types.
  14003. */
  14004. getCenter: function () {
  14005. var options = this.options,
  14006. chart = this.chart,
  14007. slicingRoom = 2 * (options.slicedOffset || 0),
  14008. handleSlicingRoom,
  14009. plotWidth = chart.plotWidth - 2 * slicingRoom,
  14010. plotHeight = chart.plotHeight - 2 * slicingRoom,
  14011. centerOption = options.center,
  14012. positions = [pick(centerOption[0], '50%'), pick(centerOption[1], '50%'), options.size || '100%', options.innerSize || 0],
  14013. smallestSize = mathMin(plotWidth, plotHeight),
  14014. isPercent;
  14015. return map(positions, function (length, i) {
  14016. isPercent = /%$/.test(length);
  14017. handleSlicingRoom = i < 2 || (i === 2 && isPercent);
  14018. return (isPercent ?
  14019. // i == 0: centerX, relative to width
  14020. // i == 1: centerY, relative to height
  14021. // i == 2: size, relative to smallestSize
  14022. // i == 4: innerSize, relative to smallestSize
  14023. [plotWidth, plotHeight, smallestSize, smallestSize][i] *
  14024. pInt(length) / 100 :
  14025. length) + (handleSlicingRoom ? slicingRoom : 0);
  14026. });
  14027. },
  14028. /**
  14029. * Do translation for pie slices
  14030. */
  14031. translate: function (positions) {
  14032. this.generatePoints();
  14033. var series = this,
  14034. cumulative = 0,
  14035. precision = 1000, // issue #172
  14036. options = series.options,
  14037. slicedOffset = options.slicedOffset,
  14038. connectorOffset = slicedOffset + options.borderWidth,
  14039. start,
  14040. end,
  14041. angle,
  14042. startAngle = options.startAngle || 0,
  14043. startAngleRad = series.startAngleRad = mathPI / 180 * (startAngle - 90),
  14044. endAngleRad = series.endAngleRad = mathPI / 180 * ((options.endAngle || (startAngle + 360)) - 90), // docs
  14045. circ = endAngleRad - startAngleRad, //2 * mathPI,
  14046. points = series.points,
  14047. radiusX, // the x component of the radius vector for a given point
  14048. radiusY,
  14049. labelDistance = options.dataLabels.distance,
  14050. ignoreHiddenPoint = options.ignoreHiddenPoint,
  14051. i,
  14052. len = points.length,
  14053. point;
  14054. // Get positions - either an integer or a percentage string must be given.
  14055. // If positions are passed as a parameter, we're in a recursive loop for adjusting
  14056. // space for data labels.
  14057. if (!positions) {
  14058. series.center = positions = series.getCenter();
  14059. }
  14060. // utility for getting the x value from a given y, used for anticollision logic in data labels
  14061. series.getX = function (y, left) {
  14062. angle = math.asin((y - positions[1]) / (positions[2] / 2 + labelDistance));
  14063. return positions[0] +
  14064. (left ? -1 : 1) *
  14065. (mathCos(angle) * (positions[2] / 2 + labelDistance));
  14066. };
  14067. // Calculate the geometry for each point
  14068. for (i = 0; i < len; i++) {
  14069. point = points[i];
  14070. // set start and end angle
  14071. start = startAngleRad + (cumulative * circ);
  14072. if (!ignoreHiddenPoint || point.visible) {
  14073. cumulative += point.percentage / 100;
  14074. }
  14075. end = startAngleRad + (cumulative * circ);
  14076. // set the shape
  14077. point.shapeType = 'arc';
  14078. point.shapeArgs = {
  14079. x: positions[0],
  14080. y: positions[1],
  14081. r: positions[2] / 2,
  14082. innerR: positions[3] / 2,
  14083. start: mathRound(start * precision) / precision,
  14084. end: mathRound(end * precision) / precision
  14085. };
  14086. // center for the sliced out slice
  14087. angle = (end + start) / 2;
  14088. if (angle > 0.75 * circ) {
  14089. angle -= 2 * mathPI;
  14090. }
  14091. point.slicedTranslation = {
  14092. translateX: mathRound(mathCos(angle) * slicedOffset),
  14093. translateY: mathRound(mathSin(angle) * slicedOffset)
  14094. };
  14095. // set the anchor point for tooltips
  14096. radiusX = mathCos(angle) * positions[2] / 2;
  14097. radiusY = mathSin(angle) * positions[2] / 2;
  14098. point.tooltipPos = [
  14099. positions[0] + radiusX * 0.7,
  14100. positions[1] + radiusY * 0.7
  14101. ];
  14102. point.half = angle < -mathPI / 2 || angle > mathPI / 2 ? 1 : 0;
  14103. point.angle = angle;
  14104. // set the anchor point for data labels
  14105. connectorOffset = mathMin(connectorOffset, labelDistance / 2); // #1678
  14106. point.labelPos = [
  14107. positions[0] + radiusX + mathCos(angle) * labelDistance, // first break of connector
  14108. positions[1] + radiusY + mathSin(angle) * labelDistance, // a/a
  14109. positions[0] + radiusX + mathCos(angle) * connectorOffset, // second break, right outside pie
  14110. positions[1] + radiusY + mathSin(angle) * connectorOffset, // a/a
  14111. positions[0] + radiusX, // landing point for connector
  14112. positions[1] + radiusY, // a/a
  14113. labelDistance < 0 ? // alignment
  14114. 'center' :
  14115. point.half ? 'right' : 'left', // alignment
  14116. angle // center angle
  14117. ];
  14118. }
  14119. },
  14120. setTooltipPoints: noop,
  14121. drawGraph: null,
  14122. /**
  14123. * Draw the data points
  14124. */
  14125. drawPoints: function () {
  14126. var series = this,
  14127. chart = series.chart,
  14128. renderer = chart.renderer,
  14129. groupTranslation,
  14130. //center,
  14131. graphic,
  14132. //group,
  14133. shadow = series.options.shadow,
  14134. shadowGroup,
  14135. shapeArgs;
  14136. if (shadow && !series.shadowGroup) {
  14137. series.shadowGroup = renderer.g('shadow')
  14138. .add(series.group);
  14139. }
  14140. // draw the slices
  14141. each(series.points, function (point) {
  14142. graphic = point.graphic;
  14143. shapeArgs = point.shapeArgs;
  14144. shadowGroup = point.shadowGroup;
  14145. // put the shadow behind all points
  14146. if (shadow && !shadowGroup) {
  14147. shadowGroup = point.shadowGroup = renderer.g('shadow')
  14148. .add(series.shadowGroup);
  14149. }
  14150. // if the point is sliced, use special translation, else use plot area traslation
  14151. groupTranslation = point.sliced ? point.slicedTranslation : {
  14152. translateX: 0,
  14153. translateY: 0
  14154. };
  14155. //group.translate(groupTranslation[0], groupTranslation[1]);
  14156. if (shadowGroup) {
  14157. shadowGroup.attr(groupTranslation);
  14158. }
  14159. // draw the slice
  14160. if (graphic) {
  14161. graphic.animate(extend(shapeArgs, groupTranslation));
  14162. } else {
  14163. point.graphic = graphic = renderer.arc(shapeArgs)
  14164. .setRadialReference(series.center)
  14165. .attr(
  14166. point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE]
  14167. )
  14168. .attr({ 'stroke-linejoin': 'round' })
  14169. .attr(groupTranslation)
  14170. .add(series.group)
  14171. .shadow(shadow, shadowGroup);
  14172. }
  14173. // detect point specific visibility
  14174. if (point.visible === false) {
  14175. point.setVisible(false);
  14176. }
  14177. });
  14178. },
  14179. /**
  14180. * Utility for sorting data labels
  14181. */
  14182. sortByAngle: function (points, sign) {
  14183. points.sort(function (a, b) {
  14184. return a.angle !== undefined && (b.angle - a.angle) * sign;
  14185. });
  14186. },
  14187. /**
  14188. * Override the base drawDataLabels method by pie specific functionality
  14189. */
  14190. drawDataLabels: function () {
  14191. var series = this,
  14192. data = series.data,
  14193. point,
  14194. chart = series.chart,
  14195. options = series.options.dataLabels,
  14196. connectorPadding = pick(options.connectorPadding, 10),
  14197. connectorWidth = pick(options.connectorWidth, 1),
  14198. plotWidth = chart.plotWidth,
  14199. plotHeight = chart.plotHeight,
  14200. connector,
  14201. connectorPath,
  14202. softConnector = pick(options.softConnector, true),
  14203. distanceOption = options.distance,
  14204. seriesCenter = series.center,
  14205. radius = seriesCenter[2] / 2,
  14206. centerY = seriesCenter[1],
  14207. outside = distanceOption > 0,
  14208. dataLabel,
  14209. dataLabelWidth,
  14210. labelPos,
  14211. labelHeight,
  14212. halves = [// divide the points into right and left halves for anti collision
  14213. [], // right
  14214. [] // left
  14215. ],
  14216. x,
  14217. y,
  14218. visibility,
  14219. rankArr,
  14220. i,
  14221. j,
  14222. overflow = [0, 0, 0, 0], // top, right, bottom, left
  14223. sort = function (a, b) {
  14224. return b.y - a.y;
  14225. };
  14226. // get out if not enabled
  14227. if (!series.visible || (!options.enabled && !series._hasPointLabels)) {
  14228. return;
  14229. }
  14230. // run parent method
  14231. Series.prototype.drawDataLabels.apply(series);
  14232. // arrange points for detection collision
  14233. each(data, function (point) {
  14234. if (point.dataLabel) { // it may have been cancelled in the base method (#407)
  14235. halves[point.half].push(point);
  14236. }
  14237. });
  14238. // assume equal label heights
  14239. i = 0;
  14240. while (!labelHeight && data[i]) { // #1569
  14241. labelHeight = data[i] && data[i].dataLabel && (data[i].dataLabel.getBBox().height || 21); // 21 is for #968
  14242. i++;
  14243. }
  14244. /* Loop over the points in each half, starting from the top and bottom
  14245. * of the pie to detect overlapping labels.
  14246. */
  14247. i = 2;
  14248. while (i--) {
  14249. var slots = [],
  14250. slotsLength,
  14251. usedSlots = [],
  14252. points = halves[i],
  14253. pos,
  14254. length = points.length,
  14255. slotIndex;
  14256. // Sort by angle
  14257. series.sortByAngle(points, i - 0.5);
  14258. // Only do anti-collision when we are outside the pie and have connectors (#856)
  14259. if (distanceOption > 0) {
  14260. // build the slots
  14261. for (pos = centerY - radius - distanceOption; pos <= centerY + radius + distanceOption; pos += labelHeight) {
  14262. slots.push(pos);
  14263. // visualize the slot
  14264. /*
  14265. var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0),
  14266. slotY = pos + chart.plotTop;
  14267. if (!isNaN(slotX)) {
  14268. chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1)
  14269. .attr({
  14270. 'stroke-width': 1,
  14271. stroke: 'silver'
  14272. })
  14273. .add();
  14274. chart.renderer.text('Slot '+ (slots.length - 1), slotX, slotY + 4)
  14275. .attr({
  14276. fill: 'silver'
  14277. }).add();
  14278. }
  14279. */
  14280. }
  14281. slotsLength = slots.length;
  14282. // if there are more values than available slots, remove lowest values
  14283. if (length > slotsLength) {
  14284. // create an array for sorting and ranking the points within each quarter
  14285. rankArr = [].concat(points);
  14286. rankArr.sort(sort);
  14287. j = length;
  14288. while (j--) {
  14289. rankArr[j].rank = j;
  14290. }
  14291. j = length;
  14292. while (j--) {
  14293. if (points[j].rank >= slotsLength) {
  14294. points.splice(j, 1);
  14295. }
  14296. }
  14297. length = points.length;
  14298. }
  14299. // The label goes to the nearest open slot, but not closer to the edge than
  14300. // the label's index.
  14301. for (j = 0; j < length; j++) {
  14302. point = points[j];
  14303. labelPos = point.labelPos;
  14304. var closest = 9999,
  14305. distance,
  14306. slotI;
  14307. // find the closest slot index
  14308. for (slotI = 0; slotI < slotsLength; slotI++) {
  14309. distance = mathAbs(slots[slotI] - labelPos[1]);
  14310. if (distance < closest) {
  14311. closest = distance;
  14312. slotIndex = slotI;
  14313. }
  14314. }
  14315. // if that slot index is closer to the edges of the slots, move it
  14316. // to the closest appropriate slot
  14317. if (slotIndex < j && slots[j] !== null) { // cluster at the top
  14318. slotIndex = j;
  14319. } else if (slotsLength < length - j + slotIndex && slots[j] !== null) { // cluster at the bottom
  14320. slotIndex = slotsLength - length + j;
  14321. while (slots[slotIndex] === null) { // make sure it is not taken
  14322. slotIndex++;
  14323. }
  14324. } else {
  14325. // Slot is taken, find next free slot below. In the next run, the next slice will find the
  14326. // slot above these, because it is the closest one
  14327. while (slots[slotIndex] === null) { // make sure it is not taken
  14328. slotIndex++;
  14329. }
  14330. }
  14331. usedSlots.push({ i: slotIndex, y: slots[slotIndex] });
  14332. slots[slotIndex] = null; // mark as taken
  14333. }
  14334. // sort them in order to fill in from the top
  14335. usedSlots.sort(sort);
  14336. }
  14337. // now the used slots are sorted, fill them up sequentially
  14338. for (j = 0; j < length; j++) {
  14339. var slot, naturalY;
  14340. point = points[j];
  14341. labelPos = point.labelPos;
  14342. dataLabel = point.dataLabel;
  14343. visibility = point.visible === false ? HIDDEN : VISIBLE;
  14344. naturalY = labelPos[1];
  14345. if (distanceOption > 0) {
  14346. slot = usedSlots.pop();
  14347. slotIndex = slot.i;
  14348. // if the slot next to currrent slot is free, the y value is allowed
  14349. // to fall back to the natural position
  14350. y = slot.y;
  14351. if ((naturalY > y && slots[slotIndex + 1] !== null) ||
  14352. (naturalY < y && slots[slotIndex - 1] !== null)) {
  14353. y = naturalY;
  14354. }
  14355. } else {
  14356. y = naturalY;
  14357. }
  14358. // get the x - use the natural x position for first and last slot, to prevent the top
  14359. // and botton slice connectors from touching each other on either side
  14360. x = options.justify ?
  14361. seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption) :
  14362. series.getX(slotIndex === 0 || slotIndex === slots.length - 1 ? naturalY : y, i);
  14363. // Record the placement and visibility
  14364. dataLabel._attr = {
  14365. visibility: visibility,
  14366. align: labelPos[6]
  14367. };
  14368. dataLabel._pos = {
  14369. x: x + options.x +
  14370. ({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0),
  14371. y: y + options.y - 10 // 10 is for the baseline (label vs text)
  14372. };
  14373. dataLabel.connX = x;
  14374. dataLabel.connY = y;
  14375. // Detect overflowing data labels
  14376. if (this.options.size === null) {
  14377. dataLabelWidth = dataLabel.width;
  14378. // Overflow left
  14379. if (x - dataLabelWidth < connectorPadding) {
  14380. overflow[3] = mathMax(mathRound(dataLabelWidth - x + connectorPadding), overflow[3]);
  14381. // Overflow right
  14382. } else if (x + dataLabelWidth > plotWidth - connectorPadding) {
  14383. overflow[1] = mathMax(mathRound(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]);
  14384. }
  14385. // Overflow top
  14386. if (y - labelHeight / 2 < 0) {
  14387. overflow[0] = mathMax(mathRound(-y + labelHeight / 2), overflow[0]);
  14388. // Overflow left
  14389. } else if (y + labelHeight / 2 > plotHeight) {
  14390. overflow[2] = mathMax(mathRound(y + labelHeight / 2 - plotHeight), overflow[2]);
  14391. }
  14392. }
  14393. } // for each point
  14394. } // for each half
  14395. // Do not apply the final placement and draw the connectors until we have verified
  14396. // that labels are not spilling over.
  14397. if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) {
  14398. // Place the labels in the final position
  14399. this.placeDataLabels();
  14400. // Draw the connectors
  14401. if (outside && connectorWidth) {
  14402. each(this.points, function (point) {
  14403. connector = point.connector;
  14404. labelPos = point.labelPos;
  14405. dataLabel = point.dataLabel;
  14406. if (dataLabel && dataLabel._pos) {
  14407. visibility = dataLabel._attr.visibility;
  14408. x = dataLabel.connX;
  14409. y = dataLabel.connY;
  14410. connectorPath = softConnector ? [
  14411. M,
  14412. x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
  14413. 'C',
  14414. x, y, // first break, next to the label
  14415. 2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5],
  14416. labelPos[2], labelPos[3], // second break
  14417. L,
  14418. labelPos[4], labelPos[5] // base
  14419. ] : [
  14420. M,
  14421. x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
  14422. L,
  14423. labelPos[2], labelPos[3], // second break
  14424. L,
  14425. labelPos[4], labelPos[5] // base
  14426. ];
  14427. if (connector) {
  14428. connector.animate({ d: connectorPath });
  14429. connector.attr('visibility', visibility);
  14430. } else {
  14431. point.connector = connector = series.chart.renderer.path(connectorPath).attr({
  14432. 'stroke-width': connectorWidth,
  14433. stroke: options.connectorColor || point.color || '#606060',
  14434. visibility: visibility
  14435. })
  14436. .add(series.group);
  14437. }
  14438. } else if (connector) {
  14439. point.connector = connector.destroy();
  14440. }
  14441. });
  14442. }
  14443. }
  14444. },
  14445. /**
  14446. * Verify whether the data labels are allowed to draw, or we should run more translation and data
  14447. * label positioning to keep them inside the plot area. Returns true when data labels are ready
  14448. * to draw.
  14449. */
  14450. verifyDataLabelOverflow: function (overflow) {
  14451. var center = this.center,
  14452. options = this.options,
  14453. centerOption = options.center,
  14454. minSize = options.minSize || 80,
  14455. newSize = minSize,
  14456. ret;
  14457. // Handle horizontal size and center
  14458. if (centerOption[0] !== null) { // Fixed center
  14459. newSize = mathMax(center[2] - mathMax(overflow[1], overflow[3]), minSize);
  14460. } else { // Auto center
  14461. newSize = mathMax(
  14462. center[2] - overflow[1] - overflow[3], // horizontal overflow
  14463. minSize
  14464. );
  14465. center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center
  14466. }
  14467. // Handle vertical size and center
  14468. if (centerOption[1] !== null) { // Fixed center
  14469. newSize = mathMax(mathMin(newSize, center[2] - mathMax(overflow[0], overflow[2])), minSize);
  14470. } else { // Auto center
  14471. newSize = mathMax(
  14472. mathMin(
  14473. newSize,
  14474. center[2] - overflow[0] - overflow[2] // vertical overflow
  14475. ),
  14476. minSize
  14477. );
  14478. center[1] += (overflow[0] - overflow[2]) / 2; // vertical center
  14479. }
  14480. // If the size must be decreased, we need to run translate and drawDataLabels again
  14481. if (newSize < center[2]) {
  14482. center[2] = newSize;
  14483. this.translate(center);
  14484. each(this.points, function (point) {
  14485. if (point.dataLabel) {
  14486. point.dataLabel._pos = null; // reset
  14487. }
  14488. });
  14489. this.drawDataLabels();
  14490. // Else, return true to indicate that the pie and its labels is within the plot area
  14491. } else {
  14492. ret = true;
  14493. }
  14494. return ret;
  14495. },
  14496. /**
  14497. * Perform the final placement of the data labels after we have verified that they
  14498. * fall within the plot area.
  14499. */
  14500. placeDataLabels: function () {
  14501. each(this.points, function (point) {
  14502. var dataLabel = point.dataLabel,
  14503. _pos;
  14504. if (dataLabel) {
  14505. _pos = dataLabel._pos;
  14506. if (_pos) {
  14507. dataLabel.attr(dataLabel._attr);
  14508. dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos);
  14509. dataLabel.moved = true;
  14510. } else if (dataLabel) {
  14511. dataLabel.attr({ y: -999 });
  14512. }
  14513. }
  14514. });
  14515. },
  14516. alignDataLabel: noop,
  14517. /**
  14518. * Draw point specific tracker objects. Inherit directly from column series.
  14519. */
  14520. drawTracker: ColumnSeries.prototype.drawTracker,
  14521. /**
  14522. * Use a simple symbol from column prototype
  14523. */
  14524. drawLegendSymbol: AreaSeries.prototype.drawLegendSymbol,
  14525. /**
  14526. * Pies don't have point marker symbols
  14527. */
  14528. getSymbol: noop
  14529. };
  14530. PieSeries = extendClass(Series, PieSeries);
  14531. seriesTypes.pie = PieSeries;
  14532. // global variables
  14533. extend(Highcharts, {
  14534. // Constructors
  14535. Axis: Axis,
  14536. Chart: Chart,
  14537. Color: Color,
  14538. Legend: Legend,
  14539. Pointer: Pointer,
  14540. Point: Point,
  14541. Tick: Tick,
  14542. Tooltip: Tooltip,
  14543. Renderer: Renderer,
  14544. Series: Series,
  14545. SVGElement: SVGElement,
  14546. SVGRenderer: SVGRenderer,
  14547. // Various
  14548. arrayMin: arrayMin,
  14549. arrayMax: arrayMax,
  14550. charts: charts,
  14551. dateFormat: dateFormat,
  14552. format: format,
  14553. pathAnim: pathAnim,
  14554. getOptions: getOptions,
  14555. hasBidiBug: hasBidiBug,
  14556. isTouchDevice: isTouchDevice,
  14557. numberFormat: numberFormat,
  14558. seriesTypes: seriesTypes,
  14559. setOptions: setOptions,
  14560. addEvent: addEvent,
  14561. removeEvent: removeEvent,
  14562. createElement: createElement,
  14563. discardElement: discardElement,
  14564. css: css,
  14565. each: each,
  14566. extend: extend,
  14567. map: map,
  14568. merge: merge,
  14569. pick: pick,
  14570. splat: splat,
  14571. extendClass: extendClass,
  14572. pInt: pInt,
  14573. wrap: wrap,
  14574. svg: hasSVG,
  14575. canvas: useCanVG,
  14576. vml: !hasSVG && !useCanVG,
  14577. product: PRODUCT,
  14578. version: VERSION
  14579. });
  14580. }());