UU跑腿标准版

highcharts.src.js 457KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673
  1. // ==ClosureCompiler==
  2. // @compilation_level SIMPLE_OPTIMIZATIONS
  3. /**
  4. * @license Highcharts JS v4.0.1 (2014-04-24)
  5. *
  6. * (c) 2009-2014 Torstein Honsi
  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,
  42. symbolSizes = {},
  43. idCounter = 0,
  44. garbageBin,
  45. defaultOptions,
  46. dateFormat, // function
  47. globalAnimation,
  48. pathAnim,
  49. timeUnits,
  50. noop = function () {},
  51. charts = [],
  52. chartCount = 0,
  53. PRODUCT = 'Highcharts',
  54. VERSION = '4.0.1',
  55. // some constants for frequently used strings
  56. DIV = 'div',
  57. ABSOLUTE = 'absolute',
  58. RELATIVE = 'relative',
  59. HIDDEN = 'hidden',
  60. PREFIX = 'highcharts-',
  61. VISIBLE = 'visible',
  62. PX = 'px',
  63. NONE = 'none',
  64. M = 'M',
  65. L = 'L',
  66. numRegex = /^[0-9]+$/,
  67. NORMAL_STATE = '',
  68. HOVER_STATE = 'hover',
  69. SELECT_STATE = 'select',
  70. MILLISECOND = 'millisecond',
  71. SECOND = 'second',
  72. MINUTE = 'minute',
  73. HOUR = 'hour',
  74. DAY = 'day',
  75. WEEK = 'week',
  76. MONTH = 'month',
  77. YEAR = 'year',
  78. // Object for extending Axis
  79. AxisPlotLineOrBandExtension,
  80. // constants for attributes
  81. STROKE_WIDTH = 'stroke-width',
  82. // time methods, changed based on whether or not UTC is used
  83. makeTime,
  84. timezoneOffset,
  85. getMinutes,
  86. getHours,
  87. getDay,
  88. getDate,
  89. getMonth,
  90. getFullYear,
  91. setMinutes,
  92. setHours,
  93. setDate,
  94. setMonth,
  95. setFullYear,
  96. // lookup over the types and the associated classes
  97. seriesTypes = {};
  98. // The Highcharts namespace
  99. var Highcharts = win.Highcharts = win.Highcharts ? error(16, true) : {};
  100. /**
  101. * Extend an object with the members of another
  102. * @param {Object} a The object to be extended
  103. * @param {Object} b The object to add to the first one
  104. */
  105. function extend(a, b) {
  106. var n;
  107. if (!a) {
  108. a = {};
  109. }
  110. for (n in b) {
  111. a[n] = b[n];
  112. }
  113. return a;
  114. }
  115. /**
  116. * Deep merge two or more objects and return a third object. If the first argument is
  117. * true, the contents of the second object is copied into the first object.
  118. * Previously this function redirected to jQuery.extend(true), but this had two limitations.
  119. * First, it deep merged arrays, which lead to workarounds in Highcharts. Second,
  120. * it copied properties from extended prototypes.
  121. */
  122. function merge() {
  123. var i,
  124. args = arguments,
  125. len,
  126. ret = {},
  127. doCopy = function (copy, original) {
  128. var value, key;
  129. // An object is replacing a primitive
  130. if (typeof copy !== 'object') {
  131. copy = {};
  132. }
  133. for (key in original) {
  134. if (original.hasOwnProperty(key)) {
  135. value = original[key];
  136. // Copy the contents of objects, but not arrays or DOM nodes
  137. if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]'
  138. && key !== 'renderTo' && typeof value.nodeType !== 'number') {
  139. copy[key] = doCopy(copy[key] || {}, value);
  140. // Primitives and arrays are copied over directly
  141. } else {
  142. copy[key] = original[key];
  143. }
  144. }
  145. }
  146. return copy;
  147. };
  148. // If first argument is true, copy into the existing object. Used in setOptions.
  149. if (args[0] === true) {
  150. ret = args[1];
  151. args = Array.prototype.slice.call(args, 2);
  152. }
  153. // For each argument, extend the return
  154. len = args.length;
  155. for (i = 0; i < len; i++) {
  156. ret = doCopy(ret, args[i]);
  157. }
  158. return ret;
  159. }
  160. /**
  161. * Take an array and turn into a hash with even number arguments as keys and odd numbers as
  162. * values. Allows creating constants for commonly used style properties, attributes etc.
  163. * Avoid it in performance critical situations like looping
  164. */
  165. function hash() {
  166. var i = 0,
  167. args = arguments,
  168. length = args.length,
  169. obj = {};
  170. for (; i < length; i++) {
  171. obj[args[i++]] = args[i];
  172. }
  173. return obj;
  174. }
  175. /**
  176. * Shortcut for parseInt
  177. * @param {Object} s
  178. * @param {Number} mag Magnitude
  179. */
  180. function pInt(s, mag) {
  181. return parseInt(s, mag || 10);
  182. }
  183. /**
  184. * Check for string
  185. * @param {Object} s
  186. */
  187. function isString(s) {
  188. return typeof s === 'string';
  189. }
  190. /**
  191. * Check for object
  192. * @param {Object} obj
  193. */
  194. function isObject(obj) {
  195. return typeof obj === 'object';
  196. }
  197. /**
  198. * Check for array
  199. * @param {Object} obj
  200. */
  201. function isArray(obj) {
  202. return Object.prototype.toString.call(obj) === '[object Array]';
  203. }
  204. /**
  205. * Check for number
  206. * @param {Object} n
  207. */
  208. function isNumber(n) {
  209. return typeof n === 'number';
  210. }
  211. function log2lin(num) {
  212. return math.log(num) / math.LN10;
  213. }
  214. function lin2log(num) {
  215. return math.pow(10, num);
  216. }
  217. /**
  218. * Remove last occurence of an item from an array
  219. * @param {Array} arr
  220. * @param {Mixed} item
  221. */
  222. function erase(arr, item) {
  223. var i = arr.length;
  224. while (i--) {
  225. if (arr[i] === item) {
  226. arr.splice(i, 1);
  227. break;
  228. }
  229. }
  230. //return arr;
  231. }
  232. /**
  233. * Returns true if the object is not null or undefined. Like MooTools' $.defined.
  234. * @param {Object} obj
  235. */
  236. function defined(obj) {
  237. return obj !== UNDEFINED && obj !== null;
  238. }
  239. /**
  240. * Set or get an attribute or an object of attributes. Can't use jQuery attr because
  241. * it attempts to set expando properties on the SVG element, which is not allowed.
  242. *
  243. * @param {Object} elem The DOM element to receive the attribute(s)
  244. * @param {String|Object} prop The property or an abject of key-value pairs
  245. * @param {String} value The value if a single property is set
  246. */
  247. function attr(elem, prop, value) {
  248. var key,
  249. ret;
  250. // if the prop is a string
  251. if (isString(prop)) {
  252. // set the value
  253. if (defined(value)) {
  254. elem.setAttribute(prop, value);
  255. // get the value
  256. } else if (elem && elem.getAttribute) { // elem not defined when printing pie demo...
  257. ret = elem.getAttribute(prop);
  258. }
  259. // else if prop is defined, it is a hash of key/value pairs
  260. } else if (defined(prop) && isObject(prop)) {
  261. for (key in prop) {
  262. elem.setAttribute(key, prop[key]);
  263. }
  264. }
  265. return ret;
  266. }
  267. /**
  268. * Check if an element is an array, and if not, make it into an array. Like
  269. * MooTools' $.splat.
  270. */
  271. function splat(obj) {
  272. return isArray(obj) ? obj : [obj];
  273. }
  274. /**
  275. * Return the first value that is defined. Like MooTools' $.pick.
  276. */
  277. function pick() {
  278. var args = arguments,
  279. i,
  280. arg,
  281. length = args.length;
  282. for (i = 0; i < length; i++) {
  283. arg = args[i];
  284. if (typeof arg !== 'undefined' && arg !== null) {
  285. return arg;
  286. }
  287. }
  288. }
  289. /**
  290. * Set CSS on a given element
  291. * @param {Object} el
  292. * @param {Object} styles Style object with camel case property names
  293. */
  294. function css(el, styles) {
  295. if (isIE && !hasSVG) { // #2686
  296. if (styles && styles.opacity !== UNDEFINED) {
  297. styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')';
  298. }
  299. }
  300. extend(el.style, styles);
  301. }
  302. /**
  303. * Utility function to create element with attributes and styles
  304. * @param {Object} tag
  305. * @param {Object} attribs
  306. * @param {Object} styles
  307. * @param {Object} parent
  308. * @param {Object} nopad
  309. */
  310. function createElement(tag, attribs, styles, parent, nopad) {
  311. var el = doc.createElement(tag);
  312. if (attribs) {
  313. extend(el, attribs);
  314. }
  315. if (nopad) {
  316. css(el, {padding: 0, border: NONE, margin: 0});
  317. }
  318. if (styles) {
  319. css(el, styles);
  320. }
  321. if (parent) {
  322. parent.appendChild(el);
  323. }
  324. return el;
  325. }
  326. /**
  327. * Extend a prototyped class by new members
  328. * @param {Object} parent
  329. * @param {Object} members
  330. */
  331. function extendClass(parent, members) {
  332. var object = function () {};
  333. object.prototype = new parent();
  334. extend(object.prototype, members);
  335. return object;
  336. }
  337. /**
  338. * Format a number and return a string based on input settings
  339. * @param {Number} number The input number to format
  340. * @param {Number} decimals The amount of decimals
  341. * @param {String} decPoint The decimal point, defaults to the one given in the lang options
  342. * @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options
  343. */
  344. function numberFormat(number, decimals, decPoint, thousandsSep) {
  345. var lang = defaultOptions.lang,
  346. // http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/
  347. n = +number || 0,
  348. c = decimals === -1 ?
  349. (n.toString().split('.')[1] || '').length : // preserve decimals
  350. (isNaN(decimals = mathAbs(decimals)) ? 2 : decimals),
  351. d = decPoint === undefined ? lang.decimalPoint : decPoint,
  352. t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep,
  353. s = n < 0 ? "-" : "",
  354. i = String(pInt(n = mathAbs(n).toFixed(c))),
  355. j = i.length > 3 ? i.length % 3 : 0;
  356. return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) +
  357. (c ? d + mathAbs(n - i).toFixed(c).slice(2) : "");
  358. }
  359. /**
  360. * Pad a string to a given length by adding 0 to the beginning
  361. * @param {Number} number
  362. * @param {Number} length
  363. */
  364. function pad(number, length) {
  365. // Create an array of the remaining length +1 and join it with 0's
  366. return new Array((length || 2) + 1 - String(number).length).join(0) + number;
  367. }
  368. /**
  369. * Wrap a method with extended functionality, preserving the original function
  370. * @param {Object} obj The context object that the method belongs to
  371. * @param {String} method The name of the method to extend
  372. * @param {Function} func A wrapper function callback. This function is called with the same arguments
  373. * as the original function, except that the original function is unshifted and passed as the first
  374. * argument.
  375. */
  376. function wrap(obj, method, func) {
  377. var proceed = obj[method];
  378. obj[method] = function () {
  379. var args = Array.prototype.slice.call(arguments);
  380. args.unshift(proceed);
  381. return func.apply(this, args);
  382. };
  383. }
  384. /**
  385. * Based on http://www.php.net/manual/en/function.strftime.php
  386. * @param {String} format
  387. * @param {Number} timestamp
  388. * @param {Boolean} capitalize
  389. */
  390. dateFormat = function (format, timestamp, capitalize) {
  391. if (!defined(timestamp) || isNaN(timestamp)) {
  392. return 'Invalid date';
  393. }
  394. format = pick(format, '%Y-%m-%d %H:%M:%S');
  395. var date = new Date(timestamp - timezoneOffset),
  396. key, // used in for constuct below
  397. // get the basic time values
  398. hours = date[getHours](),
  399. day = date[getDay](),
  400. dayOfMonth = date[getDate](),
  401. month = date[getMonth](),
  402. fullYear = date[getFullYear](),
  403. lang = defaultOptions.lang,
  404. langWeekdays = lang.weekdays,
  405. // List all format keys. Custom formats can be added from the outside.
  406. replacements = extend({
  407. // Day
  408. 'a': langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon'
  409. 'A': langWeekdays[day], // Long weekday, like 'Monday'
  410. 'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31
  411. 'e': dayOfMonth, // Day of the month, 1 through 31
  412. // Week (none implemented)
  413. //'W': weekNumber(),
  414. // Month
  415. 'b': lang.shortMonths[month], // Short month, like 'Jan'
  416. 'B': lang.months[month], // Long month, like 'January'
  417. 'm': pad(month + 1), // Two digit month number, 01 through 12
  418. // Year
  419. 'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009
  420. 'Y': fullYear, // Four digits year, like 2009
  421. // Time
  422. 'H': pad(hours), // Two digits hours in 24h format, 00 through 23
  423. 'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11
  424. 'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12
  425. 'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59
  426. 'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM
  427. 'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM
  428. 'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59
  429. 'L': pad(mathRound(timestamp % 1000), 3) // Milliseconds (naming from Ruby)
  430. }, Highcharts.dateFormats);
  431. // do the replaces
  432. for (key in replacements) {
  433. while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster
  434. format = format.replace('%' + key, typeof replacements[key] === 'function' ? replacements[key](timestamp) : replacements[key]);
  435. }
  436. }
  437. // Optionally capitalize the string and return
  438. return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format;
  439. };
  440. /**
  441. * Format a single variable. Similar to sprintf, without the % prefix.
  442. */
  443. function formatSingle(format, val) {
  444. var floatRegex = /f$/,
  445. decRegex = /\.([0-9])/,
  446. lang = defaultOptions.lang,
  447. decimals;
  448. if (floatRegex.test(format)) { // float
  449. decimals = format.match(decRegex);
  450. decimals = decimals ? decimals[1] : -1;
  451. if (val !== null) {
  452. val = numberFormat(
  453. val,
  454. decimals,
  455. lang.decimalPoint,
  456. format.indexOf(',') > -1 ? lang.thousandsSep : ''
  457. );
  458. }
  459. } else {
  460. val = dateFormat(format, val);
  461. }
  462. return val;
  463. }
  464. /**
  465. * Format a string according to a subset of the rules of Python's String.format method.
  466. */
  467. function format(str, ctx) {
  468. var splitter = '{',
  469. isInside = false,
  470. segment,
  471. valueAndFormat,
  472. path,
  473. i,
  474. len,
  475. ret = [],
  476. val,
  477. index;
  478. while ((index = str.indexOf(splitter)) !== -1) {
  479. segment = str.slice(0, index);
  480. if (isInside) { // we're on the closing bracket looking back
  481. valueAndFormat = segment.split(':');
  482. path = valueAndFormat.shift().split('.'); // get first and leave format
  483. len = path.length;
  484. val = ctx;
  485. // Assign deeper paths
  486. for (i = 0; i < len; i++) {
  487. val = val[path[i]];
  488. }
  489. // Format the replacement
  490. if (valueAndFormat.length) {
  491. val = formatSingle(valueAndFormat.join(':'), val);
  492. }
  493. // Push the result and advance the cursor
  494. ret.push(val);
  495. } else {
  496. ret.push(segment);
  497. }
  498. str = str.slice(index + 1); // the rest
  499. isInside = !isInside; // toggle
  500. splitter = isInside ? '}' : '{'; // now look for next matching bracket
  501. }
  502. ret.push(str);
  503. return ret.join('');
  504. }
  505. /**
  506. * Get the magnitude of a number
  507. */
  508. function getMagnitude(num) {
  509. return math.pow(10, mathFloor(math.log(num) / math.LN10));
  510. }
  511. /**
  512. * Take an interval and normalize it to multiples of 1, 2, 2.5 and 5
  513. * @param {Number} interval
  514. * @param {Array} multiples
  515. * @param {Number} magnitude
  516. * @param {Object} options
  517. */
  518. function normalizeTickInterval(interval, multiples, magnitude, options) {
  519. var normalized, i;
  520. // round to a tenfold of 1, 2, 2.5 or 5
  521. magnitude = pick(magnitude, 1);
  522. normalized = interval / magnitude;
  523. // multiples for a linear scale
  524. if (!multiples) {
  525. multiples = [1, 2, 2.5, 5, 10];
  526. // the allowDecimals option
  527. if (options && options.allowDecimals === false) {
  528. if (magnitude === 1) {
  529. multiples = [1, 2, 5, 10];
  530. } else if (magnitude <= 0.1) {
  531. multiples = [1 / magnitude];
  532. }
  533. }
  534. }
  535. // normalize the interval to the nearest multiple
  536. for (i = 0; i < multiples.length; i++) {
  537. interval = multiples[i];
  538. if (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2) {
  539. break;
  540. }
  541. }
  542. // multiply back to the correct magnitude
  543. interval *= magnitude;
  544. return interval;
  545. }
  546. /**
  547. * Helper class that contains variuos counters that are local to the chart.
  548. */
  549. function ChartCounters() {
  550. this.color = 0;
  551. this.symbol = 0;
  552. }
  553. ChartCounters.prototype = {
  554. /**
  555. * Wraps the color counter if it reaches the specified length.
  556. */
  557. wrapColor: function (length) {
  558. if (this.color >= length) {
  559. this.color = 0;
  560. }
  561. },
  562. /**
  563. * Wraps the symbol counter if it reaches the specified length.
  564. */
  565. wrapSymbol: function (length) {
  566. if (this.symbol >= length) {
  567. this.symbol = 0;
  568. }
  569. }
  570. };
  571. /**
  572. * Utility method that sorts an object array and keeping the order of equal items.
  573. * ECMA script standard does not specify the behaviour when items are equal.
  574. */
  575. function stableSort(arr, sortFunction) {
  576. var length = arr.length,
  577. sortValue,
  578. i;
  579. // Add index to each item
  580. for (i = 0; i < length; i++) {
  581. arr[i].ss_i = i; // stable sort index
  582. }
  583. arr.sort(function (a, b) {
  584. sortValue = sortFunction(a, b);
  585. return sortValue === 0 ? a.ss_i - b.ss_i : sortValue;
  586. });
  587. // Remove index from items
  588. for (i = 0; i < length; i++) {
  589. delete arr[i].ss_i; // stable sort index
  590. }
  591. }
  592. /**
  593. * Non-recursive method to find the lowest member of an array. Math.min raises a maximum
  594. * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
  595. * method is slightly slower, but safe.
  596. */
  597. function arrayMin(data) {
  598. var i = data.length,
  599. min = data[0];
  600. while (i--) {
  601. if (data[i] < min) {
  602. min = data[i];
  603. }
  604. }
  605. return min;
  606. }
  607. /**
  608. * Non-recursive method to find the lowest member of an array. Math.min raises a maximum
  609. * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
  610. * method is slightly slower, but safe.
  611. */
  612. function arrayMax(data) {
  613. var i = data.length,
  614. max = data[0];
  615. while (i--) {
  616. if (data[i] > max) {
  617. max = data[i];
  618. }
  619. }
  620. return max;
  621. }
  622. /**
  623. * Utility method that destroys any SVGElement or VMLElement that are properties on the given object.
  624. * It loops all properties and invokes destroy if there is a destroy method. The property is
  625. * then delete'ed.
  626. * @param {Object} The object to destroy properties on
  627. * @param {Object} Exception, do not destroy this property, only delete it.
  628. */
  629. function destroyObjectProperties(obj, except) {
  630. var n;
  631. for (n in obj) {
  632. // If the object is non-null and destroy is defined
  633. if (obj[n] && obj[n] !== except && obj[n].destroy) {
  634. // Invoke the destroy
  635. obj[n].destroy();
  636. }
  637. // Delete the property from the object.
  638. delete obj[n];
  639. }
  640. }
  641. /**
  642. * Discard an element by moving it to the bin and delete
  643. * @param {Object} The HTML node to discard
  644. */
  645. function discardElement(element) {
  646. // create a garbage bin element, not part of the DOM
  647. if (!garbageBin) {
  648. garbageBin = createElement(DIV);
  649. }
  650. // move the node and empty bin
  651. if (element) {
  652. garbageBin.appendChild(element);
  653. }
  654. garbageBin.innerHTML = '';
  655. }
  656. /**
  657. * Provide error messages for debugging, with links to online explanation
  658. */
  659. function error(code, stop) {
  660. var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code;
  661. if (stop) {
  662. throw msg;
  663. } else if (win.console) {
  664. console.log(msg);
  665. }
  666. }
  667. /**
  668. * Fix JS round off float errors
  669. * @param {Number} num
  670. */
  671. function correctFloat(num) {
  672. return parseFloat(
  673. num.toPrecision(14)
  674. );
  675. }
  676. /**
  677. * Set the global animation to either a given value, or fall back to the
  678. * given chart's animation option
  679. * @param {Object} animation
  680. * @param {Object} chart
  681. */
  682. function setAnimation(animation, chart) {
  683. globalAnimation = pick(animation, chart.animation);
  684. }
  685. /**
  686. * The time unit lookup
  687. */
  688. /*jslint white: true*/
  689. timeUnits = hash(
  690. MILLISECOND, 1,
  691. SECOND, 1000,
  692. MINUTE, 60000,
  693. HOUR, 3600000,
  694. DAY, 24 * 3600000,
  695. WEEK, 7 * 24 * 3600000,
  696. MONTH, 31 * 24 * 3600000,
  697. YEAR, 31556952000
  698. );
  699. /*jslint white: false*/
  700. /**
  701. * Path interpolation algorithm used across adapters
  702. */
  703. pathAnim = {
  704. /**
  705. * Prepare start and end values so that the path can be animated one to one
  706. */
  707. init: function (elem, fromD, toD) {
  708. fromD = fromD || '';
  709. var shift = elem.shift,
  710. bezier = fromD.indexOf('C') > -1,
  711. numParams = bezier ? 7 : 3,
  712. endLength,
  713. slice,
  714. i,
  715. start = fromD.split(' '),
  716. end = [].concat(toD), // copy
  717. startBaseLine,
  718. endBaseLine,
  719. sixify = function (arr) { // in splines make move points have six parameters like bezier curves
  720. i = arr.length;
  721. while (i--) {
  722. if (arr[i] === M) {
  723. arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]);
  724. }
  725. }
  726. };
  727. if (bezier) {
  728. sixify(start);
  729. sixify(end);
  730. }
  731. // pull out the base lines before padding
  732. if (elem.isArea) {
  733. startBaseLine = start.splice(start.length - 6, 6);
  734. endBaseLine = end.splice(end.length - 6, 6);
  735. }
  736. // if shifting points, prepend a dummy point to the end path
  737. if (shift <= end.length / numParams && start.length === end.length) {
  738. while (shift--) {
  739. end = [].concat(end).splice(0, numParams).concat(end);
  740. }
  741. }
  742. elem.shift = 0; // reset for following animations
  743. // copy and append last point until the length matches the end length
  744. if (start.length) {
  745. endLength = end.length;
  746. while (start.length < endLength) {
  747. //bezier && sixify(start);
  748. slice = [].concat(start).splice(start.length - numParams, numParams);
  749. if (bezier) { // disable first control point
  750. slice[numParams - 6] = slice[numParams - 2];
  751. slice[numParams - 5] = slice[numParams - 1];
  752. }
  753. start = start.concat(slice);
  754. }
  755. }
  756. if (startBaseLine) { // append the base lines for areas
  757. start = start.concat(startBaseLine);
  758. end = end.concat(endBaseLine);
  759. }
  760. return [start, end];
  761. },
  762. /**
  763. * Interpolate each value of the path and return the array
  764. */
  765. step: function (start, end, pos, complete) {
  766. var ret = [],
  767. i = start.length,
  768. startVal;
  769. if (pos === 1) { // land on the final path without adjustment points appended in the ends
  770. ret = complete;
  771. } else if (i === end.length && pos < 1) {
  772. while (i--) {
  773. startVal = parseFloat(start[i]);
  774. ret[i] =
  775. isNaN(startVal) ? // a letter instruction like M or L
  776. start[i] :
  777. pos * (parseFloat(end[i] - startVal)) + startVal;
  778. }
  779. } else { // if animation is finished or length not matching, land on right value
  780. ret = end;
  781. }
  782. return ret;
  783. }
  784. };
  785. (function ($) {
  786. /**
  787. * The default HighchartsAdapter for jQuery
  788. */
  789. win.HighchartsAdapter = win.HighchartsAdapter || ($ && {
  790. /**
  791. * Initialize the adapter by applying some extensions to jQuery
  792. */
  793. init: function (pathAnim) {
  794. // extend the animate function to allow SVG animations
  795. var Fx = $.fx,
  796. Step = Fx.step,
  797. dSetter,
  798. Tween = $.Tween,
  799. propHooks = Tween && Tween.propHooks,
  800. opacityHook = $.cssHooks.opacity;
  801. /*jslint unparam: true*//* allow unused param x in this function */
  802. $.extend($.easing, {
  803. easeOutQuad: function (x, t, b, c, d) {
  804. return -c * (t /= d) * (t - 2) + b;
  805. }
  806. });
  807. /*jslint unparam: false*/
  808. // extend some methods to check for elem.attr, which means it is a Highcharts SVG object
  809. $.each(['cur', '_default', 'width', 'height', 'opacity'], function (i, fn) {
  810. var obj = Step,
  811. base;
  812. // Handle different parent objects
  813. if (fn === 'cur') {
  814. obj = Fx.prototype; // 'cur', the getter, relates to Fx.prototype
  815. } else if (fn === '_default' && Tween) { // jQuery 1.8 model
  816. obj = propHooks[fn];
  817. fn = 'set';
  818. }
  819. // Overwrite the method
  820. base = obj[fn];
  821. if (base) { // step.width and step.height don't exist in jQuery < 1.7
  822. // create the extended function replacement
  823. obj[fn] = function (fx) {
  824. var elem;
  825. // Fx.prototype.cur does not use fx argument
  826. fx = i ? fx : this;
  827. // Don't run animations on textual properties like align (#1821)
  828. if (fx.prop === 'align') {
  829. return;
  830. }
  831. // shortcut
  832. elem = fx.elem;
  833. // Fx.prototype.cur returns the current value. The other ones are setters
  834. // and returning a value has no effect.
  835. return elem.attr ? // is SVG element wrapper
  836. elem.attr(fx.prop, fn === 'cur' ? UNDEFINED : fx.now) : // apply the SVG wrapper's method
  837. base.apply(this, arguments); // use jQuery's built-in method
  838. };
  839. }
  840. });
  841. // Extend the opacity getter, needed for fading opacity with IE9 and jQuery 1.10+
  842. wrap(opacityHook, 'get', function (proceed, elem, computed) {
  843. return elem.attr ? (elem.opacity || 0) : proceed.call(this, elem, computed);
  844. });
  845. // Define the setter function for d (path definitions)
  846. dSetter = function (fx) {
  847. var elem = fx.elem,
  848. ends;
  849. // Normally start and end should be set in state == 0, but sometimes,
  850. // for reasons unknown, this doesn't happen. Perhaps state == 0 is skipped
  851. // in these cases
  852. if (!fx.started) {
  853. ends = pathAnim.init(elem, elem.d, elem.toD);
  854. fx.start = ends[0];
  855. fx.end = ends[1];
  856. fx.started = true;
  857. }
  858. // interpolate each value of the path
  859. elem.attr('d', pathAnim.step(fx.start, fx.end, fx.pos, elem.toD));
  860. };
  861. // jQuery 1.8 style
  862. if (Tween) {
  863. propHooks.d = {
  864. set: dSetter
  865. };
  866. // pre 1.8
  867. } else {
  868. // animate paths
  869. Step.d = dSetter;
  870. }
  871. /**
  872. * Utility for iterating over an array. Parameters are reversed compared to jQuery.
  873. * @param {Array} arr
  874. * @param {Function} fn
  875. */
  876. this.each = Array.prototype.forEach ?
  877. function (arr, fn) { // modern browsers
  878. return Array.prototype.forEach.call(arr, fn);
  879. } :
  880. function (arr, fn) { // legacy
  881. var i = 0,
  882. len = arr.length;
  883. for (; i < len; i++) {
  884. if (fn.call(arr[i], arr[i], i, arr) === false) {
  885. return i;
  886. }
  887. }
  888. };
  889. /**
  890. * Register Highcharts as a plugin in the respective framework
  891. */
  892. $.fn.highcharts = function () {
  893. var constr = 'Chart', // default constructor
  894. args = arguments,
  895. options,
  896. ret,
  897. chart;
  898. if (this[0]) {
  899. if (isString(args[0])) {
  900. constr = args[0];
  901. args = Array.prototype.slice.call(args, 1);
  902. }
  903. options = args[0];
  904. // Create the chart
  905. if (options !== UNDEFINED) {
  906. /*jslint unused:false*/
  907. options.chart = options.chart || {};
  908. options.chart.renderTo = this[0];
  909. chart = new Highcharts[constr](options, args[1]);
  910. ret = this;
  911. /*jslint unused:true*/
  912. }
  913. // When called without parameters or with the return argument, get a predefined chart
  914. if (options === UNDEFINED) {
  915. ret = charts[attr(this[0], 'data-highcharts-chart')];
  916. }
  917. }
  918. return ret;
  919. };
  920. },
  921. /**
  922. * Downloads a script and executes a callback when done.
  923. * @param {String} scriptLocation
  924. * @param {Function} callback
  925. */
  926. getScript: $.getScript,
  927. /**
  928. * Return the index of an item in an array, or -1 if not found
  929. */
  930. inArray: $.inArray,
  931. /**
  932. * A direct link to jQuery methods. MooTools and Prototype adapters must be implemented for each case of method.
  933. * @param {Object} elem The HTML element
  934. * @param {String} method Which method to run on the wrapped element
  935. */
  936. adapterRun: function (elem, method) {
  937. return $(elem)[method]();
  938. },
  939. /**
  940. * Filter an array
  941. */
  942. grep: $.grep,
  943. /**
  944. * Map an array
  945. * @param {Array} arr
  946. * @param {Function} fn
  947. */
  948. map: function (arr, fn) {
  949. //return jQuery.map(arr, fn);
  950. var results = [],
  951. i = 0,
  952. len = arr.length;
  953. for (; i < len; i++) {
  954. results[i] = fn.call(arr[i], arr[i], i, arr);
  955. }
  956. return results;
  957. },
  958. /**
  959. * Get the position of an element relative to the top left of the page
  960. */
  961. offset: function (el) {
  962. return $(el).offset();
  963. },
  964. /**
  965. * Add an event listener
  966. * @param {Object} el A HTML element or custom object
  967. * @param {String} event The event type
  968. * @param {Function} fn The event handler
  969. */
  970. addEvent: function (el, event, fn) {
  971. $(el).bind(event, fn);
  972. },
  973. /**
  974. * Remove event added with addEvent
  975. * @param {Object} el The object
  976. * @param {String} eventType The event type. Leave blank to remove all events.
  977. * @param {Function} handler The function to remove
  978. */
  979. removeEvent: function (el, eventType, handler) {
  980. // workaround for jQuery issue with unbinding custom events:
  981. // http://forum.jQuery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jQuery-1-4-2
  982. var func = doc.removeEventListener ? 'removeEventListener' : 'detachEvent';
  983. if (doc[func] && el && !el[func]) {
  984. el[func] = function () {};
  985. }
  986. $(el).unbind(eventType, handler);
  987. },
  988. /**
  989. * Fire an event on a custom object
  990. * @param {Object} el
  991. * @param {String} type
  992. * @param {Object} eventArguments
  993. * @param {Function} defaultFunction
  994. */
  995. fireEvent: function (el, type, eventArguments, defaultFunction) {
  996. var event = $.Event(type),
  997. detachedType = 'detached' + type,
  998. defaultPrevented;
  999. // Remove warnings in Chrome when accessing returnValue (#2790), layerX and layerY. Although Highcharts
  1000. // never uses these properties, Chrome includes them in the default click event and
  1001. // raises the warning when they are copied over in the extend statement below.
  1002. //
  1003. // To avoid problems in IE (see #1010) where we cannot delete the properties and avoid
  1004. // testing if they are there (warning in chrome) the only option is to test if running IE.
  1005. if (!isIE && eventArguments) {
  1006. delete eventArguments.layerX;
  1007. delete eventArguments.layerY;
  1008. delete eventArguments.returnValue;
  1009. }
  1010. extend(event, eventArguments);
  1011. // Prevent jQuery from triggering the object method that is named the
  1012. // same as the event. For example, if the event is 'select', jQuery
  1013. // attempts calling el.select and it goes into a loop.
  1014. if (el[type]) {
  1015. el[detachedType] = el[type];
  1016. el[type] = null;
  1017. }
  1018. // Wrap preventDefault and stopPropagation in try/catch blocks in
  1019. // order to prevent JS errors when cancelling events on non-DOM
  1020. // objects. #615.
  1021. /*jslint unparam: true*/
  1022. $.each(['preventDefault', 'stopPropagation'], function (i, fn) {
  1023. var base = event[fn];
  1024. event[fn] = function () {
  1025. try {
  1026. base.call(event);
  1027. } catch (e) {
  1028. if (fn === 'preventDefault') {
  1029. defaultPrevented = true;
  1030. }
  1031. }
  1032. };
  1033. });
  1034. /*jslint unparam: false*/
  1035. // trigger it
  1036. $(el).trigger(event);
  1037. // attach the method
  1038. if (el[detachedType]) {
  1039. el[type] = el[detachedType];
  1040. el[detachedType] = null;
  1041. }
  1042. if (defaultFunction && !event.isDefaultPrevented() && !defaultPrevented) {
  1043. defaultFunction(event);
  1044. }
  1045. },
  1046. /**
  1047. * Extension method needed for MooTools
  1048. */
  1049. washMouseEvent: function (e) {
  1050. var ret = e.originalEvent || e;
  1051. // computed by jQuery, needed by IE8
  1052. if (ret.pageX === UNDEFINED) { // #1236
  1053. ret.pageX = e.pageX;
  1054. ret.pageY = e.pageY;
  1055. }
  1056. return ret;
  1057. },
  1058. /**
  1059. * Animate a HTML element or SVG element wrapper
  1060. * @param {Object} el
  1061. * @param {Object} params
  1062. * @param {Object} options jQuery-like animation options: duration, easing, callback
  1063. */
  1064. animate: function (el, params, options) {
  1065. var $el = $(el);
  1066. if (!el.style) {
  1067. el.style = {}; // #1881
  1068. }
  1069. if (params.d) {
  1070. el.toD = params.d; // keep the array form for paths, used in $.fx.step.d
  1071. params.d = 1; // because in jQuery, animating to an array has a different meaning
  1072. }
  1073. $el.stop();
  1074. if (params.opacity !== UNDEFINED && el.attr) {
  1075. params.opacity += 'px'; // force jQuery to use same logic as width and height (#2161)
  1076. }
  1077. $el.animate(params, options);
  1078. },
  1079. /**
  1080. * Stop running animation
  1081. */
  1082. stop: function (el) {
  1083. $(el).stop();
  1084. }
  1085. });
  1086. }(win.jQuery));
  1087. // check for a custom HighchartsAdapter defined prior to this file
  1088. var globalAdapter = win.HighchartsAdapter,
  1089. adapter = globalAdapter || {};
  1090. // Initialize the adapter
  1091. if (globalAdapter) {
  1092. globalAdapter.init.call(globalAdapter, pathAnim);
  1093. }
  1094. // Utility functions. If the HighchartsAdapter is not defined, adapter is an empty object
  1095. // and all the utility functions will be null. In that case they are populated by the
  1096. // default adapters below.
  1097. var adapterRun = adapter.adapterRun,
  1098. getScript = adapter.getScript,
  1099. inArray = adapter.inArray,
  1100. each = adapter.each,
  1101. grep = adapter.grep,
  1102. offset = adapter.offset,
  1103. map = adapter.map,
  1104. addEvent = adapter.addEvent,
  1105. removeEvent = adapter.removeEvent,
  1106. fireEvent = adapter.fireEvent,
  1107. washMouseEvent = adapter.washMouseEvent,
  1108. animate = adapter.animate,
  1109. stop = adapter.stop;
  1110. /* ****************************************************************************
  1111. * Handle the options *
  1112. *****************************************************************************/
  1113. var
  1114. defaultLabelOptions = {
  1115. enabled: true,
  1116. // rotation: 0,
  1117. // align: 'center',
  1118. x: 0,
  1119. y: 15,
  1120. /*formatter: function () {
  1121. return this.value;
  1122. },*/
  1123. style: {
  1124. color: '#606060',
  1125. cursor: 'default',
  1126. fontSize: '11px'
  1127. }
  1128. };
  1129. defaultOptions = {
  1130. colors: ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c',
  1131. '#8085e9', '#f15c80', '#e4d354', '#8085e8', '#8d4653', '#91e8e1'], // docs
  1132. symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'],
  1133. lang: {
  1134. loading: 'Loading...',
  1135. months: ['January', 'February', 'March', 'April', 'May', 'June', 'July',
  1136. 'August', 'September', 'October', 'November', 'December'],
  1137. shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  1138. weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  1139. decimalPoint: '.',
  1140. numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels
  1141. resetZoom: 'Reset zoom',
  1142. resetZoomTitle: 'Reset zoom level 1:1',
  1143. thousandsSep: ','
  1144. },
  1145. global: {
  1146. useUTC: true,
  1147. //timezoneOffset: 0,
  1148. canvasToolsURL: 'http://code.highcharts.com/4.0.1/modules/canvas-tools.js',
  1149. VMLRadialGradientURL: 'http://code.highcharts.com/4.0.1/gfx/vml-radial-gradient.png'
  1150. },
  1151. chart: {
  1152. //animation: true,
  1153. //alignTicks: false,
  1154. //reflow: true,
  1155. //className: null,
  1156. //events: { load, selection },
  1157. //margin: [null],
  1158. //marginTop: null,
  1159. //marginRight: null,
  1160. //marginBottom: null,
  1161. //marginLeft: null,
  1162. borderColor: '#4572A7',
  1163. //borderWidth: 0,
  1164. borderRadius: 0,
  1165. defaultSeriesType: 'line',
  1166. ignoreHiddenSeries: true,
  1167. //inverted: false,
  1168. //shadow: false,
  1169. spacing: [10, 10, 15, 10],
  1170. //spacingTop: 10,
  1171. //spacingRight: 10,
  1172. //spacingBottom: 15,
  1173. //spacingLeft: 10,
  1174. //style: {
  1175. // fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font
  1176. // fontSize: '12px'
  1177. //},
  1178. backgroundColor: '#FFFFFF',
  1179. //plotBackgroundColor: null,
  1180. plotBorderColor: '#C0C0C0',
  1181. //plotBorderWidth: 0,
  1182. //plotShadow: false,
  1183. //zoomType: ''
  1184. resetZoomButton: {
  1185. theme: {
  1186. zIndex: 20
  1187. },
  1188. position: {
  1189. align: 'right',
  1190. x: -10,
  1191. //verticalAlign: 'top',
  1192. y: 10
  1193. }
  1194. // relativeTo: 'plot'
  1195. }
  1196. },
  1197. title: {
  1198. text: 'Chart title',
  1199. align: 'center',
  1200. // floating: false,
  1201. margin: 15,
  1202. // x: 0,
  1203. // verticalAlign: 'top',
  1204. // y: null,
  1205. style: {
  1206. color: '#333333', // docs
  1207. fontSize: '18px'
  1208. }
  1209. },
  1210. subtitle: {
  1211. text: '',
  1212. align: 'center',
  1213. // floating: false
  1214. // x: 0,
  1215. // verticalAlign: 'top',
  1216. // y: null,
  1217. style: {
  1218. color: '#555555' // docs
  1219. }
  1220. },
  1221. plotOptions: {
  1222. line: { // base series options
  1223. allowPointSelect: false,
  1224. showCheckbox: false,
  1225. animation: {
  1226. duration: 1000
  1227. },
  1228. //connectNulls: false,
  1229. //cursor: 'default',
  1230. //clip: true,
  1231. //dashStyle: null,
  1232. //enableMouseTracking: true,
  1233. events: {},
  1234. //legendIndex: 0,
  1235. //linecap: 'round',
  1236. lineWidth: 2,
  1237. //shadow: false,
  1238. // stacking: null,
  1239. marker: {
  1240. //enabled: true,
  1241. //symbol: null,
  1242. lineWidth: 0,
  1243. radius: 4,
  1244. lineColor: '#FFFFFF',
  1245. //fillColor: null,
  1246. states: { // states for a single point
  1247. hover: {
  1248. enabled: true
  1249. //radius: base + 2
  1250. },
  1251. select: {
  1252. fillColor: '#FFFFFF',
  1253. lineColor: '#000000',
  1254. lineWidth: 2
  1255. }
  1256. }
  1257. },
  1258. point: {
  1259. events: {}
  1260. },
  1261. dataLabels: merge(defaultLabelOptions, {
  1262. align: 'center',
  1263. //defer: true,
  1264. enabled: false,
  1265. formatter: function () {
  1266. return this.y === null ? '' : numberFormat(this.y, -1);
  1267. },
  1268. verticalAlign: 'bottom', // above singular point
  1269. y: 0
  1270. // backgroundColor: undefined,
  1271. // borderColor: undefined,
  1272. // borderRadius: undefined,
  1273. // borderWidth: undefined,
  1274. // padding: 3,
  1275. // shadow: false
  1276. }),
  1277. cropThreshold: 300, // draw points outside the plot area when the number of points is less than this
  1278. pointRange: 0,
  1279. //pointStart: 0,
  1280. //pointInterval: 1,
  1281. //showInLegend: null, // auto: true for standalone series, false for linked series
  1282. states: { // states for the entire series
  1283. hover: {
  1284. //enabled: false,
  1285. //lineWidth: base + 1,
  1286. marker: {
  1287. // lineWidth: base + 1,
  1288. // radius: base + 1
  1289. },
  1290. halo: {
  1291. size: 10,
  1292. opacity: 0.25
  1293. }
  1294. },
  1295. select: {
  1296. marker: {}
  1297. }
  1298. },
  1299. stickyTracking: true,
  1300. //tooltip: {
  1301. //pointFormat: '<span style="color:{series.color}">\u25CF</span> {series.name}: <b>{point.y}</b>'
  1302. //valueDecimals: null,
  1303. //xDateFormat: '%A, %b %e, %Y',
  1304. //valuePrefix: '',
  1305. //ySuffix: ''
  1306. //}
  1307. turboThreshold: 1000
  1308. // zIndex: null
  1309. }
  1310. },
  1311. labels: {
  1312. //items: [],
  1313. style: {
  1314. //font: defaultFont,
  1315. position: ABSOLUTE,
  1316. color: '#3E576F'
  1317. }
  1318. },
  1319. legend: {
  1320. enabled: true,
  1321. align: 'center',
  1322. //floating: false,
  1323. layout: 'horizontal',
  1324. labelFormatter: function () {
  1325. return this.name;
  1326. },
  1327. //borderWidth: 0,
  1328. borderColor: '#909090',
  1329. borderRadius: 0, // docs
  1330. navigation: {
  1331. // animation: true,
  1332. activeColor: '#274b6d',
  1333. // arrowSize: 12
  1334. inactiveColor: '#CCC'
  1335. // style: {} // text styles
  1336. },
  1337. // margin: 20,
  1338. // reversed: false,
  1339. shadow: false,
  1340. // backgroundColor: null,
  1341. /*style: {
  1342. padding: '5px'
  1343. },*/
  1344. itemStyle: {
  1345. color: '#333333', // docs
  1346. fontSize: '12px',
  1347. fontWeight: 'bold' // docs
  1348. },
  1349. itemHoverStyle: {
  1350. //cursor: 'pointer', removed as of #601
  1351. color: '#000'
  1352. },
  1353. itemHiddenStyle: {
  1354. color: '#CCC'
  1355. },
  1356. itemCheckboxStyle: {
  1357. position: ABSOLUTE,
  1358. width: '13px', // for IE precision
  1359. height: '13px'
  1360. },
  1361. // itemWidth: undefined,
  1362. // symbolRadius: 0,
  1363. // symbolWidth: 16,
  1364. symbolPadding: 5,
  1365. verticalAlign: 'bottom',
  1366. // width: undefined,
  1367. x: 0,
  1368. y: 0,
  1369. title: {
  1370. //text: null,
  1371. style: {
  1372. fontWeight: 'bold'
  1373. }
  1374. }
  1375. },
  1376. loading: {
  1377. // hideDuration: 100,
  1378. labelStyle: {
  1379. fontWeight: 'bold',
  1380. position: RELATIVE,
  1381. top: '1em'
  1382. },
  1383. // showDuration: 0,
  1384. style: {
  1385. position: ABSOLUTE,
  1386. backgroundColor: 'white',
  1387. opacity: 0.5,
  1388. textAlign: 'center'
  1389. }
  1390. },
  1391. tooltip: {
  1392. enabled: true,
  1393. animation: hasSVG,
  1394. //crosshairs: null,
  1395. backgroundColor: 'rgba(249, 249, 249, .85)',
  1396. borderWidth: 1,
  1397. borderRadius: 3,
  1398. dateTimeLabelFormats: {
  1399. millisecond: '%A, %b %e, %H:%M:%S.%L',
  1400. second: '%A, %b %e, %H:%M:%S',
  1401. minute: '%A, %b %e, %H:%M',
  1402. hour: '%A, %b %e, %H:%M',
  1403. day: '%A, %b %e, %Y',
  1404. week: 'Week from %A, %b %e, %Y',
  1405. month: '%B %Y',
  1406. year: '%Y'
  1407. },
  1408. //formatter: defaultFormatter,
  1409. headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>',
  1410. pointFormat: '<span style="color:{series.color}">\u25CF</span> {series.name}: <b>{point.y}</b><br/>', // docs
  1411. shadow: true,
  1412. //shape: 'calout',
  1413. //shared: false,
  1414. snap: isTouchDevice ? 25 : 10,
  1415. style: {
  1416. color: '#333333',
  1417. cursor: 'default',
  1418. fontSize: '12px',
  1419. padding: '8px',
  1420. whiteSpace: 'nowrap'
  1421. }
  1422. //xDateFormat: '%A, %b %e, %Y',
  1423. //valueDecimals: null,
  1424. //valuePrefix: '',
  1425. //valueSuffix: ''
  1426. },
  1427. credits: {
  1428. enabled: true,
  1429. text: 'Highcharts.com',
  1430. href: 'http://www.highcharts.com',
  1431. position: {
  1432. align: 'right',
  1433. x: -10,
  1434. verticalAlign: 'bottom',
  1435. y: -5
  1436. },
  1437. style: {
  1438. cursor: 'pointer',
  1439. color: '#909090',
  1440. fontSize: '9px'
  1441. }
  1442. }
  1443. };
  1444. // Series defaults
  1445. var defaultPlotOptions = defaultOptions.plotOptions,
  1446. defaultSeriesOptions = defaultPlotOptions.line;
  1447. // set the default time methods
  1448. setTimeMethods();
  1449. /**
  1450. * Set the time methods globally based on the useUTC option. Time method can be either
  1451. * local time or UTC (default).
  1452. */
  1453. function setTimeMethods() {
  1454. var useUTC = defaultOptions.global.useUTC,
  1455. GET = useUTC ? 'getUTC' : 'get',
  1456. SET = useUTC ? 'setUTC' : 'set';
  1457. timezoneOffset = ((useUTC && defaultOptions.global.timezoneOffset) || 0) * 60000;
  1458. makeTime = useUTC ? Date.UTC : function (year, month, date, hours, minutes, seconds) {
  1459. return new Date(
  1460. year,
  1461. month,
  1462. pick(date, 1),
  1463. pick(hours, 0),
  1464. pick(minutes, 0),
  1465. pick(seconds, 0)
  1466. ).getTime();
  1467. };
  1468. getMinutes = GET + 'Minutes';
  1469. getHours = GET + 'Hours';
  1470. getDay = GET + 'Day';
  1471. getDate = GET + 'Date';
  1472. getMonth = GET + 'Month';
  1473. getFullYear = GET + 'FullYear';
  1474. setMinutes = SET + 'Minutes';
  1475. setHours = SET + 'Hours';
  1476. setDate = SET + 'Date';
  1477. setMonth = SET + 'Month';
  1478. setFullYear = SET + 'FullYear';
  1479. }
  1480. /**
  1481. * Merge the default options with custom options and return the new options structure
  1482. * @param {Object} options The new custom options
  1483. */
  1484. function setOptions(options) {
  1485. // Copy in the default options
  1486. defaultOptions = merge(true, defaultOptions, options);
  1487. // Apply UTC
  1488. setTimeMethods();
  1489. return defaultOptions;
  1490. }
  1491. /**
  1492. * Get the updated default options. Until 3.0.7, merely exposing defaultOptions for outside modules
  1493. * wasn't enough because the setOptions method created a new object.
  1494. */
  1495. function getOptions() {
  1496. return defaultOptions;
  1497. }
  1498. /**
  1499. * Handle color operations. The object methods are chainable.
  1500. * @param {String} input The input color in either rbga or hex format
  1501. */
  1502. var rgbaRegEx = /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*\)/,
  1503. hexRegEx = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/,
  1504. rgbRegEx = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/;
  1505. var Color = function (input) {
  1506. // declare variables
  1507. var rgba = [], result, stops;
  1508. /**
  1509. * Parse the input color to rgba array
  1510. * @param {String} input
  1511. */
  1512. function init(input) {
  1513. // Gradients
  1514. if (input && input.stops) {
  1515. stops = map(input.stops, function (stop) {
  1516. return Color(stop[1]);
  1517. });
  1518. // Solid colors
  1519. } else {
  1520. // rgba
  1521. result = rgbaRegEx.exec(input);
  1522. if (result) {
  1523. rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)];
  1524. } else {
  1525. // hex
  1526. result = hexRegEx.exec(input);
  1527. if (result) {
  1528. rgba = [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1];
  1529. } else {
  1530. // rgb
  1531. result = rgbRegEx.exec(input);
  1532. if (result) {
  1533. rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1];
  1534. }
  1535. }
  1536. }
  1537. }
  1538. }
  1539. /**
  1540. * Return the color a specified format
  1541. * @param {String} format
  1542. */
  1543. function get(format) {
  1544. var ret;
  1545. if (stops) {
  1546. ret = merge(input);
  1547. ret.stops = [].concat(ret.stops);
  1548. each(stops, function (stop, i) {
  1549. ret.stops[i] = [ret.stops[i][0], stop.get(format)];
  1550. });
  1551. // it's NaN if gradient colors on a column chart
  1552. } else if (rgba && !isNaN(rgba[0])) {
  1553. if (format === 'rgb') {
  1554. ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')';
  1555. } else if (format === 'a') {
  1556. ret = rgba[3];
  1557. } else {
  1558. ret = 'rgba(' + rgba.join(',') + ')';
  1559. }
  1560. } else {
  1561. ret = input;
  1562. }
  1563. return ret;
  1564. }
  1565. /**
  1566. * Brighten the color
  1567. * @param {Number} alpha
  1568. */
  1569. function brighten(alpha) {
  1570. if (stops) {
  1571. each(stops, function (stop) {
  1572. stop.brighten(alpha);
  1573. });
  1574. } else if (isNumber(alpha) && alpha !== 0) {
  1575. var i;
  1576. for (i = 0; i < 3; i++) {
  1577. rgba[i] += pInt(alpha * 255);
  1578. if (rgba[i] < 0) {
  1579. rgba[i] = 0;
  1580. }
  1581. if (rgba[i] > 255) {
  1582. rgba[i] = 255;
  1583. }
  1584. }
  1585. }
  1586. return this;
  1587. }
  1588. /**
  1589. * Set the color's opacity to a given alpha value
  1590. * @param {Number} alpha
  1591. */
  1592. function setOpacity(alpha) {
  1593. rgba[3] = alpha;
  1594. return this;
  1595. }
  1596. // initialize: parse the input
  1597. init(input);
  1598. // public methods
  1599. return {
  1600. get: get,
  1601. brighten: brighten,
  1602. rgba: rgba,
  1603. setOpacity: setOpacity
  1604. };
  1605. };
  1606. /**
  1607. * A wrapper object for SVG elements
  1608. */
  1609. function SVGElement() {}
  1610. SVGElement.prototype = {
  1611. /**
  1612. * Initialize the SVG renderer
  1613. * @param {Object} renderer
  1614. * @param {String} nodeName
  1615. */
  1616. init: function (renderer, nodeName) {
  1617. var wrapper = this;
  1618. wrapper.element = nodeName === 'span' ?
  1619. createElement(nodeName) :
  1620. doc.createElementNS(SVG_NS, nodeName);
  1621. wrapper.renderer = renderer;
  1622. },
  1623. /**
  1624. * Default base for animation
  1625. */
  1626. opacity: 1,
  1627. /**
  1628. * Animate a given attribute
  1629. * @param {Object} params
  1630. * @param {Number} options The same options as in jQuery animation
  1631. * @param {Function} complete Function to perform at the end of animation
  1632. */
  1633. animate: function (params, options, complete) {
  1634. var animOptions = pick(options, globalAnimation, true);
  1635. stop(this); // stop regardless of animation actually running, or reverting to .attr (#607)
  1636. if (animOptions) {
  1637. animOptions = merge(animOptions, {}); //#2625
  1638. if (complete) { // allows using a callback with the global animation without overwriting it
  1639. animOptions.complete = complete;
  1640. }
  1641. animate(this, params, animOptions);
  1642. } else {
  1643. this.attr(params);
  1644. if (complete) {
  1645. complete();
  1646. }
  1647. }
  1648. },
  1649. /**
  1650. * Build an SVG gradient out of a common JavaScript configuration object
  1651. */
  1652. colorGradient: function (color, prop, elem) {
  1653. var renderer = this.renderer,
  1654. colorObject,
  1655. gradName,
  1656. gradAttr,
  1657. gradients,
  1658. gradientObject,
  1659. stops,
  1660. stopColor,
  1661. stopOpacity,
  1662. radialReference,
  1663. n,
  1664. id,
  1665. key = [];
  1666. // Apply linear or radial gradients
  1667. if (color.linearGradient) {
  1668. gradName = 'linearGradient';
  1669. } else if (color.radialGradient) {
  1670. gradName = 'radialGradient';
  1671. }
  1672. if (gradName) {
  1673. gradAttr = color[gradName];
  1674. gradients = renderer.gradients;
  1675. stops = color.stops;
  1676. radialReference = elem.radialReference;
  1677. // Keep < 2.2 kompatibility
  1678. if (isArray(gradAttr)) {
  1679. color[gradName] = gradAttr = {
  1680. x1: gradAttr[0],
  1681. y1: gradAttr[1],
  1682. x2: gradAttr[2],
  1683. y2: gradAttr[3],
  1684. gradientUnits: 'userSpaceOnUse'
  1685. };
  1686. }
  1687. // Correct the radial gradient for the radial reference system
  1688. if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) {
  1689. gradAttr = merge(gradAttr, {
  1690. cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2],
  1691. cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2],
  1692. r: gradAttr.r * radialReference[2],
  1693. gradientUnits: 'userSpaceOnUse'
  1694. });
  1695. }
  1696. // Build the unique key to detect whether we need to create a new element (#1282)
  1697. for (n in gradAttr) {
  1698. if (n !== 'id') {
  1699. key.push(n, gradAttr[n]);
  1700. }
  1701. }
  1702. for (n in stops) {
  1703. key.push(stops[n]);
  1704. }
  1705. key = key.join(',');
  1706. // Check if a gradient object with the same config object is created within this renderer
  1707. if (gradients[key]) {
  1708. id = gradients[key].attr('id');
  1709. } else {
  1710. // Set the id and create the element
  1711. gradAttr.id = id = PREFIX + idCounter++;
  1712. gradients[key] = gradientObject = renderer.createElement(gradName)
  1713. .attr(gradAttr)
  1714. .add(renderer.defs);
  1715. // The gradient needs to keep a list of stops to be able to destroy them
  1716. gradientObject.stops = [];
  1717. each(stops, function (stop) {
  1718. var stopObject;
  1719. if (stop[1].indexOf('rgba') === 0) {
  1720. colorObject = Color(stop[1]);
  1721. stopColor = colorObject.get('rgb');
  1722. stopOpacity = colorObject.get('a');
  1723. } else {
  1724. stopColor = stop[1];
  1725. stopOpacity = 1;
  1726. }
  1727. stopObject = renderer.createElement('stop').attr({
  1728. offset: stop[0],
  1729. 'stop-color': stopColor,
  1730. 'stop-opacity': stopOpacity
  1731. }).add(gradientObject);
  1732. // Add the stop element to the gradient
  1733. gradientObject.stops.push(stopObject);
  1734. });
  1735. }
  1736. // Set the reference to the gradient object
  1737. elem.setAttribute(prop, 'url(' + renderer.url + '#' + id + ')');
  1738. }
  1739. },
  1740. /**
  1741. * Set or get a given attribute
  1742. * @param {Object|String} hash
  1743. * @param {Mixed|Undefined} val
  1744. */
  1745. attr: function (hash, val) {
  1746. var key,
  1747. value,
  1748. element = this.element,
  1749. hasSetSymbolSize,
  1750. ret = this,
  1751. skipAttr;
  1752. // single key-value pair
  1753. if (typeof hash === 'string' && val !== UNDEFINED) {
  1754. key = hash;
  1755. hash = {};
  1756. hash[key] = val;
  1757. }
  1758. // used as a getter: first argument is a string, second is undefined
  1759. if (typeof hash === 'string') {
  1760. ret = (this[hash + 'Getter'] || this._defaultGetter).call(this, hash, element);
  1761. // setter
  1762. } else {
  1763. for (key in hash) {
  1764. value = hash[key];
  1765. skipAttr = false;
  1766. if (this.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) {
  1767. if (!hasSetSymbolSize) {
  1768. this.symbolAttr(hash);
  1769. hasSetSymbolSize = true;
  1770. }
  1771. skipAttr = true;
  1772. }
  1773. if (this.rotation && (key === 'x' || key === 'y')) {
  1774. this.doTransform = true;
  1775. }
  1776. if (!skipAttr) {
  1777. (this[key + 'Setter'] || this._defaultSetter).call(this, value, key, element);
  1778. }
  1779. // Let the shadow follow the main element
  1780. if (this.shadows && /^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(key)) {
  1781. this.updateShadows(key, value);
  1782. }
  1783. }
  1784. // Update transform. Do this outside the loop to prevent redundant updating for batch setting
  1785. // of attributes.
  1786. if (this.doTransform) {
  1787. this.updateTransform();
  1788. this.doTransform = false;
  1789. }
  1790. }
  1791. return ret;
  1792. },
  1793. updateShadows: function (key, value) {
  1794. var shadows = this.shadows,
  1795. i = shadows.length;
  1796. while (i--) {
  1797. shadows[i].setAttribute(
  1798. key,
  1799. key === 'height' ?
  1800. mathMax(value - (shadows[i].cutHeight || 0), 0) :
  1801. key === 'd' ? this.d : value
  1802. );
  1803. }
  1804. },
  1805. /**
  1806. * Add a class name to an element
  1807. */
  1808. addClass: function (className) {
  1809. var element = this.element,
  1810. currentClassName = attr(element, 'class') || '';
  1811. if (currentClassName.indexOf(className) === -1) {
  1812. attr(element, 'class', currentClassName + ' ' + className);
  1813. }
  1814. return this;
  1815. },
  1816. /* hasClass and removeClass are not (yet) needed
  1817. hasClass: function (className) {
  1818. return attr(this.element, 'class').indexOf(className) !== -1;
  1819. },
  1820. removeClass: function (className) {
  1821. attr(this.element, 'class', attr(this.element, 'class').replace(className, ''));
  1822. return this;
  1823. },
  1824. */
  1825. /**
  1826. * If one of the symbol size affecting parameters are changed,
  1827. * check all the others only once for each call to an element's
  1828. * .attr() method
  1829. * @param {Object} hash
  1830. */
  1831. symbolAttr: function (hash) {
  1832. var wrapper = this;
  1833. each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function (key) {
  1834. wrapper[key] = pick(hash[key], wrapper[key]);
  1835. });
  1836. wrapper.attr({
  1837. d: wrapper.renderer.symbols[wrapper.symbolName](
  1838. wrapper.x,
  1839. wrapper.y,
  1840. wrapper.width,
  1841. wrapper.height,
  1842. wrapper
  1843. )
  1844. });
  1845. },
  1846. /**
  1847. * Apply a clipping path to this object
  1848. * @param {String} id
  1849. */
  1850. clip: function (clipRect) {
  1851. return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : NONE);
  1852. },
  1853. /**
  1854. * Calculate the coordinates needed for drawing a rectangle crisply and return the
  1855. * calculated attributes
  1856. * @param {Number} strokeWidth
  1857. * @param {Number} x
  1858. * @param {Number} y
  1859. * @param {Number} width
  1860. * @param {Number} height
  1861. */
  1862. crisp: function (rect) {
  1863. var wrapper = this,
  1864. key,
  1865. attribs = {},
  1866. normalizer,
  1867. strokeWidth = rect.strokeWidth || wrapper.strokeWidth || (wrapper.attr && wrapper.attr('stroke-width')) || 0;
  1868. normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors
  1869. // normalize for crisp edges
  1870. rect.x = mathFloor(rect.x || wrapper.x || 0) + normalizer;
  1871. rect.y = mathFloor(rect.y || wrapper.y || 0) + normalizer;
  1872. rect.width = mathFloor((rect.width || wrapper.width || 0) - 2 * normalizer);
  1873. rect.height = mathFloor((rect.height || wrapper.height || 0) - 2 * normalizer);
  1874. rect.strokeWidth = strokeWidth;
  1875. for (key in rect) {
  1876. if (wrapper[key] !== rect[key]) { // only set attribute if changed
  1877. wrapper[key] = attribs[key] = rect[key];
  1878. }
  1879. }
  1880. return attribs;
  1881. },
  1882. /**
  1883. * Set styles for the element
  1884. * @param {Object} styles
  1885. */
  1886. css: function (styles) {
  1887. var elemWrapper = this,
  1888. oldStyles = elemWrapper.styles,
  1889. newStyles = {},
  1890. elem = elemWrapper.element,
  1891. textWidth,
  1892. n,
  1893. serializedCss = '',
  1894. hyphenate,
  1895. hasNew = !oldStyles;
  1896. // convert legacy
  1897. if (styles && styles.color) {
  1898. styles.fill = styles.color;
  1899. }
  1900. // Filter out existing styles to increase performance (#2640)
  1901. if (oldStyles) {
  1902. for (n in styles) {
  1903. if (styles[n] !== oldStyles[n]) {
  1904. newStyles[n] = styles[n];
  1905. hasNew = true;
  1906. }
  1907. }
  1908. }
  1909. if (hasNew) {
  1910. textWidth = elemWrapper.textWidth = styles && styles.width && elem.nodeName.toLowerCase() === 'text' && pInt(styles.width);
  1911. // Merge the new styles with the old ones
  1912. if (oldStyles) {
  1913. styles = extend(
  1914. oldStyles,
  1915. newStyles
  1916. );
  1917. }
  1918. // store object
  1919. elemWrapper.styles = styles;
  1920. if (textWidth && (useCanVG || (!hasSVG && elemWrapper.renderer.forExport))) {
  1921. delete styles.width;
  1922. }
  1923. // serialize and set style attribute
  1924. if (isIE && !hasSVG) {
  1925. css(elemWrapper.element, styles);
  1926. } else {
  1927. /*jslint unparam: true*/
  1928. hyphenate = function (a, b) { return '-' + b.toLowerCase(); };
  1929. /*jslint unparam: false*/
  1930. for (n in styles) {
  1931. serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';';
  1932. }
  1933. attr(elem, 'style', serializedCss); // #1881
  1934. }
  1935. // re-build text
  1936. if (textWidth && elemWrapper.added) {
  1937. elemWrapper.renderer.buildText(elemWrapper);
  1938. }
  1939. }
  1940. return elemWrapper;
  1941. },
  1942. /**
  1943. * Add an event listener
  1944. * @param {String} eventType
  1945. * @param {Function} handler
  1946. */
  1947. on: function (eventType, handler) {
  1948. var svgElement = this,
  1949. element = svgElement.element;
  1950. // touch
  1951. if (hasTouch && eventType === 'click') {
  1952. element.ontouchstart = function (e) {
  1953. svgElement.touchEventFired = Date.now();
  1954. e.preventDefault();
  1955. handler.call(element, e);
  1956. };
  1957. element.onclick = function (e) {
  1958. if (userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { // #2269
  1959. handler.call(element, e);
  1960. }
  1961. };
  1962. } else {
  1963. // simplest possible event model for internal use
  1964. element['on' + eventType] = handler;
  1965. }
  1966. return this;
  1967. },
  1968. /**
  1969. * Set the coordinates needed to draw a consistent radial gradient across
  1970. * pie slices regardless of positioning inside the chart. The format is
  1971. * [centerX, centerY, diameter] in pixels.
  1972. */
  1973. setRadialReference: function (coordinates) {
  1974. this.element.radialReference = coordinates;
  1975. return this;
  1976. },
  1977. /**
  1978. * Move an object and its children by x and y values
  1979. * @param {Number} x
  1980. * @param {Number} y
  1981. */
  1982. translate: function (x, y) {
  1983. return this.attr({
  1984. translateX: x,
  1985. translateY: y
  1986. });
  1987. },
  1988. /**
  1989. * Invert a group, rotate and flip
  1990. */
  1991. invert: function () {
  1992. var wrapper = this;
  1993. wrapper.inverted = true;
  1994. wrapper.updateTransform();
  1995. return wrapper;
  1996. },
  1997. /**
  1998. * Private method to update the transform attribute based on internal
  1999. * properties
  2000. */
  2001. updateTransform: function () {
  2002. var wrapper = this,
  2003. translateX = wrapper.translateX || 0,
  2004. translateY = wrapper.translateY || 0,
  2005. scaleX = wrapper.scaleX,
  2006. scaleY = wrapper.scaleY,
  2007. inverted = wrapper.inverted,
  2008. rotation = wrapper.rotation,
  2009. element = wrapper.element,
  2010. transform;
  2011. // flipping affects translate as adjustment for flipping around the group's axis
  2012. if (inverted) {
  2013. translateX += wrapper.attr('width');
  2014. translateY += wrapper.attr('height');
  2015. }
  2016. // Apply translate. Nearly all transformed elements have translation, so instead
  2017. // of checking for translate = 0, do it always (#1767, #1846).
  2018. transform = ['translate(' + translateX + ',' + translateY + ')'];
  2019. // apply rotation
  2020. if (inverted) {
  2021. transform.push('rotate(90) scale(-1,1)');
  2022. } else if (rotation) { // text rotation
  2023. transform.push('rotate(' + rotation + ' ' + (element.getAttribute('x') || 0) + ' ' + (element.getAttribute('y') || 0) + ')');
  2024. }
  2025. // apply scale
  2026. if (defined(scaleX) || defined(scaleY)) {
  2027. transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')');
  2028. }
  2029. if (transform.length) {
  2030. element.setAttribute('transform', transform.join(' '));
  2031. }
  2032. },
  2033. /**
  2034. * Bring the element to the front
  2035. */
  2036. toFront: function () {
  2037. var element = this.element;
  2038. element.parentNode.appendChild(element);
  2039. return this;
  2040. },
  2041. /**
  2042. * Break down alignment options like align, verticalAlign, x and y
  2043. * to x and y relative to the chart.
  2044. *
  2045. * @param {Object} alignOptions
  2046. * @param {Boolean} alignByTranslate
  2047. * @param {String[Object} box The box to align to, needs a width and height. When the
  2048. * box is a string, it refers to an object in the Renderer. For example, when
  2049. * box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height
  2050. * x and y properties.
  2051. *
  2052. */
  2053. align: function (alignOptions, alignByTranslate, box) {
  2054. var align,
  2055. vAlign,
  2056. x,
  2057. y,
  2058. attribs = {},
  2059. alignTo,
  2060. renderer = this.renderer,
  2061. alignedObjects = renderer.alignedObjects;
  2062. // First call on instanciate
  2063. if (alignOptions) {
  2064. this.alignOptions = alignOptions;
  2065. this.alignByTranslate = alignByTranslate;
  2066. if (!box || isString(box)) { // boxes other than renderer handle this internally
  2067. this.alignTo = alignTo = box || 'renderer';
  2068. erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize
  2069. alignedObjects.push(this);
  2070. box = null; // reassign it below
  2071. }
  2072. // When called on resize, no arguments are supplied
  2073. } else {
  2074. alignOptions = this.alignOptions;
  2075. alignByTranslate = this.alignByTranslate;
  2076. alignTo = this.alignTo;
  2077. }
  2078. box = pick(box, renderer[alignTo], renderer);
  2079. // Assign variables
  2080. align = alignOptions.align;
  2081. vAlign = alignOptions.verticalAlign;
  2082. x = (box.x || 0) + (alignOptions.x || 0); // default: left align
  2083. y = (box.y || 0) + (alignOptions.y || 0); // default: top align
  2084. // Align
  2085. if (align === 'right' || align === 'center') {
  2086. x += (box.width - (alignOptions.width || 0)) /
  2087. { right: 1, center: 2 }[align];
  2088. }
  2089. attribs[alignByTranslate ? 'translateX' : 'x'] = mathRound(x);
  2090. // Vertical align
  2091. if (vAlign === 'bottom' || vAlign === 'middle') {
  2092. y += (box.height - (alignOptions.height || 0)) /
  2093. ({ bottom: 1, middle: 2 }[vAlign] || 1);
  2094. }
  2095. attribs[alignByTranslate ? 'translateY' : 'y'] = mathRound(y);
  2096. // Animate only if already placed
  2097. this[this.placed ? 'animate' : 'attr'](attribs);
  2098. this.placed = true;
  2099. this.alignAttr = attribs;
  2100. return this;
  2101. },
  2102. /**
  2103. * Get the bounding box (width, height, x and y) for the element
  2104. */
  2105. getBBox: function () {
  2106. var wrapper = this,
  2107. bBox = wrapper.bBox,
  2108. renderer = wrapper.renderer,
  2109. width,
  2110. height,
  2111. rotation = wrapper.rotation,
  2112. element = wrapper.element,
  2113. styles = wrapper.styles,
  2114. rad = rotation * deg2rad,
  2115. textStr = wrapper.textStr,
  2116. cacheKey;
  2117. // Since numbers are monospaced, and numerical labels appear a lot in a chart,
  2118. // we assume that a label of n characters has the same bounding box as others
  2119. // of the same length.
  2120. if (textStr === '' || numRegex.test(textStr)) {
  2121. cacheKey = 'num.' + textStr.toString().length + (styles ? ('|' + styles.fontSize + '|' + styles.fontFamily) : '');
  2122. } //else { // This code block made demo/waterfall fail, related to buildText
  2123. // Caching all strings reduces rendering time by 4-5%.
  2124. // TODO: Check how this affects places where bBox is found on the element
  2125. //cacheKey = textStr + (styles ? ('|' + styles.fontSize + '|' + styles.fontFamily) : '');
  2126. //}
  2127. if (cacheKey) {
  2128. bBox = renderer.cache[cacheKey];
  2129. }
  2130. // No cache found
  2131. if (!bBox) {
  2132. // SVG elements
  2133. if (element.namespaceURI === SVG_NS || renderer.forExport) {
  2134. try { // Fails in Firefox if the container has display: none.
  2135. bBox = element.getBBox ?
  2136. // SVG: use extend because IE9 is not allowed to change width and height in case
  2137. // of rotation (below)
  2138. extend({}, element.getBBox()) :
  2139. // Canvas renderer and legacy IE in export mode
  2140. {
  2141. width: element.offsetWidth,
  2142. height: element.offsetHeight
  2143. };
  2144. } catch (e) {}
  2145. // If the bBox is not set, the try-catch block above failed. The other condition
  2146. // is for Opera that returns a width of -Infinity on hidden elements.
  2147. if (!bBox || bBox.width < 0) {
  2148. bBox = { width: 0, height: 0 };
  2149. }
  2150. // VML Renderer or useHTML within SVG
  2151. } else {
  2152. bBox = wrapper.htmlGetBBox();
  2153. }
  2154. // True SVG elements as well as HTML elements in modern browsers using the .useHTML option
  2155. // need to compensated for rotation
  2156. if (renderer.isSVG) {
  2157. width = bBox.width;
  2158. height = bBox.height;
  2159. // Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669, #2568)
  2160. if (isIE && styles && styles.fontSize === '11px' && height.toPrecision(3) === '16.9') {
  2161. bBox.height = height = 14;
  2162. }
  2163. // Adjust for rotated text
  2164. if (rotation) {
  2165. bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad));
  2166. bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad));
  2167. }
  2168. }
  2169. // Cache it
  2170. wrapper.bBox = bBox;
  2171. if (cacheKey) {
  2172. renderer.cache[cacheKey] = bBox;
  2173. }
  2174. }
  2175. return bBox;
  2176. },
  2177. /**
  2178. * Show the element
  2179. */
  2180. show: function (inherit) {
  2181. // IE9-11 doesn't handle visibilty:inherit well, so we remove the attribute instead (#2881)
  2182. if (inherit && this.element.namespaceURI === SVG_NS) {
  2183. this.element.removeAttribute('visibility');
  2184. return this;
  2185. } else {
  2186. return this.attr({ visibility: inherit ? 'inherit' : VISIBLE });
  2187. }
  2188. },
  2189. /**
  2190. * Hide the element
  2191. */
  2192. hide: function () {
  2193. return this.attr({ visibility: HIDDEN });
  2194. },
  2195. fadeOut: function (duration) {
  2196. var elemWrapper = this;
  2197. elemWrapper.animate({
  2198. opacity: 0
  2199. }, {
  2200. duration: duration || 150,
  2201. complete: function () {
  2202. elemWrapper.hide();
  2203. }
  2204. });
  2205. },
  2206. /**
  2207. * Add the element
  2208. * @param {Object|Undefined} parent Can be an element, an element wrapper or undefined
  2209. * to append the element to the renderer.box.
  2210. */
  2211. add: function (parent) {
  2212. var renderer = this.renderer,
  2213. parentWrapper = parent || renderer,
  2214. parentNode = parentWrapper.element || renderer.box,
  2215. childNodes,
  2216. element = this.element,
  2217. zIndex = this.zIndex,
  2218. otherElement,
  2219. otherZIndex,
  2220. i,
  2221. inserted;
  2222. if (parent) {
  2223. this.parentGroup = parent;
  2224. }
  2225. // mark as inverted
  2226. this.parentInverted = parent && parent.inverted;
  2227. // build formatted text
  2228. if (this.textStr !== undefined) {
  2229. renderer.buildText(this);
  2230. }
  2231. // mark the container as having z indexed children
  2232. if (zIndex) {
  2233. parentWrapper.handleZ = true;
  2234. zIndex = pInt(zIndex);
  2235. }
  2236. // insert according to this and other elements' zIndex
  2237. if (parentWrapper.handleZ) { // this element or any of its siblings has a z index
  2238. childNodes = parentNode.childNodes;
  2239. for (i = 0; i < childNodes.length; i++) {
  2240. otherElement = childNodes[i];
  2241. otherZIndex = attr(otherElement, 'zIndex');
  2242. if (otherElement !== element && (
  2243. // insert before the first element with a higher zIndex
  2244. pInt(otherZIndex) > zIndex ||
  2245. // if no zIndex given, insert before the first element with a zIndex
  2246. (!defined(zIndex) && defined(otherZIndex))
  2247. )) {
  2248. parentNode.insertBefore(element, otherElement);
  2249. inserted = true;
  2250. break;
  2251. }
  2252. }
  2253. }
  2254. // default: append at the end
  2255. if (!inserted) {
  2256. parentNode.appendChild(element);
  2257. }
  2258. // mark as added
  2259. this.added = true;
  2260. // fire an event for internal hooks
  2261. if (this.onAdd) {
  2262. this.onAdd();
  2263. }
  2264. return this;
  2265. },
  2266. /**
  2267. * Removes a child either by removeChild or move to garbageBin.
  2268. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not.
  2269. */
  2270. safeRemoveChild: function (element) {
  2271. var parentNode = element.parentNode;
  2272. if (parentNode) {
  2273. parentNode.removeChild(element);
  2274. }
  2275. },
  2276. /**
  2277. * Destroy the element and element wrapper
  2278. */
  2279. destroy: function () {
  2280. var wrapper = this,
  2281. element = wrapper.element || {},
  2282. shadows = wrapper.shadows,
  2283. parentToClean = wrapper.renderer.isSVG && element.nodeName === 'SPAN' && wrapper.parentGroup,
  2284. grandParent,
  2285. key,
  2286. i;
  2287. // remove events
  2288. element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null;
  2289. stop(wrapper); // stop running animations
  2290. if (wrapper.clipPath) {
  2291. wrapper.clipPath = wrapper.clipPath.destroy();
  2292. }
  2293. // Destroy stops in case this is a gradient object
  2294. if (wrapper.stops) {
  2295. for (i = 0; i < wrapper.stops.length; i++) {
  2296. wrapper.stops[i] = wrapper.stops[i].destroy();
  2297. }
  2298. wrapper.stops = null;
  2299. }
  2300. // remove element
  2301. wrapper.safeRemoveChild(element);
  2302. // destroy shadows
  2303. if (shadows) {
  2304. each(shadows, function (shadow) {
  2305. wrapper.safeRemoveChild(shadow);
  2306. });
  2307. }
  2308. // In case of useHTML, clean up empty containers emulating SVG groups (#1960, #2393).
  2309. while (parentToClean && parentToClean.div.childNodes.length === 0) {
  2310. grandParent = parentToClean.parentGroup;
  2311. wrapper.safeRemoveChild(parentToClean.div);
  2312. delete parentToClean.div;
  2313. parentToClean = grandParent;
  2314. }
  2315. // remove from alignObjects
  2316. if (wrapper.alignTo) {
  2317. erase(wrapper.renderer.alignedObjects, wrapper);
  2318. }
  2319. for (key in wrapper) {
  2320. delete wrapper[key];
  2321. }
  2322. return null;
  2323. },
  2324. /**
  2325. * Add a shadow to the element. Must be done after the element is added to the DOM
  2326. * @param {Boolean|Object} shadowOptions
  2327. */
  2328. shadow: function (shadowOptions, group, cutOff) {
  2329. var shadows = [],
  2330. i,
  2331. shadow,
  2332. element = this.element,
  2333. strokeWidth,
  2334. shadowWidth,
  2335. shadowElementOpacity,
  2336. // compensate for inverted plot area
  2337. transform;
  2338. if (shadowOptions) {
  2339. shadowWidth = pick(shadowOptions.width, 3);
  2340. shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth;
  2341. transform = this.parentInverted ?
  2342. '(-1,-1)' :
  2343. '(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')';
  2344. for (i = 1; i <= shadowWidth; i++) {
  2345. shadow = element.cloneNode(0);
  2346. strokeWidth = (shadowWidth * 2) + 1 - (2 * i);
  2347. attr(shadow, {
  2348. 'isShadow': 'true',
  2349. 'stroke': shadowOptions.color || 'black',
  2350. 'stroke-opacity': shadowElementOpacity * i,
  2351. 'stroke-width': strokeWidth,
  2352. 'transform': 'translate' + transform,
  2353. 'fill': NONE
  2354. });
  2355. if (cutOff) {
  2356. attr(shadow, 'height', mathMax(attr(shadow, 'height') - strokeWidth, 0));
  2357. shadow.cutHeight = strokeWidth;
  2358. }
  2359. if (group) {
  2360. group.element.appendChild(shadow);
  2361. } else {
  2362. element.parentNode.insertBefore(shadow, element);
  2363. }
  2364. shadows.push(shadow);
  2365. }
  2366. this.shadows = shadows;
  2367. }
  2368. return this;
  2369. },
  2370. xGetter: function (key) {
  2371. if (this.element.nodeName === 'circle') {
  2372. key = { x: 'cx', y: 'cy' }[key] || key;
  2373. }
  2374. return this._defaultGetter(key);
  2375. },
  2376. /**
  2377. * Get the current value of an attribute or pseudo attribute, used mainly
  2378. * for animation.
  2379. */
  2380. _defaultGetter: function (key) {
  2381. var ret = pick(this[key], this.element ? this.element.getAttribute(key) : null, 0);
  2382. if (/^[0-9\.]+$/.test(ret)) { // is numerical
  2383. ret = parseFloat(ret);
  2384. }
  2385. return ret;
  2386. },
  2387. dSetter: function (value, key, element) {
  2388. if (value && value.join) { // join path
  2389. value = value.join(' ');
  2390. }
  2391. if (/(NaN| {2}|^$)/.test(value)) {
  2392. value = 'M 0 0';
  2393. }
  2394. element.setAttribute(key, value);
  2395. this[key] = value;
  2396. },
  2397. dashstyleSetter: function (value) {
  2398. var i;
  2399. value = value && value.toLowerCase();
  2400. if (value) {
  2401. value = value
  2402. .replace('shortdashdotdot', '3,1,1,1,1,1,')
  2403. .replace('shortdashdot', '3,1,1,1')
  2404. .replace('shortdot', '1,1,')
  2405. .replace('shortdash', '3,1,')
  2406. .replace('longdash', '8,3,')
  2407. .replace(/dot/g, '1,3,')
  2408. .replace('dash', '4,3,')
  2409. .replace(/,$/, '')
  2410. .split(','); // ending comma
  2411. i = value.length;
  2412. while (i--) {
  2413. value[i] = pInt(value[i]) * this.element.getAttribute('stroke-width');
  2414. }
  2415. value = value.join(',');
  2416. this.element.setAttribute('stroke-dasharray', value);
  2417. }
  2418. },
  2419. alignSetter: function (value) {
  2420. this.element.setAttribute('text-anchor', { left: 'start', center: 'middle', right: 'end' }[value]);
  2421. },
  2422. opacitySetter: function (value, key, element) {
  2423. this[key] = value;
  2424. element.setAttribute(key, value);
  2425. },
  2426. // In Chrome/Win < 6 as well as Batik and PhantomJS as of 1.9.7, the stroke attribute can't be set when the stroke-
  2427. // width is 0. #1369
  2428. 'stroke-widthSetter': function (value, key, element) {
  2429. if (value === 0) {
  2430. value = 0.00001;
  2431. }
  2432. this.strokeWidth = value; // read in symbol paths like 'callout'
  2433. element.setAttribute(key, value);
  2434. },
  2435. titleSetter: function (value) {
  2436. var titleNode = this.element.getElementsByTagName('title')[0];
  2437. if (!titleNode) {
  2438. titleNode = doc.createElementNS(SVG_NS, 'title');
  2439. this.element.appendChild(titleNode);
  2440. }
  2441. titleNode.textContent = value;
  2442. },
  2443. textSetter: function (value) {
  2444. if (value !== this.textStr) {
  2445. // Delete bBox memo when the text changes
  2446. delete this.bBox;
  2447. this.textStr = value;
  2448. if (this.added) {
  2449. this.renderer.buildText(this);
  2450. }
  2451. }
  2452. },
  2453. fillSetter: function (value, key, element) {
  2454. if (typeof value === 'string') {
  2455. element.setAttribute(key, value);
  2456. } else if (value) {
  2457. this.colorGradient(value, key, element);
  2458. }
  2459. },
  2460. zIndexSetter: function (value, key, element) {
  2461. element.setAttribute(key, value);
  2462. this[key] = value;
  2463. },
  2464. _defaultSetter: function (value, key, element) {
  2465. element.setAttribute(key, value);
  2466. }
  2467. };
  2468. // Some shared setters and getters
  2469. SVGElement.prototype.yGetter = SVGElement.prototype.xGetter;
  2470. SVGElement.prototype.translateXSetter = SVGElement.prototype.translateYSetter =
  2471. SVGElement.prototype.rotationSetter = SVGElement.prototype.verticalAlignSetter =
  2472. SVGElement.prototype.scaleXSetter = SVGElement.prototype.scaleYSetter = function (value, key) {
  2473. this[key] = value;
  2474. this.doTransform = true;
  2475. };
  2476. SVGElement.prototype.strokeSetter = SVGElement.prototype.fillSetter;
  2477. // In Chrome/Win < 6 as well as Batik, the stroke attribute can't be set when the stroke-
  2478. // width is 0. #1369
  2479. /*SVGElement.prototype['stroke-widthSetter'] = SVGElement.prototype.strokeSetter = function (value, key) {
  2480. this[key] = value;
  2481. // Only apply the stroke attribute if the stroke width is defined and larger than 0
  2482. if (this.stroke && this['stroke-width']) {
  2483. this.element.setAttribute('stroke', this.stroke);
  2484. this.element.setAttribute('stroke-width', this['stroke-width']);
  2485. this.hasStroke = true;
  2486. } else if (key === 'stroke-width' && value === 0 && this.hasStroke) {
  2487. this.element.removeAttribute('stroke');
  2488. this.hasStroke = false;
  2489. }
  2490. };*/
  2491. /**
  2492. * The default SVG renderer
  2493. */
  2494. var SVGRenderer = function () {
  2495. this.init.apply(this, arguments);
  2496. };
  2497. SVGRenderer.prototype = {
  2498. Element: SVGElement,
  2499. /**
  2500. * Initialize the SVGRenderer
  2501. * @param {Object} container
  2502. * @param {Number} width
  2503. * @param {Number} height
  2504. * @param {Boolean} forExport
  2505. */
  2506. init: function (container, width, height, style, forExport) {
  2507. var renderer = this,
  2508. loc = location,
  2509. boxWrapper,
  2510. element,
  2511. desc;
  2512. boxWrapper = renderer.createElement('svg')
  2513. .attr({
  2514. version: '1.1'
  2515. })
  2516. .css(this.getStyle(style));
  2517. element = boxWrapper.element;
  2518. container.appendChild(element);
  2519. // For browsers other than IE, add the namespace attribute (#1978)
  2520. if (container.innerHTML.indexOf('xmlns') === -1) {
  2521. attr(element, 'xmlns', SVG_NS);
  2522. }
  2523. // object properties
  2524. renderer.isSVG = true;
  2525. renderer.box = element;
  2526. renderer.boxWrapper = boxWrapper;
  2527. renderer.alignedObjects = [];
  2528. // Page url used for internal references. #24, #672, #1070
  2529. renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ?
  2530. loc.href
  2531. .replace(/#.*?$/, '') // remove the hash
  2532. .replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes
  2533. .replace(/ /g, '%20') : // replace spaces (needed for Safari only)
  2534. '';
  2535. // Add description
  2536. desc = this.createElement('desc').add();
  2537. desc.element.appendChild(doc.createTextNode('Created with ' + PRODUCT + ' ' + VERSION));
  2538. renderer.defs = this.createElement('defs').add();
  2539. renderer.forExport = forExport;
  2540. renderer.gradients = {}; // Object where gradient SvgElements are stored
  2541. renderer.cache = {}; // Cache for numerical bounding boxes
  2542. renderer.setSize(width, height, false);
  2543. // Issue 110 workaround:
  2544. // In Firefox, if a div is positioned by percentage, its pixel position may land
  2545. // between pixels. The container itself doesn't display this, but an SVG element
  2546. // inside this container will be drawn at subpixel precision. In order to draw
  2547. // sharp lines, this must be compensated for. This doesn't seem to work inside
  2548. // iframes though (like in jsFiddle).
  2549. var subPixelFix, rect;
  2550. if (isFirefox && container.getBoundingClientRect) {
  2551. renderer.subPixelFix = subPixelFix = function () {
  2552. css(container, { left: 0, top: 0 });
  2553. rect = container.getBoundingClientRect();
  2554. css(container, {
  2555. left: (mathCeil(rect.left) - rect.left) + PX,
  2556. top: (mathCeil(rect.top) - rect.top) + PX
  2557. });
  2558. };
  2559. // run the fix now
  2560. subPixelFix();
  2561. // run it on resize
  2562. addEvent(win, 'resize', subPixelFix);
  2563. }
  2564. },
  2565. getStyle: function (style) {
  2566. return (this.style = extend({
  2567. fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif', // default font
  2568. fontSize: '12px'
  2569. }, style));
  2570. },
  2571. /**
  2572. * Detect whether the renderer is hidden. This happens when one of the parent elements
  2573. * has display: none. #608.
  2574. */
  2575. isHidden: function () {
  2576. return !this.boxWrapper.getBBox().width;
  2577. },
  2578. /**
  2579. * Destroys the renderer and its allocated members.
  2580. */
  2581. destroy: function () {
  2582. var renderer = this,
  2583. rendererDefs = renderer.defs;
  2584. renderer.box = null;
  2585. renderer.boxWrapper = renderer.boxWrapper.destroy();
  2586. // Call destroy on all gradient elements
  2587. destroyObjectProperties(renderer.gradients || {});
  2588. renderer.gradients = null;
  2589. // Defs are null in VMLRenderer
  2590. // Otherwise, destroy them here.
  2591. if (rendererDefs) {
  2592. renderer.defs = rendererDefs.destroy();
  2593. }
  2594. // Remove sub pixel fix handler
  2595. // We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed
  2596. // See issue #982
  2597. if (renderer.subPixelFix) {
  2598. removeEvent(win, 'resize', renderer.subPixelFix);
  2599. }
  2600. renderer.alignedObjects = null;
  2601. return null;
  2602. },
  2603. /**
  2604. * Create a wrapper for an SVG element
  2605. * @param {Object} nodeName
  2606. */
  2607. createElement: function (nodeName) {
  2608. var wrapper = new this.Element();
  2609. wrapper.init(this, nodeName);
  2610. return wrapper;
  2611. },
  2612. /**
  2613. * Dummy function for use in canvas renderer
  2614. */
  2615. draw: function () {},
  2616. /**
  2617. * Parse a simple HTML string into SVG tspans
  2618. *
  2619. * @param {Object} textNode The parent text SVG node
  2620. */
  2621. buildText: function (wrapper) {
  2622. var textNode = wrapper.element,
  2623. renderer = this,
  2624. forExport = renderer.forExport,
  2625. textStr = pick(wrapper.textStr, '').toString(),
  2626. hasMarkup = textStr.indexOf('<') !== -1,
  2627. lines,
  2628. childNodes = textNode.childNodes,
  2629. styleRegex,
  2630. hrefRegex,
  2631. parentX = attr(textNode, 'x'),
  2632. textStyles = wrapper.styles,
  2633. width = wrapper.textWidth,
  2634. textLineHeight = textStyles && textStyles.lineHeight,
  2635. i = childNodes.length,
  2636. getLineHeight = function (tspan) {
  2637. return textLineHeight ?
  2638. pInt(textLineHeight) :
  2639. renderer.fontMetrics(
  2640. /(px|em)$/.test(tspan && tspan.style.fontSize) ?
  2641. tspan.style.fontSize :
  2642. ((textStyles && textStyles.fontSize) || renderer.style.fontSize || 12)
  2643. ).h;
  2644. };
  2645. /// remove old text
  2646. while (i--) {
  2647. textNode.removeChild(childNodes[i]);
  2648. }
  2649. // Skip tspans, add text directly to text node
  2650. if (!hasMarkup && textStr.indexOf(' ') === -1) {
  2651. textNode.appendChild(doc.createTextNode(textStr));
  2652. return;
  2653. // Complex strings, add more logic
  2654. } else {
  2655. styleRegex = /<.*style="([^"]+)".*>/;
  2656. hrefRegex = /<.*href="(http[^"]+)".*>/;
  2657. if (width && !wrapper.added) {
  2658. this.box.appendChild(textNode); // attach it to the DOM to read offset width
  2659. }
  2660. if (hasMarkup) {
  2661. lines = textStr
  2662. .replace(/<(b|strong)>/g, '<span style="font-weight:bold">')
  2663. .replace(/<(i|em)>/g, '<span style="font-style:italic">')
  2664. .replace(/<a/g, '<span')
  2665. .replace(/<\/(b|strong|i|em|a)>/g, '</span>')
  2666. .split(/<br.*?>/g);
  2667. } else {
  2668. lines = [textStr];
  2669. }
  2670. // remove empty line at end
  2671. if (lines[lines.length - 1] === '') {
  2672. lines.pop();
  2673. }
  2674. // build the lines
  2675. each(lines, function (line, lineNo) {
  2676. var spans, spanNo = 0;
  2677. line = line.replace(/<span/g, '|||<span').replace(/<\/span>/g, '</span>|||');
  2678. spans = line.split('|||');
  2679. each(spans, function (span) {
  2680. if (span !== '' || spans.length === 1) {
  2681. var attributes = {},
  2682. tspan = doc.createElementNS(SVG_NS, 'tspan'),
  2683. spanStyle; // #390
  2684. if (styleRegex.test(span)) {
  2685. spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2');
  2686. attr(tspan, 'style', spanStyle);
  2687. }
  2688. if (hrefRegex.test(span) && !forExport) { // Not for export - #1529
  2689. attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"');
  2690. css(tspan, { cursor: 'pointer' });
  2691. }
  2692. span = (span.replace(/<(.|\n)*?>/g, '') || ' ')
  2693. .replace(/&lt;/g, '<')
  2694. .replace(/&gt;/g, '>');
  2695. // Nested tags aren't supported, and cause crash in Safari (#1596)
  2696. if (span !== ' ') {
  2697. // add the text node
  2698. tspan.appendChild(doc.createTextNode(span));
  2699. if (!spanNo) { // first span in a line, align it to the left
  2700. if (lineNo && parentX !== null) {
  2701. attributes.x = parentX;
  2702. }
  2703. } else {
  2704. attributes.dx = 0; // #16
  2705. }
  2706. // add attributes
  2707. attr(tspan, attributes);
  2708. // first span on subsequent line, add the line height
  2709. if (!spanNo && lineNo) {
  2710. // allow getting the right offset height in exporting in IE
  2711. if (!hasSVG && forExport) {
  2712. css(tspan, { display: 'block' });
  2713. }
  2714. // Set the line height based on the font size of either
  2715. // the text element or the tspan element
  2716. attr(
  2717. tspan,
  2718. 'dy',
  2719. getLineHeight(tspan),
  2720. // Safari 6.0.2 - too optimized for its own good (#1539)
  2721. // TODO: revisit this with future versions of Safari
  2722. isWebKit && tspan.offsetHeight
  2723. );
  2724. }
  2725. // Append it
  2726. textNode.appendChild(tspan);
  2727. spanNo++;
  2728. // check width and apply soft breaks
  2729. if (width) {
  2730. var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273
  2731. hasWhiteSpace = words.length > 1 && textStyles.whiteSpace !== 'nowrap',
  2732. tooLong,
  2733. actualWidth,
  2734. clipHeight = wrapper._clipHeight,
  2735. rest = [],
  2736. dy = getLineHeight(),
  2737. softLineNo = 1,
  2738. bBox;
  2739. while (hasWhiteSpace && (words.length || rest.length)) {
  2740. delete wrapper.bBox; // delete cache
  2741. bBox = wrapper.getBBox();
  2742. actualWidth = bBox.width;
  2743. // Old IE cannot measure the actualWidth for SVG elements (#2314)
  2744. if (!hasSVG && renderer.forExport) {
  2745. actualWidth = renderer.measureSpanWidth(tspan.firstChild.data, wrapper.styles);
  2746. }
  2747. tooLong = actualWidth > width;
  2748. if (!tooLong || words.length === 1) { // new line needed
  2749. words = rest;
  2750. rest = [];
  2751. if (words.length) {
  2752. softLineNo++;
  2753. if (clipHeight && softLineNo * dy > clipHeight) {
  2754. words = ['...'];
  2755. wrapper.attr('title', wrapper.textStr);
  2756. } else {
  2757. tspan = doc.createElementNS(SVG_NS, 'tspan');
  2758. attr(tspan, {
  2759. dy: dy,
  2760. x: parentX
  2761. });
  2762. if (spanStyle) { // #390
  2763. attr(tspan, 'style', spanStyle);
  2764. }
  2765. textNode.appendChild(tspan);
  2766. if (actualWidth > width) { // a single word is pressing it out
  2767. width = actualWidth;
  2768. }
  2769. }
  2770. }
  2771. } else { // append to existing line tspan
  2772. tspan.removeChild(tspan.firstChild);
  2773. rest.unshift(words.pop());
  2774. }
  2775. if (words.length) {
  2776. tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-')));
  2777. }
  2778. }
  2779. }
  2780. }
  2781. }
  2782. });
  2783. });
  2784. }
  2785. },
  2786. /**
  2787. * Create a button with preset states
  2788. * @param {String} text
  2789. * @param {Number} x
  2790. * @param {Number} y
  2791. * @param {Function} callback
  2792. * @param {Object} normalState
  2793. * @param {Object} hoverState
  2794. * @param {Object} pressedState
  2795. */
  2796. button: function (text, x, y, callback, normalState, hoverState, pressedState, disabledState, shape) {
  2797. var label = this.label(text, x, y, shape, null, null, null, null, 'button'),
  2798. curState = 0,
  2799. stateOptions,
  2800. stateStyle,
  2801. normalStyle,
  2802. hoverStyle,
  2803. pressedStyle,
  2804. disabledStyle,
  2805. verticalGradient = { x1: 0, y1: 0, x2: 0, y2: 1 };
  2806. // Normal state - prepare the attributes
  2807. normalState = merge({
  2808. 'stroke-width': 1,
  2809. stroke: '#CCCCCC',
  2810. fill: {
  2811. linearGradient: verticalGradient,
  2812. stops: [
  2813. [0, '#FEFEFE'],
  2814. [1, '#F6F6F6']
  2815. ]
  2816. },
  2817. r: 2,
  2818. padding: 5,
  2819. style: {
  2820. color: 'black'
  2821. }
  2822. }, normalState);
  2823. normalStyle = normalState.style;
  2824. delete normalState.style;
  2825. // Hover state
  2826. hoverState = merge(normalState, {
  2827. stroke: '#68A',
  2828. fill: {
  2829. linearGradient: verticalGradient,
  2830. stops: [
  2831. [0, '#FFF'],
  2832. [1, '#ACF']
  2833. ]
  2834. }
  2835. }, hoverState);
  2836. hoverStyle = hoverState.style;
  2837. delete hoverState.style;
  2838. // Pressed state
  2839. pressedState = merge(normalState, {
  2840. stroke: '#68A',
  2841. fill: {
  2842. linearGradient: verticalGradient,
  2843. stops: [
  2844. [0, '#9BD'],
  2845. [1, '#CDF']
  2846. ]
  2847. }
  2848. }, pressedState);
  2849. pressedStyle = pressedState.style;
  2850. delete pressedState.style;
  2851. // Disabled state
  2852. disabledState = merge(normalState, {
  2853. style: {
  2854. color: '#CCC'
  2855. }
  2856. }, disabledState);
  2857. disabledStyle = disabledState.style;
  2858. delete disabledState.style;
  2859. // Add the events. IE9 and IE10 need mouseover and mouseout to funciton (#667).
  2860. addEvent(label.element, isIE ? 'mouseover' : 'mouseenter', function () {
  2861. if (curState !== 3) {
  2862. label.attr(hoverState)
  2863. .css(hoverStyle);
  2864. }
  2865. });
  2866. addEvent(label.element, isIE ? 'mouseout' : 'mouseleave', function () {
  2867. if (curState !== 3) {
  2868. stateOptions = [normalState, hoverState, pressedState][curState];
  2869. stateStyle = [normalStyle, hoverStyle, pressedStyle][curState];
  2870. label.attr(stateOptions)
  2871. .css(stateStyle);
  2872. }
  2873. });
  2874. label.setState = function (state) {
  2875. label.state = curState = state;
  2876. if (!state) {
  2877. label.attr(normalState)
  2878. .css(normalStyle);
  2879. } else if (state === 2) {
  2880. label.attr(pressedState)
  2881. .css(pressedStyle);
  2882. } else if (state === 3) {
  2883. label.attr(disabledState)
  2884. .css(disabledStyle);
  2885. }
  2886. };
  2887. return label
  2888. .on('click', function () {
  2889. if (curState !== 3) {
  2890. callback.call(label);
  2891. }
  2892. })
  2893. .attr(normalState)
  2894. .css(extend({ cursor: 'default' }, normalStyle));
  2895. },
  2896. /**
  2897. * Make a straight line crisper by not spilling out to neighbour pixels
  2898. * @param {Array} points
  2899. * @param {Number} width
  2900. */
  2901. crispLine: function (points, width) {
  2902. // points format: [M, 0, 0, L, 100, 0]
  2903. // normalize to a crisp line
  2904. if (points[1] === points[4]) {
  2905. // Substract due to #1129. Now bottom and left axis gridlines behave the same.
  2906. points[1] = points[4] = mathRound(points[1]) - (width % 2 / 2);
  2907. }
  2908. if (points[2] === points[5]) {
  2909. points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2);
  2910. }
  2911. return points;
  2912. },
  2913. /**
  2914. * Draw a path
  2915. * @param {Array} path An SVG path in array form
  2916. */
  2917. path: function (path) {
  2918. var attr = {
  2919. fill: NONE
  2920. };
  2921. if (isArray(path)) {
  2922. attr.d = path;
  2923. } else if (isObject(path)) { // attributes
  2924. extend(attr, path);
  2925. }
  2926. return this.createElement('path').attr(attr);
  2927. },
  2928. /**
  2929. * Draw and return an SVG circle
  2930. * @param {Number} x The x position
  2931. * @param {Number} y The y position
  2932. * @param {Number} r The radius
  2933. */
  2934. circle: function (x, y, r) {
  2935. var attr = isObject(x) ?
  2936. x :
  2937. {
  2938. x: x,
  2939. y: y,
  2940. r: r
  2941. },
  2942. wrapper = this.createElement('circle');
  2943. wrapper.xSetter = function (value) {
  2944. this.element.setAttribute('cx', value);
  2945. };
  2946. wrapper.ySetter = function (value) {
  2947. this.element.setAttribute('cy', value);
  2948. };
  2949. return wrapper.attr(attr);
  2950. },
  2951. /**
  2952. * Draw and return an arc
  2953. * @param {Number} x X position
  2954. * @param {Number} y Y position
  2955. * @param {Number} r Radius
  2956. * @param {Number} innerR Inner radius like used in donut charts
  2957. * @param {Number} start Starting angle
  2958. * @param {Number} end Ending angle
  2959. */
  2960. arc: function (x, y, r, innerR, start, end) {
  2961. var arc;
  2962. if (isObject(x)) {
  2963. y = x.y;
  2964. r = x.r;
  2965. innerR = x.innerR;
  2966. start = x.start;
  2967. end = x.end;
  2968. x = x.x;
  2969. }
  2970. // Arcs are defined as symbols for the ability to set
  2971. // attributes in attr and animate
  2972. arc = this.symbol('arc', x || 0, y || 0, r || 0, r || 0, {
  2973. innerR: innerR || 0,
  2974. start: start || 0,
  2975. end: end || 0
  2976. });
  2977. arc.r = r; // #959
  2978. return arc;
  2979. },
  2980. /**
  2981. * Draw and return a rectangle
  2982. * @param {Number} x Left position
  2983. * @param {Number} y Top position
  2984. * @param {Number} width
  2985. * @param {Number} height
  2986. * @param {Number} r Border corner radius
  2987. * @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing
  2988. */
  2989. rect: function (x, y, width, height, r, strokeWidth) {
  2990. r = isObject(x) ? x.r : r;
  2991. var wrapper = this.createElement('rect'),
  2992. attribs = isObject(x) ? x : x === UNDEFINED ? {} : {
  2993. x: x,
  2994. y: y,
  2995. width: mathMax(width, 0),
  2996. height: mathMax(height, 0)
  2997. };
  2998. if (strokeWidth !== UNDEFINED) {
  2999. attribs.strokeWidth = strokeWidth;
  3000. attribs = wrapper.crisp(attribs);
  3001. }
  3002. if (r) {
  3003. attribs.r = r;
  3004. }
  3005. wrapper.rSetter = function (value) {
  3006. attr(this.element, {
  3007. rx: value,
  3008. ry: value
  3009. });
  3010. };
  3011. return wrapper.attr(attribs);
  3012. },
  3013. /**
  3014. * Resize the box and re-align all aligned elements
  3015. * @param {Object} width
  3016. * @param {Object} height
  3017. * @param {Boolean} animate
  3018. *
  3019. */
  3020. setSize: function (width, height, animate) {
  3021. var renderer = this,
  3022. alignedObjects = renderer.alignedObjects,
  3023. i = alignedObjects.length;
  3024. renderer.width = width;
  3025. renderer.height = height;
  3026. renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({
  3027. width: width,
  3028. height: height
  3029. });
  3030. while (i--) {
  3031. alignedObjects[i].align();
  3032. }
  3033. },
  3034. /**
  3035. * Create a group
  3036. * @param {String} name The group will be given a class name of 'highcharts-{name}'.
  3037. * This can be used for styling and scripting.
  3038. */
  3039. g: function (name) {
  3040. var elem = this.createElement('g');
  3041. return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem;
  3042. },
  3043. /**
  3044. * Display an image
  3045. * @param {String} src
  3046. * @param {Number} x
  3047. * @param {Number} y
  3048. * @param {Number} width
  3049. * @param {Number} height
  3050. */
  3051. image: function (src, x, y, width, height) {
  3052. var attribs = {
  3053. preserveAspectRatio: NONE
  3054. },
  3055. elemWrapper;
  3056. // optional properties
  3057. if (arguments.length > 1) {
  3058. extend(attribs, {
  3059. x: x,
  3060. y: y,
  3061. width: width,
  3062. height: height
  3063. });
  3064. }
  3065. elemWrapper = this.createElement('image').attr(attribs);
  3066. // set the href in the xlink namespace
  3067. if (elemWrapper.element.setAttributeNS) {
  3068. elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink',
  3069. 'href', src);
  3070. } else {
  3071. // could be exporting in IE
  3072. // using href throws "not supported" in ie7 and under, requries regex shim to fix later
  3073. elemWrapper.element.setAttribute('hc-svg-href', src);
  3074. }
  3075. return elemWrapper;
  3076. },
  3077. /**
  3078. * Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object.
  3079. *
  3080. * @param {Object} symbol
  3081. * @param {Object} x
  3082. * @param {Object} y
  3083. * @param {Object} radius
  3084. * @param {Object} options
  3085. */
  3086. symbol: function (symbol, x, y, width, height, options) {
  3087. var obj,
  3088. // get the symbol definition function
  3089. symbolFn = this.symbols[symbol],
  3090. // check if there's a path defined for this symbol
  3091. path = symbolFn && symbolFn(
  3092. mathRound(x),
  3093. mathRound(y),
  3094. width,
  3095. height,
  3096. options
  3097. ),
  3098. imageElement,
  3099. imageRegex = /^url\((.*?)\)$/,
  3100. imageSrc,
  3101. imageSize,
  3102. centerImage;
  3103. if (path) {
  3104. obj = this.path(path);
  3105. // expando properties for use in animate and attr
  3106. extend(obj, {
  3107. symbolName: symbol,
  3108. x: x,
  3109. y: y,
  3110. width: width,
  3111. height: height
  3112. });
  3113. if (options) {
  3114. extend(obj, options);
  3115. }
  3116. // image symbols
  3117. } else if (imageRegex.test(symbol)) {
  3118. // On image load, set the size and position
  3119. centerImage = function (img, size) {
  3120. if (img.element) { // it may be destroyed in the meantime (#1390)
  3121. img.attr({
  3122. width: size[0],
  3123. height: size[1]
  3124. });
  3125. if (!img.alignByTranslate) { // #185
  3126. img.translate(
  3127. mathRound((width - size[0]) / 2), // #1378
  3128. mathRound((height - size[1]) / 2)
  3129. );
  3130. }
  3131. }
  3132. };
  3133. imageSrc = symbol.match(imageRegex)[1];
  3134. imageSize = symbolSizes[imageSrc];
  3135. // Ireate the image synchronously, add attribs async
  3136. obj = this.image(imageSrc)
  3137. .attr({
  3138. x: x,
  3139. y: y
  3140. });
  3141. obj.isImg = true;
  3142. if (imageSize) {
  3143. centerImage(obj, imageSize);
  3144. } else {
  3145. // Initialize image to be 0 size so export will still function if there's no cached sizes.
  3146. //
  3147. obj.attr({ width: 0, height: 0 });
  3148. // Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8,
  3149. // the created element must be assigned to a variable in order to load (#292).
  3150. imageElement = createElement('img', {
  3151. onload: function () {
  3152. centerImage(obj, symbolSizes[imageSrc] = [this.width, this.height]);
  3153. },
  3154. src: imageSrc
  3155. });
  3156. }
  3157. }
  3158. return obj;
  3159. },
  3160. /**
  3161. * An extendable collection of functions for defining symbol paths.
  3162. */
  3163. symbols: {
  3164. 'circle': function (x, y, w, h) {
  3165. var cpw = 0.166 * w;
  3166. return [
  3167. M, x + w / 2, y,
  3168. 'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h,
  3169. 'C', x - cpw, y + h, x - cpw, y, x + w / 2, y,
  3170. 'Z'
  3171. ];
  3172. },
  3173. 'square': function (x, y, w, h) {
  3174. return [
  3175. M, x, y,
  3176. L, x + w, y,
  3177. x + w, y + h,
  3178. x, y + h,
  3179. 'Z'
  3180. ];
  3181. },
  3182. 'triangle': function (x, y, w, h) {
  3183. return [
  3184. M, x + w / 2, y,
  3185. L, x + w, y + h,
  3186. x, y + h,
  3187. 'Z'
  3188. ];
  3189. },
  3190. 'triangle-down': function (x, y, w, h) {
  3191. return [
  3192. M, x, y,
  3193. L, x + w, y,
  3194. x + w / 2, y + h,
  3195. 'Z'
  3196. ];
  3197. },
  3198. 'diamond': function (x, y, w, h) {
  3199. return [
  3200. M, x + w / 2, y,
  3201. L, x + w, y + h / 2,
  3202. x + w / 2, y + h,
  3203. x, y + h / 2,
  3204. 'Z'
  3205. ];
  3206. },
  3207. 'arc': function (x, y, w, h, options) {
  3208. var start = options.start,
  3209. radius = options.r || w || h,
  3210. end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561)
  3211. innerRadius = options.innerR,
  3212. open = options.open,
  3213. cosStart = mathCos(start),
  3214. sinStart = mathSin(start),
  3215. cosEnd = mathCos(end),
  3216. sinEnd = mathSin(end),
  3217. longArc = options.end - start < mathPI ? 0 : 1;
  3218. return [
  3219. M,
  3220. x + radius * cosStart,
  3221. y + radius * sinStart,
  3222. 'A', // arcTo
  3223. radius, // x radius
  3224. radius, // y radius
  3225. 0, // slanting
  3226. longArc, // long or short arc
  3227. 1, // clockwise
  3228. x + radius * cosEnd,
  3229. y + radius * sinEnd,
  3230. open ? M : L,
  3231. x + innerRadius * cosEnd,
  3232. y + innerRadius * sinEnd,
  3233. 'A', // arcTo
  3234. innerRadius, // x radius
  3235. innerRadius, // y radius
  3236. 0, // slanting
  3237. longArc, // long or short arc
  3238. 0, // clockwise
  3239. x + innerRadius * cosStart,
  3240. y + innerRadius * sinStart,
  3241. open ? '' : 'Z' // close
  3242. ];
  3243. },
  3244. /**
  3245. * Callout shape used for default tooltips, also used for rounded rectangles in VML
  3246. */
  3247. callout: function (x, y, w, h, options) {
  3248. var arrowLength = 6,
  3249. halfDistance = 6,
  3250. r = mathMin((options && options.r) || 0, w, h),
  3251. safeDistance = r + halfDistance,
  3252. anchorX = options && options.anchorX,
  3253. anchorY = options && options.anchorY,
  3254. path,
  3255. normalizer = mathRound(options.strokeWidth || 0) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors;
  3256. x += normalizer;
  3257. y += normalizer;
  3258. path = [
  3259. 'M', x + r, y,
  3260. 'L', x + w - r, y, // top side
  3261. 'C', x + w, y, x + w, y, x + w, y + r, // top-right corner
  3262. 'L', x + w, y + h - r, // right side
  3263. 'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-right corner
  3264. 'L', x + r, y + h, // bottom side
  3265. 'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner
  3266. 'L', x, y + r, // left side
  3267. 'C', x, y, x, y, x + r, y // top-right corner
  3268. ];
  3269. if (anchorX && anchorX > w && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace right side
  3270. path.splice(13, 3,
  3271. 'L', x + w, anchorY - halfDistance,
  3272. x + w + arrowLength, anchorY,
  3273. x + w, anchorY + halfDistance,
  3274. x + w, y + h - r
  3275. );
  3276. } else if (anchorX && anchorX < 0 && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace left side
  3277. path.splice(33, 3,
  3278. 'L', x, anchorY + halfDistance,
  3279. x - arrowLength, anchorY,
  3280. x, anchorY - halfDistance,
  3281. x, y + r
  3282. );
  3283. } else if (anchorY && anchorY > h && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace bottom
  3284. path.splice(23, 3,
  3285. 'L', anchorX + halfDistance, y + h,
  3286. anchorX, y + h + arrowLength,
  3287. anchorX - halfDistance, y + h,
  3288. x + r, y + h
  3289. );
  3290. } else if (anchorY && anchorY < 0 && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace top
  3291. path.splice(3, 3,
  3292. 'L', anchorX - halfDistance, y,
  3293. anchorX, y - arrowLength,
  3294. anchorX + halfDistance, y,
  3295. w - r, y
  3296. );
  3297. }
  3298. return path;
  3299. }
  3300. },
  3301. /**
  3302. * Define a clipping rectangle
  3303. * @param {String} id
  3304. * @param {Number} x
  3305. * @param {Number} y
  3306. * @param {Number} width
  3307. * @param {Number} height
  3308. */
  3309. clipRect: function (x, y, width, height) {
  3310. var wrapper,
  3311. id = PREFIX + idCounter++,
  3312. clipPath = this.createElement('clipPath').attr({
  3313. id: id
  3314. }).add(this.defs);
  3315. wrapper = this.rect(x, y, width, height, 0).add(clipPath);
  3316. wrapper.id = id;
  3317. wrapper.clipPath = clipPath;
  3318. return wrapper;
  3319. },
  3320. /**
  3321. * Add text to the SVG object
  3322. * @param {String} str
  3323. * @param {Number} x Left position
  3324. * @param {Number} y Top position
  3325. * @param {Boolean} useHTML Use HTML to render the text
  3326. */
  3327. text: function (str, x, y, useHTML) {
  3328. // declare variables
  3329. var renderer = this,
  3330. fakeSVG = useCanVG || (!hasSVG && renderer.forExport),
  3331. wrapper,
  3332. attr = {};
  3333. if (useHTML && !renderer.forExport) {
  3334. return renderer.html(str, x, y);
  3335. }
  3336. attr.x = Math.round(x || 0); // X is always needed for line-wrap logic
  3337. if (y) {
  3338. attr.y = Math.round(y);
  3339. }
  3340. if (str || str === 0) {
  3341. attr.text = str;
  3342. }
  3343. wrapper = renderer.createElement('text')
  3344. .attr(attr);
  3345. // Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063)
  3346. if (fakeSVG) {
  3347. wrapper.css({
  3348. position: ABSOLUTE
  3349. });
  3350. }
  3351. if (!useHTML) {
  3352. wrapper.xSetter = function (value, key, element) {
  3353. var childNodes = element.childNodes,
  3354. child,
  3355. i;
  3356. for (i = 1; i < childNodes.length; i++) {
  3357. child = childNodes[i];
  3358. // if the x values are equal, the tspan represents a linebreak
  3359. if (child.getAttribute('x') === element.getAttribute('x')) {
  3360. child.setAttribute('x', value);
  3361. }
  3362. }
  3363. element.setAttribute(key, value);
  3364. };
  3365. }
  3366. return wrapper;
  3367. },
  3368. /**
  3369. * Utility to return the baseline offset and total line height from the font size
  3370. */
  3371. fontMetrics: function (fontSize) {
  3372. fontSize = fontSize || this.style.fontSize;
  3373. fontSize = /px/.test(fontSize) ? pInt(fontSize) : /em/.test(fontSize) ? parseFloat(fontSize) * 12 : 12;
  3374. // Empirical values found by comparing font size and bounding box height.
  3375. // Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/
  3376. var lineHeight = fontSize < 24 ? fontSize + 4 : mathRound(fontSize * 1.2),
  3377. baseline = mathRound(lineHeight * 0.8);
  3378. return {
  3379. h: lineHeight,
  3380. b: baseline
  3381. };
  3382. },
  3383. /**
  3384. * Add a label, a text item that can hold a colored or gradient background
  3385. * as well as a border and shadow.
  3386. * @param {string} str
  3387. * @param {Number} x
  3388. * @param {Number} y
  3389. * @param {String} shape
  3390. * @param {Number} anchorX In case the shape has a pointer, like a flag, this is the
  3391. * coordinates it should be pinned to
  3392. * @param {Number} anchorY
  3393. * @param {Boolean} baseline Whether to position the label relative to the text baseline,
  3394. * like renderer.text, or to the upper border of the rectangle.
  3395. * @param {String} className Class name for the group
  3396. */
  3397. label: function (str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) {
  3398. var renderer = this,
  3399. wrapper = renderer.g(className),
  3400. text = renderer.text('', 0, 0, useHTML)
  3401. .attr({
  3402. zIndex: 1
  3403. }),
  3404. //.add(wrapper),
  3405. box,
  3406. bBox,
  3407. alignFactor = 0,
  3408. padding = 3,
  3409. paddingLeft = 0,
  3410. width,
  3411. height,
  3412. wrapperX,
  3413. wrapperY,
  3414. crispAdjust = 0,
  3415. deferredAttr = {},
  3416. baselineOffset,
  3417. needsBox;
  3418. /**
  3419. * This function runs after the label is added to the DOM (when the bounding box is
  3420. * available), and after the text of the label is updated to detect the new bounding
  3421. * box and reflect it in the border box.
  3422. */
  3423. function updateBoxSize() {
  3424. var boxX,
  3425. boxY,
  3426. style = text.element.style;
  3427. bBox = (width === undefined || height === undefined || wrapper.styles.textAlign) && text.textStr &&
  3428. text.getBBox();
  3429. wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft;
  3430. wrapper.height = (height || bBox.height || 0) + 2 * padding;
  3431. // update the label-scoped y offset
  3432. baselineOffset = padding + renderer.fontMetrics(style && style.fontSize).b;
  3433. if (needsBox) {
  3434. // create the border box if it is not already present
  3435. if (!box) {
  3436. boxX = mathRound(-alignFactor * padding);
  3437. boxY = baseline ? -baselineOffset : 0;
  3438. wrapper.box = box = shape ?
  3439. renderer.symbol(shape, boxX, boxY, wrapper.width, wrapper.height, deferredAttr) :
  3440. renderer.rect(boxX, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]);
  3441. box.attr('fill', NONE).add(wrapper);
  3442. }
  3443. // apply the box attributes
  3444. if (!box.isImg) { // #1630
  3445. box.attr(extend({
  3446. width: mathRound(wrapper.width),
  3447. height: mathRound(wrapper.height)
  3448. }, deferredAttr));
  3449. }
  3450. deferredAttr = null;
  3451. }
  3452. }
  3453. /**
  3454. * This function runs after setting text or padding, but only if padding is changed
  3455. */
  3456. function updateTextPadding() {
  3457. var styles = wrapper.styles,
  3458. textAlign = styles && styles.textAlign,
  3459. x = paddingLeft + padding * (1 - alignFactor),
  3460. y;
  3461. // determin y based on the baseline
  3462. y = baseline ? 0 : baselineOffset;
  3463. // compensate for alignment
  3464. if (defined(width) && bBox && (textAlign === 'center' || textAlign === 'right')) {
  3465. x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width);
  3466. }
  3467. // update if anything changed
  3468. if (x !== text.x || y !== text.y) {
  3469. text.attr('x', x);
  3470. if (y !== UNDEFINED) {
  3471. text.attr('y', y);
  3472. }
  3473. }
  3474. // record current values
  3475. text.x = x;
  3476. text.y = y;
  3477. }
  3478. /**
  3479. * Set a box attribute, or defer it if the box is not yet created
  3480. * @param {Object} key
  3481. * @param {Object} value
  3482. */
  3483. function boxAttr(key, value) {
  3484. if (box) {
  3485. box.attr(key, value);
  3486. } else {
  3487. deferredAttr[key] = value;
  3488. }
  3489. }
  3490. /**
  3491. * After the text element is added, get the desired size of the border box
  3492. * and add it before the text in the DOM.
  3493. */
  3494. wrapper.onAdd = function () {
  3495. text.add(wrapper);
  3496. wrapper.attr({
  3497. text: str || '', // alignment is available now
  3498. x: x,
  3499. y: y
  3500. });
  3501. if (box && defined(anchorX)) {
  3502. wrapper.attr({
  3503. anchorX: anchorX,
  3504. anchorY: anchorY
  3505. });
  3506. }
  3507. };
  3508. /*
  3509. * Add specific attribute setters.
  3510. */
  3511. // only change local variables
  3512. wrapper.widthSetter = function (value) {
  3513. width = value;
  3514. };
  3515. wrapper.heightSetter = function (value) {
  3516. height = value;
  3517. };
  3518. wrapper.paddingSetter = function (value) {
  3519. if (defined(value) && value !== padding) {
  3520. padding = value;
  3521. updateTextPadding();
  3522. }
  3523. };
  3524. wrapper.paddingLeftSetter = function (value) {
  3525. if (defined(value) && value !== paddingLeft) {
  3526. paddingLeft = value;
  3527. updateTextPadding();
  3528. }
  3529. };
  3530. // change local variable and prevent setting attribute on the group
  3531. wrapper.alignSetter = function (value) {
  3532. alignFactor = { left: 0, center: 0.5, right: 1 }[value];
  3533. };
  3534. // apply these to the box and the text alike
  3535. wrapper.textSetter = function (value) {
  3536. if (value !== UNDEFINED) {
  3537. text.textSetter(value);
  3538. }
  3539. updateBoxSize();
  3540. updateTextPadding();
  3541. };
  3542. // apply these to the box but not to the text
  3543. wrapper['stroke-widthSetter'] = function (value, key) {
  3544. if (value) {
  3545. needsBox = true;
  3546. }
  3547. crispAdjust = value % 2 / 2;
  3548. boxAttr(key, value);
  3549. };
  3550. wrapper.strokeSetter = wrapper.fillSetter = wrapper.rSetter = function (value, key) {
  3551. if (key === 'fill' && value) {
  3552. needsBox = true;
  3553. }
  3554. boxAttr(key, value);
  3555. };
  3556. wrapper.anchorXSetter = function (value, key) {
  3557. anchorX = value;
  3558. boxAttr(key, value + crispAdjust - wrapperX);
  3559. };
  3560. wrapper.anchorYSetter = function (value, key) {
  3561. anchorY = value;
  3562. boxAttr(key, value - wrapperY);
  3563. };
  3564. // rename attributes
  3565. wrapper.xSetter = function (value) {
  3566. wrapper.x = value; // for animation getter
  3567. if (alignFactor) {
  3568. value -= alignFactor * ((width || bBox.width) + padding);
  3569. }
  3570. wrapperX = mathRound(value);
  3571. wrapper.attr('translateX', wrapperX);
  3572. };
  3573. wrapper.ySetter = function (value) {
  3574. wrapperY = wrapper.y = mathRound(value);
  3575. wrapper.attr('translateY', wrapperY);
  3576. };
  3577. // Redirect certain methods to either the box or the text
  3578. var baseCss = wrapper.css;
  3579. return extend(wrapper, {
  3580. /**
  3581. * Pick up some properties and apply them to the text instead of the wrapper
  3582. */
  3583. css: function (styles) {
  3584. if (styles) {
  3585. var textStyles = {};
  3586. styles = merge(styles); // create a copy to avoid altering the original object (#537)
  3587. each(['fontSize', 'fontWeight', 'fontFamily', 'color', 'lineHeight', 'width', 'textDecoration', 'textShadow'], function (prop) {
  3588. if (styles[prop] !== UNDEFINED) {
  3589. textStyles[prop] = styles[prop];
  3590. delete styles[prop];
  3591. }
  3592. });
  3593. text.css(textStyles);
  3594. }
  3595. return baseCss.call(wrapper, styles);
  3596. },
  3597. /**
  3598. * Return the bounding box of the box, not the group
  3599. */
  3600. getBBox: function () {
  3601. return {
  3602. width: bBox.width + 2 * padding,
  3603. height: bBox.height + 2 * padding,
  3604. x: bBox.x - padding,
  3605. y: bBox.y - padding
  3606. };
  3607. },
  3608. /**
  3609. * Apply the shadow to the box
  3610. */
  3611. shadow: function (b) {
  3612. if (box) {
  3613. box.shadow(b);
  3614. }
  3615. return wrapper;
  3616. },
  3617. /**
  3618. * Destroy and release memory.
  3619. */
  3620. destroy: function () {
  3621. // Added by button implementation
  3622. removeEvent(wrapper.element, 'mouseenter');
  3623. removeEvent(wrapper.element, 'mouseleave');
  3624. if (text) {
  3625. text = text.destroy();
  3626. }
  3627. if (box) {
  3628. box = box.destroy();
  3629. }
  3630. // Call base implementation to destroy the rest
  3631. SVGElement.prototype.destroy.call(wrapper);
  3632. // Release local pointers (#1298)
  3633. wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = null;
  3634. }
  3635. });
  3636. }
  3637. }; // end SVGRenderer
  3638. // general renderer
  3639. Renderer = SVGRenderer;
  3640. // extend SvgElement for useHTML option
  3641. extend(SVGElement.prototype, {
  3642. /**
  3643. * Apply CSS to HTML elements. This is used in text within SVG rendering and
  3644. * by the VML renderer
  3645. */
  3646. htmlCss: function (styles) {
  3647. var wrapper = this,
  3648. element = wrapper.element,
  3649. textWidth = styles && element.tagName === 'SPAN' && styles.width;
  3650. if (textWidth) {
  3651. delete styles.width;
  3652. wrapper.textWidth = textWidth;
  3653. wrapper.updateTransform();
  3654. }
  3655. wrapper.styles = extend(wrapper.styles, styles);
  3656. css(wrapper.element, styles);
  3657. return wrapper;
  3658. },
  3659. /**
  3660. * VML and useHTML method for calculating the bounding box based on offsets
  3661. * @param {Boolean} refresh Whether to force a fresh value from the DOM or to
  3662. * use the cached value
  3663. *
  3664. * @return {Object} A hash containing values for x, y, width and height
  3665. */
  3666. htmlGetBBox: function () {
  3667. var wrapper = this,
  3668. element = wrapper.element,
  3669. bBox = wrapper.bBox;
  3670. // faking getBBox in exported SVG in legacy IE
  3671. if (!bBox) {
  3672. // faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?)
  3673. if (element.nodeName === 'text') {
  3674. element.style.position = ABSOLUTE;
  3675. }
  3676. bBox = wrapper.bBox = {
  3677. x: element.offsetLeft,
  3678. y: element.offsetTop,
  3679. width: element.offsetWidth,
  3680. height: element.offsetHeight
  3681. };
  3682. }
  3683. return bBox;
  3684. },
  3685. /**
  3686. * VML override private method to update elements based on internal
  3687. * properties based on SVG transform
  3688. */
  3689. htmlUpdateTransform: function () {
  3690. // aligning non added elements is expensive
  3691. if (!this.added) {
  3692. this.alignOnAdd = true;
  3693. return;
  3694. }
  3695. var wrapper = this,
  3696. renderer = wrapper.renderer,
  3697. elem = wrapper.element,
  3698. translateX = wrapper.translateX || 0,
  3699. translateY = wrapper.translateY || 0,
  3700. x = wrapper.x || 0,
  3701. y = wrapper.y || 0,
  3702. align = wrapper.textAlign || 'left',
  3703. alignCorrection = { left: 0, center: 0.5, right: 1 }[align],
  3704. shadows = wrapper.shadows;
  3705. // apply translate
  3706. css(elem, {
  3707. marginLeft: translateX,
  3708. marginTop: translateY
  3709. });
  3710. if (shadows) { // used in labels/tooltip
  3711. each(shadows, function (shadow) {
  3712. css(shadow, {
  3713. marginLeft: translateX + 1,
  3714. marginTop: translateY + 1
  3715. });
  3716. });
  3717. }
  3718. // apply inversion
  3719. if (wrapper.inverted) { // wrapper is a group
  3720. each(elem.childNodes, function (child) {
  3721. renderer.invertChild(child, elem);
  3722. });
  3723. }
  3724. if (elem.tagName === 'SPAN') {
  3725. var width,
  3726. rotation = wrapper.rotation,
  3727. baseline,
  3728. textWidth = pInt(wrapper.textWidth),
  3729. currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth].join(',');
  3730. if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed
  3731. baseline = renderer.fontMetrics(elem.style.fontSize).b;
  3732. // Renderer specific handling of span rotation
  3733. if (defined(rotation)) {
  3734. wrapper.setSpanRotation(rotation, alignCorrection, baseline);
  3735. }
  3736. width = pick(wrapper.elemWidth, elem.offsetWidth);
  3737. // Update textWidth
  3738. if (width > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254
  3739. css(elem, {
  3740. width: textWidth + PX,
  3741. display: 'block',
  3742. whiteSpace: 'normal'
  3743. });
  3744. width = textWidth;
  3745. }
  3746. wrapper.getSpanCorrection(width, baseline, alignCorrection, rotation, align);
  3747. }
  3748. // apply position with correction
  3749. css(elem, {
  3750. left: (x + (wrapper.xCorr || 0)) + PX,
  3751. top: (y + (wrapper.yCorr || 0)) + PX
  3752. });
  3753. // force reflow in webkit to apply the left and top on useHTML element (#1249)
  3754. if (isWebKit) {
  3755. baseline = elem.offsetHeight; // assigned to baseline for JSLint purpose
  3756. }
  3757. // record current text transform
  3758. wrapper.cTT = currentTextTransform;
  3759. }
  3760. },
  3761. /**
  3762. * Set the rotation of an individual HTML span
  3763. */
  3764. setSpanRotation: function (rotation, alignCorrection, baseline) {
  3765. var rotationStyle = {},
  3766. cssTransformKey = isIE ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : '';
  3767. rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)';
  3768. rotationStyle[cssTransformKey + (isFirefox ? 'Origin' : '-origin')] = rotationStyle.transformOrigin = (alignCorrection * 100) + '% ' + baseline + 'px';
  3769. css(this.element, rotationStyle);
  3770. },
  3771. /**
  3772. * Get the correction in X and Y positioning as the element is rotated.
  3773. */
  3774. getSpanCorrection: function (width, baseline, alignCorrection) {
  3775. this.xCorr = -width * alignCorrection;
  3776. this.yCorr = -baseline;
  3777. }
  3778. });
  3779. // Extend SvgRenderer for useHTML option.
  3780. extend(SVGRenderer.prototype, {
  3781. /**
  3782. * Create HTML text node. This is used by the VML renderer as well as the SVG
  3783. * renderer through the useHTML option.
  3784. *
  3785. * @param {String} str
  3786. * @param {Number} x
  3787. * @param {Number} y
  3788. */
  3789. html: function (str, x, y) {
  3790. var wrapper = this.createElement('span'),
  3791. element = wrapper.element,
  3792. renderer = wrapper.renderer;
  3793. // Text setter
  3794. wrapper.textSetter = function (value) {
  3795. if (value !== element.innerHTML) {
  3796. delete this.bBox;
  3797. }
  3798. element.innerHTML = this.textStr = value;
  3799. };
  3800. // Various setters which rely on update transform
  3801. wrapper.xSetter = wrapper.ySetter = wrapper.alignSetter = wrapper.rotationSetter = function (value, key) {
  3802. if (key === 'align') {
  3803. key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML.
  3804. }
  3805. wrapper[key] = value;
  3806. wrapper.htmlUpdateTransform();
  3807. };
  3808. // Set the default attributes
  3809. wrapper.attr({
  3810. text: str,
  3811. x: mathRound(x),
  3812. y: mathRound(y)
  3813. })
  3814. .css({
  3815. position: ABSOLUTE,
  3816. whiteSpace: 'nowrap',
  3817. fontFamily: this.style.fontFamily,
  3818. fontSize: this.style.fontSize
  3819. });
  3820. // Use the HTML specific .css method
  3821. wrapper.css = wrapper.htmlCss;
  3822. // This is specific for HTML within SVG
  3823. if (renderer.isSVG) {
  3824. wrapper.add = function (svgGroupWrapper) {
  3825. var htmlGroup,
  3826. container = renderer.box.parentNode,
  3827. parentGroup,
  3828. parents = [];
  3829. this.parentGroup = svgGroupWrapper;
  3830. // Create a mock group to hold the HTML elements
  3831. if (svgGroupWrapper) {
  3832. htmlGroup = svgGroupWrapper.div;
  3833. if (!htmlGroup) {
  3834. // Read the parent chain into an array and read from top down
  3835. parentGroup = svgGroupWrapper;
  3836. while (parentGroup) {
  3837. parents.push(parentGroup);
  3838. // Move up to the next parent group
  3839. parentGroup = parentGroup.parentGroup;
  3840. }
  3841. // Ensure dynamically updating position when any parent is translated
  3842. each(parents.reverse(), function (parentGroup) {
  3843. var htmlGroupStyle;
  3844. // Create a HTML div and append it to the parent div to emulate
  3845. // the SVG group structure
  3846. htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, {
  3847. className: attr(parentGroup.element, 'class')
  3848. }, {
  3849. position: ABSOLUTE,
  3850. left: (parentGroup.translateX || 0) + PX,
  3851. top: (parentGroup.translateY || 0) + PX
  3852. }, htmlGroup || container); // the top group is appended to container
  3853. // Shortcut
  3854. htmlGroupStyle = htmlGroup.style;
  3855. // Set listeners to update the HTML div's position whenever the SVG group
  3856. // position is changed
  3857. extend(parentGroup, {
  3858. translateXSetter: function (value, key) {
  3859. htmlGroupStyle.left = value + PX;
  3860. parentGroup[key] = value;
  3861. parentGroup.doTransform = true;
  3862. },
  3863. translateYSetter: function (value, key) {
  3864. htmlGroupStyle.top = value + PX;
  3865. parentGroup[key] = value;
  3866. parentGroup.doTransform = true;
  3867. },
  3868. visibilitySetter: function (value, key) {
  3869. htmlGroupStyle[key] = value;
  3870. }
  3871. });
  3872. });
  3873. }
  3874. } else {
  3875. htmlGroup = container;
  3876. }
  3877. htmlGroup.appendChild(element);
  3878. // Shared with VML:
  3879. wrapper.added = true;
  3880. if (wrapper.alignOnAdd) {
  3881. wrapper.htmlUpdateTransform();
  3882. }
  3883. return wrapper;
  3884. };
  3885. }
  3886. return wrapper;
  3887. }
  3888. });
  3889. /* ****************************************************************************
  3890. * *
  3891. * START OF INTERNET EXPLORER <= 8 SPECIFIC CODE *
  3892. * *
  3893. * For applications and websites that don't need IE support, like platform *
  3894. * targeted mobile apps and web apps, this code can be removed. *
  3895. * *
  3896. *****************************************************************************/
  3897. /**
  3898. * @constructor
  3899. */
  3900. var VMLRenderer, VMLElement;
  3901. if (!hasSVG && !useCanVG) {
  3902. /**
  3903. * The VML element wrapper.
  3904. */
  3905. Highcharts.VMLElement = VMLElement = {
  3906. /**
  3907. * Initialize a new VML element wrapper. It builds the markup as a string
  3908. * to minimize DOM traffic.
  3909. * @param {Object} renderer
  3910. * @param {Object} nodeName
  3911. */
  3912. init: function (renderer, nodeName) {
  3913. var wrapper = this,
  3914. markup = ['<', nodeName, ' filled="f" stroked="f"'],
  3915. style = ['position: ', ABSOLUTE, ';'],
  3916. isDiv = nodeName === DIV;
  3917. // divs and shapes need size
  3918. if (nodeName === 'shape' || isDiv) {
  3919. style.push('left:0;top:0;width:1px;height:1px;');
  3920. }
  3921. style.push('visibility: ', isDiv ? HIDDEN : VISIBLE);
  3922. markup.push(' style="', style.join(''), '"/>');
  3923. // create element with default attributes and style
  3924. if (nodeName) {
  3925. markup = isDiv || nodeName === 'span' || nodeName === 'img' ?
  3926. markup.join('')
  3927. : renderer.prepVML(markup);
  3928. wrapper.element = createElement(markup);
  3929. }
  3930. wrapper.renderer = renderer;
  3931. },
  3932. /**
  3933. * Add the node to the given parent
  3934. * @param {Object} parent
  3935. */
  3936. add: function (parent) {
  3937. var wrapper = this,
  3938. renderer = wrapper.renderer,
  3939. element = wrapper.element,
  3940. box = renderer.box,
  3941. inverted = parent && parent.inverted,
  3942. // get the parent node
  3943. parentNode = parent ?
  3944. parent.element || parent :
  3945. box;
  3946. // if the parent group is inverted, apply inversion on all children
  3947. if (inverted) { // only on groups
  3948. renderer.invertChild(element, parentNode);
  3949. }
  3950. // append it
  3951. parentNode.appendChild(element);
  3952. // align text after adding to be able to read offset
  3953. wrapper.added = true;
  3954. if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) {
  3955. wrapper.updateTransform();
  3956. }
  3957. // fire an event for internal hooks
  3958. if (wrapper.onAdd) {
  3959. wrapper.onAdd();
  3960. }
  3961. return wrapper;
  3962. },
  3963. /**
  3964. * VML always uses htmlUpdateTransform
  3965. */
  3966. updateTransform: SVGElement.prototype.htmlUpdateTransform,
  3967. /**
  3968. * Set the rotation of a span with oldIE's filter
  3969. */
  3970. setSpanRotation: function () {
  3971. // Adjust for alignment and rotation. Rotation of useHTML content is not yet implemented
  3972. // but it can probably be implemented for Firefox 3.5+ on user request. FF3.5+
  3973. // has support for CSS3 transform. The getBBox method also needs to be updated
  3974. // to compensate for the rotation, like it currently does for SVG.
  3975. // Test case: http://jsfiddle.net/highcharts/Ybt44/
  3976. var rotation = this.rotation,
  3977. costheta = mathCos(rotation * deg2rad),
  3978. sintheta = mathSin(rotation * deg2rad);
  3979. css(this.element, {
  3980. filter: rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta,
  3981. ', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta,
  3982. ', sizingMethod=\'auto expand\')'].join('') : NONE
  3983. });
  3984. },
  3985. /**
  3986. * Get the positioning correction for the span after rotating.
  3987. */
  3988. getSpanCorrection: function (width, baseline, alignCorrection, rotation, align) {
  3989. var costheta = rotation ? mathCos(rotation * deg2rad) : 1,
  3990. sintheta = rotation ? mathSin(rotation * deg2rad) : 0,
  3991. height = pick(this.elemHeight, this.element.offsetHeight),
  3992. quad,
  3993. nonLeft = align && align !== 'left';
  3994. // correct x and y
  3995. this.xCorr = costheta < 0 && -width;
  3996. this.yCorr = sintheta < 0 && -height;
  3997. // correct for baseline and corners spilling out after rotation
  3998. quad = costheta * sintheta < 0;
  3999. this.xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection);
  4000. this.yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1);
  4001. // correct for the length/height of the text
  4002. if (nonLeft) {
  4003. this.xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1);
  4004. if (rotation) {
  4005. this.yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1);
  4006. }
  4007. css(this.element, {
  4008. textAlign: align
  4009. });
  4010. }
  4011. },
  4012. /**
  4013. * Converts a subset of an SVG path definition to its VML counterpart. Takes an array
  4014. * as the parameter and returns a string.
  4015. */
  4016. pathToVML: function (value) {
  4017. // convert paths
  4018. var i = value.length,
  4019. path = [];
  4020. while (i--) {
  4021. // Multiply by 10 to allow subpixel precision.
  4022. // Substracting half a pixel seems to make the coordinates
  4023. // align with SVG, but this hasn't been tested thoroughly
  4024. if (isNumber(value[i])) {
  4025. path[i] = mathRound(value[i] * 10) - 5;
  4026. } else if (value[i] === 'Z') { // close the path
  4027. path[i] = 'x';
  4028. } else {
  4029. path[i] = value[i];
  4030. // When the start X and end X coordinates of an arc are too close,
  4031. // they are rounded to the same value above. In this case, substract or
  4032. // add 1 from the end X and Y positions. #186, #760, #1371, #1410.
  4033. if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) {
  4034. // Start and end X
  4035. if (path[i + 5] === path[i + 7]) {
  4036. path[i + 7] += value[i + 7] > value[i + 5] ? 1 : -1;
  4037. }
  4038. // Start and end Y
  4039. if (path[i + 6] === path[i + 8]) {
  4040. path[i + 8] += value[i + 8] > value[i + 6] ? 1 : -1;
  4041. }
  4042. }
  4043. }
  4044. }
  4045. // Loop up again to handle path shortcuts (#2132)
  4046. /*while (i++ < path.length) {
  4047. if (path[i] === 'H') { // horizontal line to
  4048. path[i] = 'L';
  4049. path.splice(i + 2, 0, path[i - 1]);
  4050. } else if (path[i] === 'V') { // vertical line to
  4051. path[i] = 'L';
  4052. path.splice(i + 1, 0, path[i - 2]);
  4053. }
  4054. }*/
  4055. return path.join(' ') || 'x';
  4056. },
  4057. /**
  4058. * Set the element's clipping to a predefined rectangle
  4059. *
  4060. * @param {String} id The id of the clip rectangle
  4061. */
  4062. clip: function (clipRect) {
  4063. var wrapper = this,
  4064. clipMembers,
  4065. cssRet;
  4066. if (clipRect) {
  4067. clipMembers = clipRect.members;
  4068. erase(clipMembers, wrapper); // Ensure unique list of elements (#1258)
  4069. clipMembers.push(wrapper);
  4070. wrapper.destroyClip = function () {
  4071. erase(clipMembers, wrapper);
  4072. };
  4073. cssRet = clipRect.getCSS(wrapper);
  4074. } else {
  4075. if (wrapper.destroyClip) {
  4076. wrapper.destroyClip();
  4077. }
  4078. cssRet = { clip: docMode8 ? 'inherit' : 'rect(auto)' }; // #1214
  4079. }
  4080. return wrapper.css(cssRet);
  4081. },
  4082. /**
  4083. * Set styles for the element
  4084. * @param {Object} styles
  4085. */
  4086. css: SVGElement.prototype.htmlCss,
  4087. /**
  4088. * Removes a child either by removeChild or move to garbageBin.
  4089. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not.
  4090. */
  4091. safeRemoveChild: function (element) {
  4092. // discardElement will detach the node from its parent before attaching it
  4093. // to the garbage bin. Therefore it is important that the node is attached and have parent.
  4094. if (element.parentNode) {
  4095. discardElement(element);
  4096. }
  4097. },
  4098. /**
  4099. * Extend element.destroy by removing it from the clip members array
  4100. */
  4101. destroy: function () {
  4102. if (this.destroyClip) {
  4103. this.destroyClip();
  4104. }
  4105. return SVGElement.prototype.destroy.apply(this);
  4106. },
  4107. /**
  4108. * Add an event listener. VML override for normalizing event parameters.
  4109. * @param {String} eventType
  4110. * @param {Function} handler
  4111. */
  4112. on: function (eventType, handler) {
  4113. // simplest possible event model for internal use
  4114. this.element['on' + eventType] = function () {
  4115. var evt = win.event;
  4116. evt.target = evt.srcElement;
  4117. handler(evt);
  4118. };
  4119. return this;
  4120. },
  4121. /**
  4122. * In stacked columns, cut off the shadows so that they don't overlap
  4123. */
  4124. cutOffPath: function (path, length) {
  4125. var len;
  4126. path = path.split(/[ ,]/);
  4127. len = path.length;
  4128. if (len === 9 || len === 11) {
  4129. path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length;
  4130. }
  4131. return path.join(' ');
  4132. },
  4133. /**
  4134. * Apply a drop shadow by copying elements and giving them different strokes
  4135. * @param {Boolean|Object} shadowOptions
  4136. */
  4137. shadow: function (shadowOptions, group, cutOff) {
  4138. var shadows = [],
  4139. i,
  4140. element = this.element,
  4141. renderer = this.renderer,
  4142. shadow,
  4143. elemStyle = element.style,
  4144. markup,
  4145. path = element.path,
  4146. strokeWidth,
  4147. modifiedPath,
  4148. shadowWidth,
  4149. shadowElementOpacity;
  4150. // some times empty paths are not strings
  4151. if (path && typeof path.value !== 'string') {
  4152. path = 'x';
  4153. }
  4154. modifiedPath = path;
  4155. if (shadowOptions) {
  4156. shadowWidth = pick(shadowOptions.width, 3);
  4157. shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth;
  4158. for (i = 1; i <= 3; i++) {
  4159. strokeWidth = (shadowWidth * 2) + 1 - (2 * i);
  4160. // Cut off shadows for stacked column items
  4161. if (cutOff) {
  4162. modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5);
  4163. }
  4164. markup = ['<shape isShadow="true" strokeweight="', strokeWidth,
  4165. '" filled="false" path="', modifiedPath,
  4166. '" coordsize="10 10" style="', element.style.cssText, '" />'];
  4167. shadow = createElement(renderer.prepVML(markup),
  4168. null, {
  4169. left: pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1),
  4170. top: pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1)
  4171. }
  4172. );
  4173. if (cutOff) {
  4174. shadow.cutOff = strokeWidth + 1;
  4175. }
  4176. // apply the opacity
  4177. markup = ['<stroke color="', shadowOptions.color || 'black', '" opacity="', shadowElementOpacity * i, '"/>'];
  4178. createElement(renderer.prepVML(markup), null, null, shadow);
  4179. // insert it
  4180. if (group) {
  4181. group.element.appendChild(shadow);
  4182. } else {
  4183. element.parentNode.insertBefore(shadow, element);
  4184. }
  4185. // record it
  4186. shadows.push(shadow);
  4187. }
  4188. this.shadows = shadows;
  4189. }
  4190. return this;
  4191. },
  4192. updateShadows: noop, // Used in SVG only
  4193. setAttr: function (key, value) {
  4194. if (docMode8) { // IE8 setAttribute bug
  4195. this.element[key] = value;
  4196. } else {
  4197. this.element.setAttribute(key, value);
  4198. }
  4199. },
  4200. classSetter: function (value) {
  4201. // IE8 Standards mode has problems retrieving the className unless set like this
  4202. this.element.className = value;
  4203. },
  4204. dashstyleSetter: function (value, key, element) {
  4205. var strokeElem = element.getElementsByTagName('stroke')[0] ||
  4206. createElement(this.renderer.prepVML(['<stroke/>']), null, null, element);
  4207. strokeElem[key] = value || 'solid';
  4208. this[key] = value; /* because changing stroke-width will change the dash length
  4209. and cause an epileptic effect */
  4210. },
  4211. dSetter: function (value, key, element) {
  4212. var i,
  4213. shadows = this.shadows;
  4214. value = value || [];
  4215. this.d = value.join(' '); // used in getter for animation
  4216. element.path = value = this.pathToVML(value);
  4217. // update shadows
  4218. if (shadows) {
  4219. i = shadows.length;
  4220. while (i--) {
  4221. shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value;
  4222. }
  4223. }
  4224. this.setAttr(key, value);
  4225. },
  4226. fillSetter: function (value, key, element) {
  4227. var nodeName = element.nodeName;
  4228. if (nodeName === 'SPAN') { // text color
  4229. element.style.color = value;
  4230. } else if (nodeName !== 'IMG') { // #1336
  4231. element.filled = value !== NONE;
  4232. this.setAttr('fillcolor', this.renderer.color(value, element, key, this));
  4233. }
  4234. },
  4235. opacitySetter: noop, // Don't bother - animation is too slow and filters introduce artifacts
  4236. rotationSetter: function (value, key, element) {
  4237. var style = element.style;
  4238. this[key] = style[key] = value; // style is for #1873
  4239. // Correction for the 1x1 size of the shape container. Used in gauge needles.
  4240. style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX;
  4241. style.top = mathRound(mathCos(value * deg2rad)) + PX;
  4242. },
  4243. strokeSetter: function (value, key, element) {
  4244. this.setAttr('strokecolor', this.renderer.color(value, element, key));
  4245. },
  4246. 'stroke-widthSetter': function (value, key, element) {
  4247. element.stroked = !!value; // VML "stroked" attribute
  4248. this[key] = value; // used in getter, issue #113
  4249. if (isNumber(value)) {
  4250. value += PX;
  4251. }
  4252. this.setAttr('strokeweight', value);
  4253. },
  4254. titleSetter: function (value, key) {
  4255. this.setAttr(key, value);
  4256. },
  4257. visibilitySetter: function (value, key, element) {
  4258. // Handle inherited visibility
  4259. if (value === 'inherit') {
  4260. value = VISIBLE;
  4261. }
  4262. // Let the shadow follow the main element
  4263. if (this.shadows) {
  4264. each(this.shadows, function (shadow) {
  4265. shadow.style[key] = value;
  4266. });
  4267. }
  4268. // Instead of toggling the visibility CSS property, move the div out of the viewport.
  4269. // This works around #61 and #586
  4270. if (element.nodeName === 'DIV') {
  4271. value = value === HIDDEN ? '-999em' : 0;
  4272. // In order to redraw, IE7 needs the div to be visible when tucked away
  4273. // outside the viewport. So the visibility is actually opposite of
  4274. // the expected value. This applies to the tooltip only.
  4275. if (!docMode8) {
  4276. element.style[key] = value ? VISIBLE : HIDDEN;
  4277. }
  4278. key = 'top';
  4279. }
  4280. element.style[key] = value;
  4281. },
  4282. xSetter: function (value, key, element) {
  4283. this[key] = value; // used in getter
  4284. if (key === 'x') {
  4285. key = 'left';
  4286. } else if (key === 'y') {
  4287. key = 'top';
  4288. }/* else {
  4289. value = mathMax(0, value); // don't set width or height below zero (#311)
  4290. }*/
  4291. // clipping rectangle special
  4292. if (this.updateClipping) {
  4293. this[key] = value; // the key is now 'left' or 'top' for 'x' and 'y'
  4294. this.updateClipping();
  4295. } else {
  4296. // normal
  4297. element.style[key] = value;
  4298. }
  4299. },
  4300. zIndexSetter: function (value, key, element) {
  4301. element.style[key] = value;
  4302. }
  4303. };
  4304. VMLElement = extendClass(SVGElement, VMLElement);
  4305. // Some shared setters
  4306. VMLElement.prototype.ySetter =
  4307. VMLElement.prototype.widthSetter =
  4308. VMLElement.prototype.heightSetter =
  4309. VMLElement.prototype.xSetter;
  4310. /**
  4311. * The VML renderer
  4312. */
  4313. var VMLRendererExtension = { // inherit SVGRenderer
  4314. Element: VMLElement,
  4315. isIE8: userAgent.indexOf('MSIE 8.0') > -1,
  4316. /**
  4317. * Initialize the VMLRenderer
  4318. * @param {Object} container
  4319. * @param {Number} width
  4320. * @param {Number} height
  4321. */
  4322. init: function (container, width, height, style) {
  4323. var renderer = this,
  4324. boxWrapper,
  4325. box,
  4326. css;
  4327. renderer.alignedObjects = [];
  4328. boxWrapper = renderer.createElement(DIV)
  4329. .css(extend(this.getStyle(style), { position: RELATIVE}));
  4330. box = boxWrapper.element;
  4331. container.appendChild(boxWrapper.element);
  4332. // generate the containing box
  4333. renderer.isVML = true;
  4334. renderer.box = box;
  4335. renderer.boxWrapper = boxWrapper;
  4336. renderer.cache = {};
  4337. renderer.setSize(width, height, false);
  4338. // The only way to make IE6 and IE7 print is to use a global namespace. However,
  4339. // with IE8 the only way to make the dynamic shapes visible in screen and print mode
  4340. // seems to be to add the xmlns attribute and the behaviour style inline.
  4341. if (!doc.namespaces.hcv) {
  4342. doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml');
  4343. // Setup default CSS (#2153, #2368, #2384)
  4344. css = 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' +
  4345. '{ behavior:url(#default#VML); display: inline-block; } ';
  4346. try {
  4347. doc.createStyleSheet().cssText = css;
  4348. } catch (e) {
  4349. doc.styleSheets[0].cssText += css;
  4350. }
  4351. }
  4352. },
  4353. /**
  4354. * Detect whether the renderer is hidden. This happens when one of the parent elements
  4355. * has display: none
  4356. */
  4357. isHidden: function () {
  4358. return !this.box.offsetWidth;
  4359. },
  4360. /**
  4361. * Define a clipping rectangle. In VML it is accomplished by storing the values
  4362. * for setting the CSS style to all associated members.
  4363. *
  4364. * @param {Number} x
  4365. * @param {Number} y
  4366. * @param {Number} width
  4367. * @param {Number} height
  4368. */
  4369. clipRect: function (x, y, width, height) {
  4370. // create a dummy element
  4371. var clipRect = this.createElement(),
  4372. isObj = isObject(x);
  4373. // mimic a rectangle with its style object for automatic updating in attr
  4374. return extend(clipRect, {
  4375. members: [],
  4376. left: (isObj ? x.x : x) + 1,
  4377. top: (isObj ? x.y : y) + 1,
  4378. width: (isObj ? x.width : width) - 1,
  4379. height: (isObj ? x.height : height) - 1,
  4380. getCSS: function (wrapper) {
  4381. var element = wrapper.element,
  4382. nodeName = element.nodeName,
  4383. isShape = nodeName === 'shape',
  4384. inverted = wrapper.inverted,
  4385. rect = this,
  4386. top = rect.top - (isShape ? element.offsetTop : 0),
  4387. left = rect.left,
  4388. right = left + rect.width,
  4389. bottom = top + rect.height,
  4390. ret = {
  4391. clip: 'rect(' +
  4392. mathRound(inverted ? left : top) + 'px,' +
  4393. mathRound(inverted ? bottom : right) + 'px,' +
  4394. mathRound(inverted ? right : bottom) + 'px,' +
  4395. mathRound(inverted ? top : left) + 'px)'
  4396. };
  4397. // issue 74 workaround
  4398. if (!inverted && docMode8 && nodeName === 'DIV') {
  4399. extend(ret, {
  4400. width: right + PX,
  4401. height: bottom + PX
  4402. });
  4403. }
  4404. return ret;
  4405. },
  4406. // used in attr and animation to update the clipping of all members
  4407. updateClipping: function () {
  4408. each(clipRect.members, function (member) {
  4409. if (member.element) { // Deleted series, like in stock/members/series-remove demo. Should be removed from members, but this will do.
  4410. member.css(clipRect.getCSS(member));
  4411. }
  4412. });
  4413. }
  4414. });
  4415. },
  4416. /**
  4417. * Take a color and return it if it's a string, make it a gradient if it's a
  4418. * gradient configuration object, and apply opacity.
  4419. *
  4420. * @param {Object} color The color or config object
  4421. */
  4422. color: function (color, elem, prop, wrapper) {
  4423. var renderer = this,
  4424. colorObject,
  4425. regexRgba = /^rgba/,
  4426. markup,
  4427. fillType,
  4428. ret = NONE;
  4429. // Check for linear or radial gradient
  4430. if (color && color.linearGradient) {
  4431. fillType = 'gradient';
  4432. } else if (color && color.radialGradient) {
  4433. fillType = 'pattern';
  4434. }
  4435. if (fillType) {
  4436. var stopColor,
  4437. stopOpacity,
  4438. gradient = color.linearGradient || color.radialGradient,
  4439. x1,
  4440. y1,
  4441. x2,
  4442. y2,
  4443. opacity1,
  4444. opacity2,
  4445. color1,
  4446. color2,
  4447. fillAttr = '',
  4448. stops = color.stops,
  4449. firstStop,
  4450. lastStop,
  4451. colors = [],
  4452. addFillNode = function () {
  4453. // Add the fill subnode. When colors attribute is used, the meanings of opacity and o:opacity2
  4454. // are reversed.
  4455. markup = ['<fill colors="' + colors.join(',') + '" opacity="', opacity2, '" o:opacity2="', opacity1,
  4456. '" type="', fillType, '" ', fillAttr, 'focus="100%" method="any" />'];
  4457. createElement(renderer.prepVML(markup), null, null, elem);
  4458. };
  4459. // Extend from 0 to 1
  4460. firstStop = stops[0];
  4461. lastStop = stops[stops.length - 1];
  4462. if (firstStop[0] > 0) {
  4463. stops.unshift([
  4464. 0,
  4465. firstStop[1]
  4466. ]);
  4467. }
  4468. if (lastStop[0] < 1) {
  4469. stops.push([
  4470. 1,
  4471. lastStop[1]
  4472. ]);
  4473. }
  4474. // Compute the stops
  4475. each(stops, function (stop, i) {
  4476. if (regexRgba.test(stop[1])) {
  4477. colorObject = Color(stop[1]);
  4478. stopColor = colorObject.get('rgb');
  4479. stopOpacity = colorObject.get('a');
  4480. } else {
  4481. stopColor = stop[1];
  4482. stopOpacity = 1;
  4483. }
  4484. // Build the color attribute
  4485. colors.push((stop[0] * 100) + '% ' + stopColor);
  4486. // Only start and end opacities are allowed, so we use the first and the last
  4487. if (!i) {
  4488. opacity1 = stopOpacity;
  4489. color2 = stopColor;
  4490. } else {
  4491. opacity2 = stopOpacity;
  4492. color1 = stopColor;
  4493. }
  4494. });
  4495. // Apply the gradient to fills only.
  4496. if (prop === 'fill') {
  4497. // Handle linear gradient angle
  4498. if (fillType === 'gradient') {
  4499. x1 = gradient.x1 || gradient[0] || 0;
  4500. y1 = gradient.y1 || gradient[1] || 0;
  4501. x2 = gradient.x2 || gradient[2] || 0;
  4502. y2 = gradient.y2 || gradient[3] || 0;
  4503. fillAttr = 'angle="' + (90 - math.atan(
  4504. (y2 - y1) / // y vector
  4505. (x2 - x1) // x vector
  4506. ) * 180 / mathPI) + '"';
  4507. addFillNode();
  4508. // Radial (circular) gradient
  4509. } else {
  4510. var r = gradient.r,
  4511. sizex = r * 2,
  4512. sizey = r * 2,
  4513. cx = gradient.cx,
  4514. cy = gradient.cy,
  4515. radialReference = elem.radialReference,
  4516. bBox,
  4517. applyRadialGradient = function () {
  4518. if (radialReference) {
  4519. bBox = wrapper.getBBox();
  4520. cx += (radialReference[0] - bBox.x) / bBox.width - 0.5;
  4521. cy += (radialReference[1] - bBox.y) / bBox.height - 0.5;
  4522. sizex *= radialReference[2] / bBox.width;
  4523. sizey *= radialReference[2] / bBox.height;
  4524. }
  4525. fillAttr = 'src="' + defaultOptions.global.VMLRadialGradientURL + '" ' +
  4526. 'size="' + sizex + ',' + sizey + '" ' +
  4527. 'origin="0.5,0.5" ' +
  4528. 'position="' + cx + ',' + cy + '" ' +
  4529. 'color2="' + color2 + '" ';
  4530. addFillNode();
  4531. };
  4532. // Apply radial gradient
  4533. if (wrapper.added) {
  4534. applyRadialGradient();
  4535. } else {
  4536. // We need to know the bounding box to get the size and position right
  4537. wrapper.onAdd = applyRadialGradient;
  4538. }
  4539. // The fill element's color attribute is broken in IE8 standards mode, so we
  4540. // need to set the parent shape's fillcolor attribute instead.
  4541. ret = color1;
  4542. }
  4543. // Gradients are not supported for VML stroke, return the first color. #722.
  4544. } else {
  4545. ret = stopColor;
  4546. }
  4547. // if the color is an rgba color, split it and add a fill node
  4548. // to hold the opacity component
  4549. } else if (regexRgba.test(color) && elem.tagName !== 'IMG') {
  4550. colorObject = Color(color);
  4551. markup = ['<', prop, ' opacity="', colorObject.get('a'), '"/>'];
  4552. createElement(this.prepVML(markup), null, null, elem);
  4553. ret = colorObject.get('rgb');
  4554. } else {
  4555. var propNodes = elem.getElementsByTagName(prop); // 'stroke' or 'fill' node
  4556. if (propNodes.length) {
  4557. propNodes[0].opacity = 1;
  4558. propNodes[0].type = 'solid';
  4559. }
  4560. ret = color;
  4561. }
  4562. return ret;
  4563. },
  4564. /**
  4565. * Take a VML string and prepare it for either IE8 or IE6/IE7.
  4566. * @param {Array} markup A string array of the VML markup to prepare
  4567. */
  4568. prepVML: function (markup) {
  4569. var vmlStyle = 'display:inline-block;behavior:url(#default#VML);',
  4570. isIE8 = this.isIE8;
  4571. markup = markup.join('');
  4572. if (isIE8) { // add xmlns and style inline
  4573. markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />');
  4574. if (markup.indexOf('style="') === -1) {
  4575. markup = markup.replace('/>', ' style="' + vmlStyle + '" />');
  4576. } else {
  4577. markup = markup.replace('style="', 'style="' + vmlStyle);
  4578. }
  4579. } else { // add namespace
  4580. markup = markup.replace('<', '<hcv:');
  4581. }
  4582. return markup;
  4583. },
  4584. /**
  4585. * Create rotated and aligned text
  4586. * @param {String} str
  4587. * @param {Number} x
  4588. * @param {Number} y
  4589. */
  4590. text: SVGRenderer.prototype.html,
  4591. /**
  4592. * Create and return a path element
  4593. * @param {Array} path
  4594. */
  4595. path: function (path) {
  4596. var attr = {
  4597. // subpixel precision down to 0.1 (width and height = 1px)
  4598. coordsize: '10 10'
  4599. };
  4600. if (isArray(path)) {
  4601. attr.d = path;
  4602. } else if (isObject(path)) { // attributes
  4603. extend(attr, path);
  4604. }
  4605. // create the shape
  4606. return this.createElement('shape').attr(attr);
  4607. },
  4608. /**
  4609. * Create and return a circle element. In VML circles are implemented as
  4610. * shapes, which is faster than v:oval
  4611. * @param {Number} x
  4612. * @param {Number} y
  4613. * @param {Number} r
  4614. */
  4615. circle: function (x, y, r) {
  4616. var circle = this.symbol('circle');
  4617. if (isObject(x)) {
  4618. r = x.r;
  4619. y = x.y;
  4620. x = x.x;
  4621. }
  4622. circle.isCircle = true; // Causes x and y to mean center (#1682)
  4623. circle.r = r;
  4624. return circle.attr({ x: x, y: y });
  4625. },
  4626. /**
  4627. * Create a group using an outer div and an inner v:group to allow rotating
  4628. * and flipping. A simple v:group would have problems with positioning
  4629. * child HTML elements and CSS clip.
  4630. *
  4631. * @param {String} name The name of the group
  4632. */
  4633. g: function (name) {
  4634. var wrapper,
  4635. attribs;
  4636. // set the class name
  4637. if (name) {
  4638. attribs = { 'className': PREFIX + name, 'class': PREFIX + name };
  4639. }
  4640. // the div to hold HTML and clipping
  4641. wrapper = this.createElement(DIV).attr(attribs);
  4642. return wrapper;
  4643. },
  4644. /**
  4645. * VML override to create a regular HTML image
  4646. * @param {String} src
  4647. * @param {Number} x
  4648. * @param {Number} y
  4649. * @param {Number} width
  4650. * @param {Number} height
  4651. */
  4652. image: function (src, x, y, width, height) {
  4653. var obj = this.createElement('img')
  4654. .attr({ src: src });
  4655. if (arguments.length > 1) {
  4656. obj.attr({
  4657. x: x,
  4658. y: y,
  4659. width: width,
  4660. height: height
  4661. });
  4662. }
  4663. return obj;
  4664. },
  4665. /**
  4666. * For rectangles, VML uses a shape for rect to overcome bugs and rotation problems
  4667. */
  4668. createElement: function (nodeName) {
  4669. return nodeName === 'rect' ? this.symbol(nodeName) : SVGRenderer.prototype.createElement.call(this, nodeName);
  4670. },
  4671. /**
  4672. * In the VML renderer, each child of an inverted div (group) is inverted
  4673. * @param {Object} element
  4674. * @param {Object} parentNode
  4675. */
  4676. invertChild: function (element, parentNode) {
  4677. var ren = this,
  4678. parentStyle = parentNode.style,
  4679. imgStyle = element.tagName === 'IMG' && element.style; // #1111
  4680. css(element, {
  4681. flip: 'x',
  4682. left: pInt(parentStyle.width) - (imgStyle ? pInt(imgStyle.top) : 1),
  4683. top: pInt(parentStyle.height) - (imgStyle ? pInt(imgStyle.left) : 1),
  4684. rotation: -90
  4685. });
  4686. // Recursively invert child elements, needed for nested composite shapes like box plots and error bars. #1680, #1806.
  4687. each(element.childNodes, function (child) {
  4688. ren.invertChild(child, element);
  4689. });
  4690. },
  4691. /**
  4692. * Symbol definitions that override the parent SVG renderer's symbols
  4693. *
  4694. */
  4695. symbols: {
  4696. // VML specific arc function
  4697. arc: function (x, y, w, h, options) {
  4698. var start = options.start,
  4699. end = options.end,
  4700. radius = options.r || w || h,
  4701. innerRadius = options.innerR,
  4702. cosStart = mathCos(start),
  4703. sinStart = mathSin(start),
  4704. cosEnd = mathCos(end),
  4705. sinEnd = mathSin(end),
  4706. ret;
  4707. if (end - start === 0) { // no angle, don't show it.
  4708. return ['x'];
  4709. }
  4710. ret = [
  4711. 'wa', // clockwise arc to
  4712. x - radius, // left
  4713. y - radius, // top
  4714. x + radius, // right
  4715. y + radius, // bottom
  4716. x + radius * cosStart, // start x
  4717. y + radius * sinStart, // start y
  4718. x + radius * cosEnd, // end x
  4719. y + radius * sinEnd // end y
  4720. ];
  4721. if (options.open && !innerRadius) {
  4722. ret.push(
  4723. 'e',
  4724. M,
  4725. x,// - innerRadius,
  4726. y// - innerRadius
  4727. );
  4728. }
  4729. ret.push(
  4730. 'at', // anti clockwise arc to
  4731. x - innerRadius, // left
  4732. y - innerRadius, // top
  4733. x + innerRadius, // right
  4734. y + innerRadius, // bottom
  4735. x + innerRadius * cosEnd, // start x
  4736. y + innerRadius * sinEnd, // start y
  4737. x + innerRadius * cosStart, // end x
  4738. y + innerRadius * sinStart, // end y
  4739. 'x', // finish path
  4740. 'e' // close
  4741. );
  4742. ret.isArc = true;
  4743. return ret;
  4744. },
  4745. // Add circle symbol path. This performs significantly faster than v:oval.
  4746. circle: function (x, y, w, h, wrapper) {
  4747. if (wrapper) {
  4748. w = h = 2 * wrapper.r;
  4749. }
  4750. // Center correction, #1682
  4751. if (wrapper && wrapper.isCircle) {
  4752. x -= w / 2;
  4753. y -= h / 2;
  4754. }
  4755. // Return the path
  4756. return [
  4757. 'wa', // clockwisearcto
  4758. x, // left
  4759. y, // top
  4760. x + w, // right
  4761. y + h, // bottom
  4762. x + w, // start x
  4763. y + h / 2, // start y
  4764. x + w, // end x
  4765. y + h / 2, // end y
  4766. //'x', // finish path
  4767. 'e' // close
  4768. ];
  4769. },
  4770. /**
  4771. * Add rectangle symbol path which eases rotation and omits arcsize problems
  4772. * compared to the built-in VML roundrect shape. When borders are not rounded,
  4773. * use the simpler square path, else use the callout path without the arrow.
  4774. */
  4775. rect: function (x, y, w, h, options) {
  4776. return SVGRenderer.prototype.symbols[
  4777. !defined(options) || !options.r ? 'square' : 'callout'
  4778. ].call(0, x, y, w, h, options);
  4779. }
  4780. }
  4781. };
  4782. Highcharts.VMLRenderer = VMLRenderer = function () {
  4783. this.init.apply(this, arguments);
  4784. };
  4785. VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension);
  4786. // general renderer
  4787. Renderer = VMLRenderer;
  4788. }
  4789. // This method is used with exporting in old IE, when emulating SVG (see #2314)
  4790. SVGRenderer.prototype.measureSpanWidth = function (text, styles) {
  4791. var measuringSpan = doc.createElement('span'),
  4792. offsetWidth,
  4793. textNode = doc.createTextNode(text);
  4794. measuringSpan.appendChild(textNode);
  4795. css(measuringSpan, styles);
  4796. this.box.appendChild(measuringSpan);
  4797. offsetWidth = measuringSpan.offsetWidth;
  4798. discardElement(measuringSpan); // #2463
  4799. return offsetWidth;
  4800. };
  4801. /* ****************************************************************************
  4802. * *
  4803. * END OF INTERNET EXPLORER <= 8 SPECIFIC CODE *
  4804. * *
  4805. *****************************************************************************/
  4806. /* ****************************************************************************
  4807. * *
  4808. * START OF ANDROID < 3 SPECIFIC CODE. THIS CAN BE REMOVED IF YOU'RE NOT *
  4809. * TARGETING THAT SYSTEM. *
  4810. * *
  4811. *****************************************************************************/
  4812. var CanVGRenderer,
  4813. CanVGController;
  4814. if (useCanVG) {
  4815. /**
  4816. * The CanVGRenderer is empty from start to keep the source footprint small.
  4817. * When requested, the CanVGController downloads the rest of the source packaged
  4818. * together with the canvg library.
  4819. */
  4820. Highcharts.CanVGRenderer = CanVGRenderer = function () {
  4821. // Override the global SVG namespace to fake SVG/HTML that accepts CSS
  4822. SVG_NS = 'http://www.w3.org/1999/xhtml';
  4823. };
  4824. /**
  4825. * Start with an empty symbols object. This is needed when exporting is used (exporting.src.js will add a few symbols), but
  4826. * the implementation from SvgRenderer will not be merged in until first render.
  4827. */
  4828. CanVGRenderer.prototype.symbols = {};
  4829. /**
  4830. * Handles on demand download of canvg rendering support.
  4831. */
  4832. CanVGController = (function () {
  4833. // List of renderering calls
  4834. var deferredRenderCalls = [];
  4835. /**
  4836. * When downloaded, we are ready to draw deferred charts.
  4837. */
  4838. function drawDeferred() {
  4839. var callLength = deferredRenderCalls.length,
  4840. callIndex;
  4841. // Draw all pending render calls
  4842. for (callIndex = 0; callIndex < callLength; callIndex++) {
  4843. deferredRenderCalls[callIndex]();
  4844. }
  4845. // Clear the list
  4846. deferredRenderCalls = [];
  4847. }
  4848. return {
  4849. push: function (func, scriptLocation) {
  4850. // Only get the script once
  4851. if (deferredRenderCalls.length === 0) {
  4852. getScript(scriptLocation, drawDeferred);
  4853. }
  4854. // Register render call
  4855. deferredRenderCalls.push(func);
  4856. }
  4857. };
  4858. }());
  4859. Renderer = CanVGRenderer;
  4860. } // end CanVGRenderer
  4861. /* ****************************************************************************
  4862. * *
  4863. * END OF ANDROID < 3 SPECIFIC CODE *
  4864. * *
  4865. *****************************************************************************/
  4866. /**
  4867. * The Tick class
  4868. */
  4869. function Tick(axis, pos, type, noLabel) {
  4870. this.axis = axis;
  4871. this.pos = pos;
  4872. this.type = type || '';
  4873. this.isNew = true;
  4874. if (!type && !noLabel) {
  4875. this.addLabel();
  4876. }
  4877. }
  4878. Tick.prototype = {
  4879. /**
  4880. * Write the tick label
  4881. */
  4882. addLabel: function () {
  4883. var tick = this,
  4884. axis = tick.axis,
  4885. options = axis.options,
  4886. chart = axis.chart,
  4887. horiz = axis.horiz,
  4888. categories = axis.categories,
  4889. names = axis.names,
  4890. pos = tick.pos,
  4891. labelOptions = options.labels,
  4892. str,
  4893. tickPositions = axis.tickPositions,
  4894. width = (horiz && categories &&
  4895. !labelOptions.step && !labelOptions.staggerLines &&
  4896. !labelOptions.rotation &&
  4897. chart.plotWidth / tickPositions.length) ||
  4898. (!horiz && (chart.margin[3] || chart.chartWidth * 0.33)), // #1580, #1931
  4899. isFirst = pos === tickPositions[0],
  4900. isLast = pos === tickPositions[tickPositions.length - 1],
  4901. css,
  4902. attr,
  4903. value = categories ?
  4904. pick(categories[pos], names[pos], pos) :
  4905. pos,
  4906. label = tick.label,
  4907. tickPositionInfo = tickPositions.info,
  4908. dateTimeLabelFormat;
  4909. // Set the datetime label format. If a higher rank is set for this position, use that. If not,
  4910. // use the general format.
  4911. if (axis.isDatetimeAxis && tickPositionInfo) {
  4912. dateTimeLabelFormat = options.dateTimeLabelFormats[tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName];
  4913. }
  4914. // set properties for access in render method
  4915. tick.isFirst = isFirst;
  4916. tick.isLast = isLast;
  4917. // get the string
  4918. str = axis.labelFormatter.call({
  4919. axis: axis,
  4920. chart: chart,
  4921. isFirst: isFirst,
  4922. isLast: isLast,
  4923. dateTimeLabelFormat: dateTimeLabelFormat,
  4924. value: axis.isLog ? correctFloat(lin2log(value)) : value
  4925. });
  4926. // prepare CSS
  4927. css = width && { width: mathMax(1, mathRound(width - 2 * (labelOptions.padding || 10))) + PX };
  4928. css = extend(css, labelOptions.style);
  4929. // first call
  4930. if (!defined(label)) {
  4931. attr = {
  4932. align: axis.labelAlign
  4933. };
  4934. if (isNumber(labelOptions.rotation)) {
  4935. attr.rotation = labelOptions.rotation;
  4936. }
  4937. if (width && labelOptions.ellipsis) {
  4938. attr._clipHeight = axis.len / tickPositions.length;
  4939. }
  4940. tick.label =
  4941. defined(str) && labelOptions.enabled ?
  4942. chart.renderer.text(
  4943. str,
  4944. 0,
  4945. 0,
  4946. labelOptions.useHTML
  4947. )
  4948. .attr(attr)
  4949. // without position absolute, IE export sometimes is wrong
  4950. .css(css)
  4951. .add(axis.labelGroup) :
  4952. null;
  4953. // update
  4954. } else if (label) {
  4955. label.attr({
  4956. text: str
  4957. })
  4958. .css(css);
  4959. }
  4960. },
  4961. /**
  4962. * Get the offset height or width of the label
  4963. */
  4964. getLabelSize: function () {
  4965. var label = this.label,
  4966. axis = this.axis;
  4967. return label ?
  4968. label.getBBox()[axis.horiz ? 'height' : 'width'] :
  4969. 0;
  4970. },
  4971. /**
  4972. * Find how far the labels extend to the right and left of the tick's x position. Used for anti-collision
  4973. * detection with overflow logic.
  4974. */
  4975. getLabelSides: function () {
  4976. var bBox = this.label.getBBox(),
  4977. axis = this.axis,
  4978. horiz = axis.horiz,
  4979. options = axis.options,
  4980. labelOptions = options.labels,
  4981. size = horiz ? bBox.width : bBox.height,
  4982. leftSide = horiz ?
  4983. labelOptions.x - size * { left: 0, center: 0.5, right: 1 }[axis.labelAlign] :
  4984. 0,
  4985. rightSide = horiz ?
  4986. size + leftSide :
  4987. size;
  4988. return [leftSide, rightSide];
  4989. },
  4990. /**
  4991. * Handle the label overflow by adjusting the labels to the left and right edge, or
  4992. * hide them if they collide into the neighbour label.
  4993. */
  4994. handleOverflow: function (index, xy) {
  4995. var show = true,
  4996. axis = this.axis,
  4997. isFirst = this.isFirst,
  4998. isLast = this.isLast,
  4999. horiz = axis.horiz,
  5000. pxPos = horiz ? xy.x : xy.y,
  5001. reversed = axis.reversed,
  5002. tickPositions = axis.tickPositions,
  5003. sides = this.getLabelSides(),
  5004. leftSide = sides[0],
  5005. rightSide = sides[1],
  5006. axisLeft,
  5007. axisRight,
  5008. neighbour,
  5009. neighbourEdge,
  5010. line = this.label.line || 0,
  5011. labelEdge = axis.labelEdge,
  5012. justifyLabel = axis.justifyLabels && (isFirst || isLast),
  5013. justifyToPlot;
  5014. // Hide it if it now overlaps the neighbour label
  5015. if (labelEdge[line] === UNDEFINED || pxPos + leftSide > labelEdge[line]) {
  5016. labelEdge[line] = pxPos + rightSide;
  5017. } else if (!justifyLabel) {
  5018. show = false;
  5019. }
  5020. if (justifyLabel) {
  5021. justifyToPlot = axis.justifyToPlot;
  5022. axisLeft = justifyToPlot ? axis.pos : 0;
  5023. axisRight = justifyToPlot ? axisLeft + axis.len : axis.chart.chartWidth;
  5024. // Find the firsth neighbour on the same line
  5025. do {
  5026. index += (isFirst ? 1 : -1);
  5027. neighbour = axis.ticks[tickPositions[index]];
  5028. } while (tickPositions[index] && (!neighbour || neighbour.label.line !== line));
  5029. neighbourEdge = neighbour && neighbour.label.xy && neighbour.label.xy.x + neighbour.getLabelSides()[isFirst ? 0 : 1];
  5030. if ((isFirst && !reversed) || (isLast && reversed)) {
  5031. // Is the label spilling out to the left of the plot area?
  5032. if (pxPos + leftSide < axisLeft) {
  5033. // Align it to plot left
  5034. pxPos = axisLeft - leftSide;
  5035. // Hide it if it now overlaps the neighbour label
  5036. if (neighbour && pxPos + rightSide > neighbourEdge) {
  5037. show = false;
  5038. }
  5039. }
  5040. } else {
  5041. // Is the label spilling out to the right of the plot area?
  5042. if (pxPos + rightSide > axisRight) {
  5043. // Align it to plot right
  5044. pxPos = axisRight - rightSide;
  5045. // Hide it if it now overlaps the neighbour label
  5046. if (neighbour && pxPos + leftSide < neighbourEdge) {
  5047. show = false;
  5048. }
  5049. }
  5050. }
  5051. // Set the modified x position of the label
  5052. xy.x = pxPos;
  5053. }
  5054. return show;
  5055. },
  5056. /**
  5057. * Get the x and y position for ticks and labels
  5058. */
  5059. getPosition: function (horiz, pos, tickmarkOffset, old) {
  5060. var axis = this.axis,
  5061. chart = axis.chart,
  5062. cHeight = (old && chart.oldChartHeight) || chart.chartHeight;
  5063. return {
  5064. x: horiz ?
  5065. axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB :
  5066. axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0),
  5067. y: horiz ?
  5068. cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) :
  5069. cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB
  5070. };
  5071. },
  5072. /**
  5073. * Get the x, y position of the tick label
  5074. */
  5075. getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) {
  5076. var axis = this.axis,
  5077. transA = axis.transA,
  5078. reversed = axis.reversed,
  5079. staggerLines = axis.staggerLines,
  5080. baseline = axis.chart.renderer.fontMetrics(labelOptions.style.fontSize).b,
  5081. rotation = labelOptions.rotation;
  5082. x = x + labelOptions.x - (tickmarkOffset && horiz ?
  5083. tickmarkOffset * transA * (reversed ? -1 : 1) : 0);
  5084. y = y + labelOptions.y - (tickmarkOffset && !horiz ?
  5085. tickmarkOffset * transA * (reversed ? 1 : -1) : 0);
  5086. // Correct for rotation (#1764)
  5087. if (rotation && axis.side === 2) {
  5088. y -= baseline - baseline * mathCos(rotation * deg2rad);
  5089. }
  5090. // Vertically centered
  5091. if (!defined(labelOptions.y) && !rotation) { // #1951
  5092. y += baseline - label.getBBox().height / 2;
  5093. }
  5094. // Correct for staggered labels
  5095. if (staggerLines) {
  5096. label.line = (index / (step || 1) % staggerLines);
  5097. y += label.line * (axis.labelOffset / staggerLines);
  5098. }
  5099. return {
  5100. x: x,
  5101. y: y
  5102. };
  5103. },
  5104. /**
  5105. * Extendible method to return the path of the marker
  5106. */
  5107. getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) {
  5108. return renderer.crispLine([
  5109. M,
  5110. x,
  5111. y,
  5112. L,
  5113. x + (horiz ? 0 : -tickLength),
  5114. y + (horiz ? tickLength : 0)
  5115. ], tickWidth);
  5116. },
  5117. /**
  5118. * Put everything in place
  5119. *
  5120. * @param index {Number}
  5121. * @param old {Boolean} Use old coordinates to prepare an animation into new position
  5122. */
  5123. render: function (index, old, opacity) {
  5124. var tick = this,
  5125. axis = tick.axis,
  5126. options = axis.options,
  5127. chart = axis.chart,
  5128. renderer = chart.renderer,
  5129. horiz = axis.horiz,
  5130. type = tick.type,
  5131. label = tick.label,
  5132. pos = tick.pos,
  5133. labelOptions = options.labels,
  5134. gridLine = tick.gridLine,
  5135. gridPrefix = type ? type + 'Grid' : 'grid',
  5136. tickPrefix = type ? type + 'Tick' : 'tick',
  5137. gridLineWidth = options[gridPrefix + 'LineWidth'],
  5138. gridLineColor = options[gridPrefix + 'LineColor'],
  5139. dashStyle = options[gridPrefix + 'LineDashStyle'],
  5140. tickLength = options[tickPrefix + 'Length'],
  5141. tickWidth = options[tickPrefix + 'Width'] || 0,
  5142. tickColor = options[tickPrefix + 'Color'],
  5143. tickPosition = options[tickPrefix + 'Position'],
  5144. gridLinePath,
  5145. mark = tick.mark,
  5146. markPath,
  5147. step = labelOptions.step,
  5148. attribs,
  5149. show = true,
  5150. tickmarkOffset = axis.tickmarkOffset,
  5151. xy = tick.getPosition(horiz, pos, tickmarkOffset, old),
  5152. x = xy.x,
  5153. y = xy.y,
  5154. reverseCrisp = ((horiz && x === axis.pos + axis.len) || (!horiz && y === axis.pos)) ? -1 : 1; // #1480, #1687
  5155. this.isActive = true;
  5156. // create the grid line
  5157. if (gridLineWidth) {
  5158. gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLineWidth * reverseCrisp, old, true);
  5159. if (gridLine === UNDEFINED) {
  5160. attribs = {
  5161. stroke: gridLineColor,
  5162. 'stroke-width': gridLineWidth
  5163. };
  5164. if (dashStyle) {
  5165. attribs.dashstyle = dashStyle;
  5166. }
  5167. if (!type) {
  5168. attribs.zIndex = 1;
  5169. }
  5170. if (old) {
  5171. attribs.opacity = 0;
  5172. }
  5173. tick.gridLine = gridLine =
  5174. gridLineWidth ?
  5175. renderer.path(gridLinePath)
  5176. .attr(attribs).add(axis.gridGroup) :
  5177. null;
  5178. }
  5179. // If the parameter 'old' is set, the current call will be followed
  5180. // by another call, therefore do not do any animations this time
  5181. if (!old && gridLine && gridLinePath) {
  5182. gridLine[tick.isNew ? 'attr' : 'animate']({
  5183. d: gridLinePath,
  5184. opacity: opacity
  5185. });
  5186. }
  5187. }
  5188. // create the tick mark
  5189. if (tickWidth && tickLength) {
  5190. // negate the length
  5191. if (tickPosition === 'inside') {
  5192. tickLength = -tickLength;
  5193. }
  5194. if (axis.opposite) {
  5195. tickLength = -tickLength;
  5196. }
  5197. markPath = tick.getMarkPath(x, y, tickLength, tickWidth * reverseCrisp, horiz, renderer);
  5198. if (mark) { // updating
  5199. mark.animate({
  5200. d: markPath,
  5201. opacity: opacity
  5202. });
  5203. } else { // first time
  5204. tick.mark = renderer.path(
  5205. markPath
  5206. ).attr({
  5207. stroke: tickColor,
  5208. 'stroke-width': tickWidth,
  5209. opacity: opacity
  5210. }).add(axis.axisGroup);
  5211. }
  5212. }
  5213. // the label is created on init - now move it into place
  5214. if (label && !isNaN(x)) {
  5215. label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step);
  5216. // Apply show first and show last. If the tick is both first and last, it is
  5217. // a single centered tick, in which case we show the label anyway (#2100).
  5218. if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) ||
  5219. (tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) {
  5220. show = false;
  5221. // Handle label overflow and show or hide accordingly
  5222. } else if (!axis.isRadial && !labelOptions.step && !labelOptions.rotation && !old && opacity !== 0) {
  5223. show = tick.handleOverflow(index, xy);
  5224. }
  5225. // apply step
  5226. if (step && index % step) {
  5227. // show those indices dividable by step
  5228. show = false;
  5229. }
  5230. // Set the new position, and show or hide
  5231. if (show && !isNaN(xy.y)) {
  5232. xy.opacity = opacity;
  5233. label[tick.isNew ? 'attr' : 'animate'](xy);
  5234. tick.isNew = false;
  5235. } else {
  5236. label.attr('y', -9999); // #1338
  5237. }
  5238. }
  5239. },
  5240. /**
  5241. * Destructor for the tick prototype
  5242. */
  5243. destroy: function () {
  5244. destroyObjectProperties(this, this.axis);
  5245. }
  5246. };
  5247. /**
  5248. * The object wrapper for plot lines and plot bands
  5249. * @param {Object} options
  5250. */
  5251. Highcharts.PlotLineOrBand = function (axis, options) {
  5252. this.axis = axis;
  5253. if (options) {
  5254. this.options = options;
  5255. this.id = options.id;
  5256. }
  5257. };
  5258. Highcharts.PlotLineOrBand.prototype = {
  5259. /**
  5260. * Render the plot line or plot band. If it is already existing,
  5261. * move it.
  5262. */
  5263. render: function () {
  5264. var plotLine = this,
  5265. axis = plotLine.axis,
  5266. horiz = axis.horiz,
  5267. halfPointRange = (axis.pointRange || 0) / 2,
  5268. options = plotLine.options,
  5269. optionsLabel = options.label,
  5270. label = plotLine.label,
  5271. width = options.width,
  5272. to = options.to,
  5273. from = options.from,
  5274. isBand = defined(from) && defined(to),
  5275. value = options.value,
  5276. dashStyle = options.dashStyle,
  5277. svgElem = plotLine.svgElem,
  5278. path = [],
  5279. addEvent,
  5280. eventType,
  5281. xs,
  5282. ys,
  5283. x,
  5284. y,
  5285. color = options.color,
  5286. zIndex = options.zIndex,
  5287. events = options.events,
  5288. attribs = {},
  5289. renderer = axis.chart.renderer;
  5290. // logarithmic conversion
  5291. if (axis.isLog) {
  5292. from = log2lin(from);
  5293. to = log2lin(to);
  5294. value = log2lin(value);
  5295. }
  5296. // plot line
  5297. if (width) {
  5298. path = axis.getPlotLinePath(value, width);
  5299. attribs = {
  5300. stroke: color,
  5301. 'stroke-width': width
  5302. };
  5303. if (dashStyle) {
  5304. attribs.dashstyle = dashStyle;
  5305. }
  5306. } else if (isBand) { // plot band
  5307. // keep within plot area
  5308. from = mathMax(from, axis.min - halfPointRange);
  5309. to = mathMin(to, axis.max + halfPointRange);
  5310. path = axis.getPlotBandPath(from, to, options);
  5311. if (color) {
  5312. attribs.fill = color;
  5313. }
  5314. if (options.borderWidth) {
  5315. attribs.stroke = options.borderColor;
  5316. attribs['stroke-width'] = options.borderWidth;
  5317. }
  5318. } else {
  5319. return;
  5320. }
  5321. // zIndex
  5322. if (defined(zIndex)) {
  5323. attribs.zIndex = zIndex;
  5324. }
  5325. // common for lines and bands
  5326. if (svgElem) {
  5327. if (path) {
  5328. svgElem.animate({
  5329. d: path
  5330. }, null, svgElem.onGetPath);
  5331. } else {
  5332. svgElem.hide();
  5333. svgElem.onGetPath = function () {
  5334. svgElem.show();
  5335. };
  5336. if (label) {
  5337. plotLine.label = label = label.destroy();
  5338. }
  5339. }
  5340. } else if (path && path.length) {
  5341. plotLine.svgElem = svgElem = renderer.path(path)
  5342. .attr(attribs).add();
  5343. // events
  5344. if (events) {
  5345. addEvent = function (eventType) {
  5346. svgElem.on(eventType, function (e) {
  5347. events[eventType].apply(plotLine, [e]);
  5348. });
  5349. };
  5350. for (eventType in events) {
  5351. addEvent(eventType);
  5352. }
  5353. }
  5354. }
  5355. // the plot band/line label
  5356. if (optionsLabel && defined(optionsLabel.text) && path && path.length && axis.width > 0 && axis.height > 0) {
  5357. // apply defaults
  5358. optionsLabel = merge({
  5359. align: horiz && isBand && 'center',
  5360. x: horiz ? !isBand && 4 : 10,
  5361. verticalAlign : !horiz && isBand && 'middle',
  5362. y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4,
  5363. rotation: horiz && !isBand && 90
  5364. }, optionsLabel);
  5365. // add the SVG element
  5366. if (!label) {
  5367. attribs = {
  5368. align: optionsLabel.textAlign || optionsLabel.align,
  5369. rotation: optionsLabel.rotation
  5370. };
  5371. if (defined(zIndex)) {
  5372. attribs.zIndex = zIndex;
  5373. }
  5374. plotLine.label = label = renderer.text(
  5375. optionsLabel.text,
  5376. 0,
  5377. 0,
  5378. optionsLabel.useHTML
  5379. )
  5380. .attr(attribs)
  5381. .css(optionsLabel.style)
  5382. .add();
  5383. }
  5384. // get the bounding box and align the label
  5385. xs = [path[1], path[4], pick(path[6], path[1])];
  5386. ys = [path[2], path[5], pick(path[7], path[2])];
  5387. x = arrayMin(xs);
  5388. y = arrayMin(ys);
  5389. label.align(optionsLabel, false, {
  5390. x: x,
  5391. y: y,
  5392. width: arrayMax(xs) - x,
  5393. height: arrayMax(ys) - y
  5394. });
  5395. label.show();
  5396. } else if (label) { // move out of sight
  5397. label.hide();
  5398. }
  5399. // chainable
  5400. return plotLine;
  5401. },
  5402. /**
  5403. * Remove the plot line or band
  5404. */
  5405. destroy: function () {
  5406. // remove it from the lookup
  5407. erase(this.axis.plotLinesAndBands, this);
  5408. delete this.axis;
  5409. destroyObjectProperties(this);
  5410. }
  5411. };
  5412. /**
  5413. * Object with members for extending the Axis prototype
  5414. */
  5415. AxisPlotLineOrBandExtension = {
  5416. /**
  5417. * Create the path for a plot band
  5418. */
  5419. getPlotBandPath: function (from, to) {
  5420. var toPath = this.getPlotLinePath(to),
  5421. path = this.getPlotLinePath(from);
  5422. if (path && toPath) {
  5423. path.push(
  5424. toPath[4],
  5425. toPath[5],
  5426. toPath[1],
  5427. toPath[2]
  5428. );
  5429. } else { // outside the axis area
  5430. path = null;
  5431. }
  5432. return path;
  5433. },
  5434. addPlotBand: function (options) {
  5435. this.addPlotBandOrLine(options, 'plotBands');
  5436. },
  5437. addPlotLine: function (options) {
  5438. this.addPlotBandOrLine(options, 'plotLines');
  5439. },
  5440. /**
  5441. * Add a plot band or plot line after render time
  5442. *
  5443. * @param options {Object} The plotBand or plotLine configuration object
  5444. */
  5445. addPlotBandOrLine: function (options, coll) {
  5446. var obj = new Highcharts.PlotLineOrBand(this, options).render(),
  5447. userOptions = this.userOptions;
  5448. if (obj) { // #2189
  5449. // Add it to the user options for exporting and Axis.update
  5450. if (coll) {
  5451. userOptions[coll] = userOptions[coll] || [];
  5452. userOptions[coll].push(options);
  5453. }
  5454. this.plotLinesAndBands.push(obj);
  5455. }
  5456. return obj;
  5457. },
  5458. /**
  5459. * Remove a plot band or plot line from the chart by id
  5460. * @param {Object} id
  5461. */
  5462. removePlotBandOrLine: function (id) {
  5463. var plotLinesAndBands = this.plotLinesAndBands,
  5464. options = this.options,
  5465. userOptions = this.userOptions,
  5466. i = plotLinesAndBands.length;
  5467. while (i--) {
  5468. if (plotLinesAndBands[i].id === id) {
  5469. plotLinesAndBands[i].destroy();
  5470. }
  5471. }
  5472. each([options.plotLines || [], userOptions.plotLines || [], options.plotBands || [], userOptions.plotBands || []], function (arr) {
  5473. i = arr.length;
  5474. while (i--) {
  5475. if (arr[i].id === id) {
  5476. erase(arr, arr[i]);
  5477. }
  5478. }
  5479. });
  5480. }
  5481. };
  5482. /**
  5483. * Create a new axis object
  5484. * @param {Object} chart
  5485. * @param {Object} options
  5486. */
  5487. function Axis() {
  5488. this.init.apply(this, arguments);
  5489. }
  5490. Axis.prototype = {
  5491. /**
  5492. * Default options for the X axis - the Y axis has extended defaults
  5493. */
  5494. defaultOptions: {
  5495. // allowDecimals: null,
  5496. // alternateGridColor: null,
  5497. // categories: [],
  5498. dateTimeLabelFormats: {
  5499. millisecond: '%H:%M:%S.%L',
  5500. second: '%H:%M:%S',
  5501. minute: '%H:%M',
  5502. hour: '%H:%M',
  5503. day: '%e. %b',
  5504. week: '%e. %b',
  5505. month: '%b \'%y',
  5506. year: '%Y'
  5507. },
  5508. endOnTick: false,
  5509. gridLineColor: '#C0C0C0',
  5510. // gridLineDashStyle: 'solid',
  5511. // gridLineWidth: 0,
  5512. // reversed: false,
  5513. labels: defaultLabelOptions,
  5514. // { step: null },
  5515. lineColor: '#C0D0E0',
  5516. lineWidth: 1,
  5517. //linkedTo: null,
  5518. //max: undefined,
  5519. //min: undefined,
  5520. minPadding: 0.01,
  5521. maxPadding: 0.01,
  5522. //minRange: null,
  5523. minorGridLineColor: '#E0E0E0',
  5524. // minorGridLineDashStyle: null,
  5525. minorGridLineWidth: 1,
  5526. minorTickColor: '#A0A0A0',
  5527. //minorTickInterval: null,
  5528. minorTickLength: 2,
  5529. minorTickPosition: 'outside', // inside or outside
  5530. //minorTickWidth: 0,
  5531. //opposite: false,
  5532. //offset: 0,
  5533. //plotBands: [{
  5534. // events: {},
  5535. // zIndex: 1,
  5536. // labels: { align, x, verticalAlign, y, style, rotation, textAlign }
  5537. //}],
  5538. //plotLines: [{
  5539. // events: {}
  5540. // dashStyle: {}
  5541. // zIndex:
  5542. // labels: { align, x, verticalAlign, y, style, rotation, textAlign }
  5543. //}],
  5544. //reversed: false,
  5545. // showFirstLabel: true,
  5546. // showLastLabel: true,
  5547. startOfWeek: 1,
  5548. startOnTick: false,
  5549. tickColor: '#C0D0E0',
  5550. //tickInterval: null,
  5551. tickLength: 10,
  5552. tickmarkPlacement: 'between', // on or between
  5553. tickPixelInterval: 100,
  5554. tickPosition: 'outside',
  5555. tickWidth: 1,
  5556. title: {
  5557. //text: null,
  5558. align: 'middle', // low, middle or high
  5559. //margin: 0 for horizontal, 10 for vertical axes,
  5560. //rotation: 0,
  5561. //side: 'outside',
  5562. style: {
  5563. color: '#707070'
  5564. }
  5565. //x: 0,
  5566. //y: 0
  5567. },
  5568. type: 'linear' // linear, logarithmic or datetime
  5569. },
  5570. /**
  5571. * This options set extends the defaultOptions for Y axes
  5572. */
  5573. defaultYAxisOptions: {
  5574. endOnTick: true,
  5575. gridLineWidth: 1,
  5576. tickPixelInterval: 72,
  5577. showLastLabel: true,
  5578. labels: {
  5579. x: -8,
  5580. y: 3
  5581. },
  5582. lineWidth: 0,
  5583. maxPadding: 0.05,
  5584. minPadding: 0.05,
  5585. startOnTick: true,
  5586. tickWidth: 0,
  5587. title: {
  5588. rotation: 270,
  5589. text: 'Values'
  5590. },
  5591. stackLabels: {
  5592. enabled: false,
  5593. //align: dynamic,
  5594. //y: dynamic,
  5595. //x: dynamic,
  5596. //verticalAlign: dynamic,
  5597. //textAlign: dynamic,
  5598. //rotation: 0,
  5599. formatter: function () {
  5600. return numberFormat(this.total, -1);
  5601. },
  5602. style: defaultLabelOptions.style
  5603. }
  5604. },
  5605. /**
  5606. * These options extend the defaultOptions for left axes
  5607. */
  5608. defaultLeftAxisOptions: {
  5609. labels: {
  5610. x: -15,
  5611. y: null
  5612. },
  5613. title: {
  5614. rotation: 270
  5615. }
  5616. },
  5617. /**
  5618. * These options extend the defaultOptions for right axes
  5619. */
  5620. defaultRightAxisOptions: {
  5621. labels: {
  5622. x: 15,
  5623. y: null
  5624. },
  5625. title: {
  5626. rotation: 90
  5627. }
  5628. },
  5629. /**
  5630. * These options extend the defaultOptions for bottom axes
  5631. */
  5632. defaultBottomAxisOptions: {
  5633. labels: {
  5634. x: 0,
  5635. y: 20
  5636. // overflow: undefined,
  5637. // staggerLines: null
  5638. },
  5639. title: {
  5640. rotation: 0
  5641. }
  5642. },
  5643. /**
  5644. * These options extend the defaultOptions for left axes
  5645. */
  5646. defaultTopAxisOptions: {
  5647. labels: {
  5648. x: 0,
  5649. y: -15
  5650. // overflow: undefined
  5651. // staggerLines: null
  5652. },
  5653. title: {
  5654. rotation: 0
  5655. }
  5656. },
  5657. /**
  5658. * Initialize the axis
  5659. */
  5660. init: function (chart, userOptions) {
  5661. var isXAxis = userOptions.isX,
  5662. axis = this;
  5663. // Flag, is the axis horizontal
  5664. axis.horiz = chart.inverted ? !isXAxis : isXAxis;
  5665. // Flag, isXAxis
  5666. axis.isXAxis = isXAxis;
  5667. axis.coll = isXAxis ? 'xAxis' : 'yAxis';
  5668. axis.opposite = userOptions.opposite; // needed in setOptions
  5669. axis.side = userOptions.side || (axis.horiz ?
  5670. (axis.opposite ? 0 : 2) : // top : bottom
  5671. (axis.opposite ? 1 : 3)); // right : left
  5672. axis.setOptions(userOptions);
  5673. var options = this.options,
  5674. type = options.type,
  5675. isDatetimeAxis = type === 'datetime';
  5676. axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format
  5677. // Flag, stagger lines or not
  5678. axis.userOptions = userOptions;
  5679. //axis.axisTitleMargin = UNDEFINED,// = options.title.margin,
  5680. axis.minPixelPadding = 0;
  5681. //axis.ignoreMinPadding = UNDEFINED; // can be set to true by a column or bar series
  5682. //axis.ignoreMaxPadding = UNDEFINED;
  5683. axis.chart = chart;
  5684. axis.reversed = options.reversed;
  5685. axis.zoomEnabled = options.zoomEnabled !== false;
  5686. // Initial categories
  5687. axis.categories = options.categories || type === 'category';
  5688. axis.names = [];
  5689. // Elements
  5690. //axis.axisGroup = UNDEFINED;
  5691. //axis.gridGroup = UNDEFINED;
  5692. //axis.axisTitle = UNDEFINED;
  5693. //axis.axisLine = UNDEFINED;
  5694. // Shorthand types
  5695. axis.isLog = type === 'logarithmic';
  5696. axis.isDatetimeAxis = isDatetimeAxis;
  5697. // Flag, if axis is linked to another axis
  5698. axis.isLinked = defined(options.linkedTo);
  5699. // Linked axis.
  5700. //axis.linkedParent = UNDEFINED;
  5701. // Tick positions
  5702. //axis.tickPositions = UNDEFINED; // array containing predefined positions
  5703. // Tick intervals
  5704. //axis.tickInterval = UNDEFINED;
  5705. //axis.minorTickInterval = UNDEFINED;
  5706. axis.tickmarkOffset = (axis.categories && options.tickmarkPlacement === 'between') ? 0.5 : 0;
  5707. // Major ticks
  5708. axis.ticks = {};
  5709. axis.labelEdge = [];
  5710. // Minor ticks
  5711. axis.minorTicks = {};
  5712. //axis.tickAmount = UNDEFINED;
  5713. // List of plotLines/Bands
  5714. axis.plotLinesAndBands = [];
  5715. // Alternate bands
  5716. axis.alternateBands = {};
  5717. // Axis metrics
  5718. //axis.left = UNDEFINED;
  5719. //axis.top = UNDEFINED;
  5720. //axis.width = UNDEFINED;
  5721. //axis.height = UNDEFINED;
  5722. //axis.bottom = UNDEFINED;
  5723. //axis.right = UNDEFINED;
  5724. //axis.transA = UNDEFINED;
  5725. //axis.transB = UNDEFINED;
  5726. //axis.oldTransA = UNDEFINED;
  5727. axis.len = 0;
  5728. //axis.oldMin = UNDEFINED;
  5729. //axis.oldMax = UNDEFINED;
  5730. //axis.oldUserMin = UNDEFINED;
  5731. //axis.oldUserMax = UNDEFINED;
  5732. //axis.oldAxisLength = UNDEFINED;
  5733. axis.minRange = axis.userMinRange = options.minRange || options.maxZoom;
  5734. axis.range = options.range;
  5735. axis.offset = options.offset || 0;
  5736. // Dictionary for stacks
  5737. axis.stacks = {};
  5738. axis.oldStacks = {};
  5739. // Min and max in the data
  5740. //axis.dataMin = UNDEFINED,
  5741. //axis.dataMax = UNDEFINED,
  5742. // The axis range
  5743. axis.max = null;
  5744. axis.min = null;
  5745. // User set min and max
  5746. //axis.userMin = UNDEFINED,
  5747. //axis.userMax = UNDEFINED,
  5748. // Crosshair options
  5749. axis.crosshair = pick(options.crosshair, splat(chart.options.tooltip.crosshairs)[isXAxis ? 0 : 1], false);
  5750. // Run Axis
  5751. var eventType,
  5752. events = axis.options.events;
  5753. // Register
  5754. if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update()
  5755. if (isXAxis && !this.isColorAxis) { // #2713
  5756. chart.axes.splice(chart.xAxis.length, 0, axis);
  5757. } else {
  5758. chart.axes.push(axis);
  5759. }
  5760. chart[axis.coll].push(axis);
  5761. }
  5762. axis.series = axis.series || []; // populated by Series
  5763. // inverted charts have reversed xAxes as default
  5764. if (chart.inverted && isXAxis && axis.reversed === UNDEFINED) {
  5765. axis.reversed = true;
  5766. }
  5767. axis.removePlotBand = axis.removePlotBandOrLine;
  5768. axis.removePlotLine = axis.removePlotBandOrLine;
  5769. // register event listeners
  5770. for (eventType in events) {
  5771. addEvent(axis, eventType, events[eventType]);
  5772. }
  5773. // extend logarithmic axis
  5774. if (axis.isLog) {
  5775. axis.val2lin = log2lin;
  5776. axis.lin2val = lin2log;
  5777. }
  5778. },
  5779. /**
  5780. * Merge and set options
  5781. */
  5782. setOptions: function (userOptions) {
  5783. this.options = merge(
  5784. this.defaultOptions,
  5785. this.isXAxis ? {} : this.defaultYAxisOptions,
  5786. [this.defaultTopAxisOptions, this.defaultRightAxisOptions,
  5787. this.defaultBottomAxisOptions, this.defaultLeftAxisOptions][this.side],
  5788. merge(
  5789. defaultOptions[this.coll], // if set in setOptions (#1053)
  5790. userOptions
  5791. )
  5792. );
  5793. },
  5794. /**
  5795. * The default label formatter. The context is a special config object for the label.
  5796. */
  5797. defaultLabelFormatter: function () {
  5798. var axis = this.axis,
  5799. value = this.value,
  5800. categories = axis.categories,
  5801. dateTimeLabelFormat = this.dateTimeLabelFormat,
  5802. numericSymbols = defaultOptions.lang.numericSymbols,
  5803. i = numericSymbols && numericSymbols.length,
  5804. multi,
  5805. ret,
  5806. formatOption = axis.options.labels.format,
  5807. // make sure the same symbol is added for all labels on a linear axis
  5808. numericSymbolDetector = axis.isLog ? value : axis.tickInterval;
  5809. if (formatOption) {
  5810. ret = format(formatOption, this);
  5811. } else if (categories) {
  5812. ret = value;
  5813. } else if (dateTimeLabelFormat) { // datetime axis
  5814. ret = dateFormat(dateTimeLabelFormat, value);
  5815. } else if (i && numericSymbolDetector >= 1000) {
  5816. // Decide whether we should add a numeric symbol like k (thousands) or M (millions).
  5817. // If we are to enable this in tooltip or other places as well, we can move this
  5818. // logic to the numberFormatter and enable it by a parameter.
  5819. while (i-- && ret === UNDEFINED) {
  5820. multi = Math.pow(1000, i + 1);
  5821. if (numericSymbolDetector >= multi && numericSymbols[i] !== null) {
  5822. ret = numberFormat(value / multi, -1) + numericSymbols[i];
  5823. }
  5824. }
  5825. }
  5826. if (ret === UNDEFINED) {
  5827. if (mathAbs(value) >= 10000) { // add thousands separators
  5828. ret = numberFormat(value, 0);
  5829. } else { // small numbers
  5830. ret = numberFormat(value, -1, UNDEFINED, ''); // #2466
  5831. }
  5832. }
  5833. return ret;
  5834. },
  5835. /**
  5836. * Get the minimum and maximum for the series of each axis
  5837. */
  5838. getSeriesExtremes: function () {
  5839. var axis = this,
  5840. chart = axis.chart;
  5841. axis.hasVisibleSeries = false;
  5842. // reset dataMin and dataMax in case we're redrawing
  5843. axis.dataMin = axis.dataMax = null;
  5844. if (axis.buildStacks) {
  5845. axis.buildStacks();
  5846. }
  5847. // loop through this axis' series
  5848. each(axis.series, function (series) {
  5849. if (series.visible || !chart.options.chart.ignoreHiddenSeries) {
  5850. var seriesOptions = series.options,
  5851. xData,
  5852. threshold = seriesOptions.threshold,
  5853. seriesDataMin,
  5854. seriesDataMax;
  5855. axis.hasVisibleSeries = true;
  5856. // Validate threshold in logarithmic axes
  5857. if (axis.isLog && threshold <= 0) {
  5858. threshold = null;
  5859. }
  5860. // Get dataMin and dataMax for X axes
  5861. if (axis.isXAxis) {
  5862. xData = series.xData;
  5863. if (xData.length) {
  5864. axis.dataMin = mathMin(pick(axis.dataMin, xData[0]), arrayMin(xData));
  5865. axis.dataMax = mathMax(pick(axis.dataMax, xData[0]), arrayMax(xData));
  5866. }
  5867. // Get dataMin and dataMax for Y axes, as well as handle stacking and processed data
  5868. } else {
  5869. // Get this particular series extremes
  5870. series.getExtremes();
  5871. seriesDataMax = series.dataMax;
  5872. seriesDataMin = series.dataMin;
  5873. // Get the dataMin and dataMax so far. If percentage is used, the min and max are
  5874. // always 0 and 100. If seriesDataMin and seriesDataMax is null, then series
  5875. // doesn't have active y data, we continue with nulls
  5876. if (defined(seriesDataMin) && defined(seriesDataMax)) {
  5877. axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin);
  5878. axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax);
  5879. }
  5880. // Adjust to threshold
  5881. if (defined(threshold)) {
  5882. if (axis.dataMin >= threshold) {
  5883. axis.dataMin = threshold;
  5884. axis.ignoreMinPadding = true;
  5885. } else if (axis.dataMax < threshold) {
  5886. axis.dataMax = threshold;
  5887. axis.ignoreMaxPadding = true;
  5888. }
  5889. }
  5890. }
  5891. }
  5892. });
  5893. },
  5894. /**
  5895. * Translate from axis value to pixel position on the chart, or back
  5896. *
  5897. */
  5898. translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacement) {
  5899. var axis = this,
  5900. sign = 1,
  5901. cvsOffset = 0,
  5902. localA = old ? axis.oldTransA : axis.transA,
  5903. localMin = old ? axis.oldMin : axis.min,
  5904. returnValue,
  5905. minPixelPadding = axis.minPixelPadding,
  5906. postTranslate = (axis.options.ordinal || (axis.isLog && handleLog)) && axis.lin2val;
  5907. if (!localA) {
  5908. localA = axis.transA;
  5909. }
  5910. // In vertical axes, the canvas coordinates start from 0 at the top like in
  5911. // SVG.
  5912. if (cvsCoord) {
  5913. sign *= -1; // canvas coordinates inverts the value
  5914. cvsOffset = axis.len;
  5915. }
  5916. // Handle reversed axis
  5917. if (axis.reversed) {
  5918. sign *= -1;
  5919. cvsOffset -= sign * (axis.sector || axis.len);
  5920. }
  5921. // From pixels to value
  5922. if (backwards) { // reverse translation
  5923. val = val * sign + cvsOffset;
  5924. val -= minPixelPadding;
  5925. returnValue = val / localA + localMin; // from chart pixel to value
  5926. if (postTranslate) { // log and ordinal axes
  5927. returnValue = axis.lin2val(returnValue);
  5928. }
  5929. // From value to pixels
  5930. } else {
  5931. if (postTranslate) { // log and ordinal axes
  5932. val = axis.val2lin(val);
  5933. }
  5934. if (pointPlacement === 'between') {
  5935. pointPlacement = 0.5;
  5936. }
  5937. returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) +
  5938. (isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0);
  5939. }
  5940. return returnValue;
  5941. },
  5942. /**
  5943. * Utility method to translate an axis value to pixel position.
  5944. * @param {Number} value A value in terms of axis units
  5945. * @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart
  5946. * or just the axis/pane itself.
  5947. */
  5948. toPixels: function (value, paneCoordinates) {
  5949. return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos);
  5950. },
  5951. /*
  5952. * Utility method to translate a pixel position in to an axis value
  5953. * @param {Number} pixel The pixel value coordinate
  5954. * @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the
  5955. * axis/pane itself.
  5956. */
  5957. toValue: function (pixel, paneCoordinates) {
  5958. return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true);
  5959. },
  5960. /**
  5961. * Create the path for a plot line that goes from the given value on
  5962. * this axis, across the plot to the opposite side
  5963. * @param {Number} value
  5964. * @param {Number} lineWidth Used for calculation crisp line
  5965. * @param {Number] old Use old coordinates (for resizing and rescaling)
  5966. */
  5967. getPlotLinePath: function (value, lineWidth, old, force, translatedValue) {
  5968. var axis = this,
  5969. chart = axis.chart,
  5970. axisLeft = axis.left,
  5971. axisTop = axis.top,
  5972. x1,
  5973. y1,
  5974. x2,
  5975. y2,
  5976. cHeight = (old && chart.oldChartHeight) || chart.chartHeight,
  5977. cWidth = (old && chart.oldChartWidth) || chart.chartWidth,
  5978. skip,
  5979. transB = axis.transB;
  5980. translatedValue = pick(translatedValue, axis.translate(value, null, null, old));
  5981. x1 = x2 = mathRound(translatedValue + transB);
  5982. y1 = y2 = mathRound(cHeight - translatedValue - transB);
  5983. if (isNaN(translatedValue)) { // no min or max
  5984. skip = true;
  5985. } else if (axis.horiz) {
  5986. y1 = axisTop;
  5987. y2 = cHeight - axis.bottom;
  5988. if (x1 < axisLeft || x1 > axisLeft + axis.width) {
  5989. skip = true;
  5990. }
  5991. } else {
  5992. x1 = axisLeft;
  5993. x2 = cWidth - axis.right;
  5994. if (y1 < axisTop || y1 > axisTop + axis.height) {
  5995. skip = true;
  5996. }
  5997. }
  5998. return skip && !force ?
  5999. null :
  6000. chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 1);
  6001. },
  6002. /**
  6003. * Set the tick positions of a linear axis to round values like whole tens or every five.
  6004. */
  6005. getLinearTickPositions: function (tickInterval, min, max) {
  6006. var pos,
  6007. lastPos,
  6008. roundedMin = correctFloat(mathFloor(min / tickInterval) * tickInterval),
  6009. roundedMax = correctFloat(mathCeil(max / tickInterval) * tickInterval),
  6010. tickPositions = [];
  6011. // For single points, add a tick regardless of the relative position (#2662)
  6012. if (min === max && isNumber(min)) {
  6013. return [min];
  6014. }
  6015. // Populate the intermediate values
  6016. pos = roundedMin;
  6017. while (pos <= roundedMax) {
  6018. // Place the tick on the rounded value
  6019. tickPositions.push(pos);
  6020. // Always add the raw tickInterval, not the corrected one.
  6021. pos = correctFloat(pos + tickInterval);
  6022. // If the interval is not big enough in the current min - max range to actually increase
  6023. // the loop variable, we need to break out to prevent endless loop. Issue #619
  6024. if (pos === lastPos) {
  6025. break;
  6026. }
  6027. // Record the last value
  6028. lastPos = pos;
  6029. }
  6030. return tickPositions;
  6031. },
  6032. /**
  6033. * Return the minor tick positions. For logarithmic axes, reuse the same logic
  6034. * as for major ticks.
  6035. */
  6036. getMinorTickPositions: function () {
  6037. var axis = this,
  6038. options = axis.options,
  6039. tickPositions = axis.tickPositions,
  6040. minorTickInterval = axis.minorTickInterval,
  6041. minorTickPositions = [],
  6042. pos,
  6043. i,
  6044. len;
  6045. if (axis.isLog) {
  6046. len = tickPositions.length;
  6047. for (i = 1; i < len; i++) {
  6048. minorTickPositions = minorTickPositions.concat(
  6049. axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true)
  6050. );
  6051. }
  6052. } else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314
  6053. minorTickPositions = minorTickPositions.concat(
  6054. axis.getTimeTicks(
  6055. axis.normalizeTimeTickInterval(minorTickInterval),
  6056. axis.min,
  6057. axis.max,
  6058. options.startOfWeek
  6059. )
  6060. );
  6061. if (minorTickPositions[0] < axis.min) {
  6062. minorTickPositions.shift();
  6063. }
  6064. } else {
  6065. for (pos = axis.min + (tickPositions[0] - axis.min) % minorTickInterval; pos <= axis.max; pos += minorTickInterval) {
  6066. minorTickPositions.push(pos);
  6067. }
  6068. }
  6069. return minorTickPositions;
  6070. },
  6071. /**
  6072. * Adjust the min and max for the minimum range. Keep in mind that the series data is
  6073. * not yet processed, so we don't have information on data cropping and grouping, or
  6074. * updated axis.pointRange or series.pointRange. The data can't be processed until
  6075. * we have finally established min and max.
  6076. */
  6077. adjustForMinRange: function () {
  6078. var axis = this,
  6079. options = axis.options,
  6080. min = axis.min,
  6081. max = axis.max,
  6082. zoomOffset,
  6083. spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange,
  6084. closestDataRange,
  6085. i,
  6086. distance,
  6087. xData,
  6088. loopLength,
  6089. minArgs,
  6090. maxArgs;
  6091. // Set the automatic minimum range based on the closest point distance
  6092. if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) {
  6093. if (defined(options.min) || defined(options.max)) {
  6094. axis.minRange = null; // don't do this again
  6095. } else {
  6096. // Find the closest distance between raw data points, as opposed to
  6097. // closestPointRange that applies to processed points (cropped and grouped)
  6098. each(axis.series, function (series) {
  6099. xData = series.xData;
  6100. loopLength = series.xIncrement ? 1 : xData.length - 1;
  6101. for (i = loopLength; i > 0; i--) {
  6102. distance = xData[i] - xData[i - 1];
  6103. if (closestDataRange === UNDEFINED || distance < closestDataRange) {
  6104. closestDataRange = distance;
  6105. }
  6106. }
  6107. });
  6108. axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin);
  6109. }
  6110. }
  6111. // if minRange is exceeded, adjust
  6112. if (max - min < axis.minRange) {
  6113. var minRange = axis.minRange;
  6114. zoomOffset = (minRange - max + min) / 2;
  6115. // if min and max options have been set, don't go beyond it
  6116. minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)];
  6117. if (spaceAvailable) { // if space is available, stay within the data range
  6118. minArgs[2] = axis.dataMin;
  6119. }
  6120. min = arrayMax(minArgs);
  6121. maxArgs = [min + minRange, pick(options.max, min + minRange)];
  6122. if (spaceAvailable) { // if space is availabe, stay within the data range
  6123. maxArgs[2] = axis.dataMax;
  6124. }
  6125. max = arrayMin(maxArgs);
  6126. // now if the max is adjusted, adjust the min back
  6127. if (max - min < minRange) {
  6128. minArgs[0] = max - minRange;
  6129. minArgs[1] = pick(options.min, max - minRange);
  6130. min = arrayMax(minArgs);
  6131. }
  6132. }
  6133. // Record modified extremes
  6134. axis.min = min;
  6135. axis.max = max;
  6136. },
  6137. /**
  6138. * Update translation information
  6139. */
  6140. setAxisTranslation: function (saveOld) {
  6141. var axis = this,
  6142. range = axis.max - axis.min,
  6143. pointRange = axis.axisPointRange || 0,
  6144. closestPointRange,
  6145. minPointOffset = 0,
  6146. pointRangePadding = 0,
  6147. linkedParent = axis.linkedParent,
  6148. ordinalCorrection,
  6149. hasCategories = !!axis.categories,
  6150. transA = axis.transA;
  6151. // Adjust translation for padding. Y axis with categories need to go through the same (#1784).
  6152. if (axis.isXAxis || hasCategories || pointRange) {
  6153. if (linkedParent) {
  6154. minPointOffset = linkedParent.minPointOffset;
  6155. pointRangePadding = linkedParent.pointRangePadding;
  6156. } else {
  6157. each(axis.series, function (series) {
  6158. var seriesPointRange = hasCategories ? 1 : (axis.isXAxis ? series.pointRange : (axis.axisPointRange || 0)), // #2806
  6159. pointPlacement = series.options.pointPlacement,
  6160. seriesClosestPointRange = series.closestPointRange;
  6161. if (seriesPointRange > range) { // #1446
  6162. seriesPointRange = 0;
  6163. }
  6164. pointRange = mathMax(pointRange, seriesPointRange);
  6165. // minPointOffset is the value padding to the left of the axis in order to make
  6166. // room for points with a pointRange, typically columns. When the pointPlacement option
  6167. // is 'between' or 'on', this padding does not apply.
  6168. minPointOffset = mathMax(
  6169. minPointOffset,
  6170. isString(pointPlacement) ? 0 : seriesPointRange / 2
  6171. );
  6172. // Determine the total padding needed to the length of the axis to make room for the
  6173. // pointRange. If the series' pointPlacement is 'on', no padding is added.
  6174. pointRangePadding = mathMax(
  6175. pointRangePadding,
  6176. pointPlacement === 'on' ? 0 : seriesPointRange
  6177. );
  6178. // Set the closestPointRange
  6179. if (!series.noSharedTooltip && defined(seriesClosestPointRange)) {
  6180. closestPointRange = defined(closestPointRange) ?
  6181. mathMin(closestPointRange, seriesClosestPointRange) :
  6182. seriesClosestPointRange;
  6183. }
  6184. });
  6185. }
  6186. // Record minPointOffset and pointRangePadding
  6187. ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853
  6188. axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection;
  6189. axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection;
  6190. // pointRange means the width reserved for each point, like in a column chart
  6191. axis.pointRange = mathMin(pointRange, range);
  6192. // closestPointRange means the closest distance between points. In columns
  6193. // it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange
  6194. // is some other value
  6195. axis.closestPointRange = closestPointRange;
  6196. }
  6197. // Secondary values
  6198. if (saveOld) {
  6199. axis.oldTransA = transA;
  6200. }
  6201. axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1);
  6202. axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend
  6203. axis.minPixelPadding = transA * minPointOffset;
  6204. },
  6205. /**
  6206. * Set the tick positions to round values and optionally extend the extremes
  6207. * to the nearest tick
  6208. */
  6209. setTickPositions: function (secondPass) {
  6210. var axis = this,
  6211. chart = axis.chart,
  6212. options = axis.options,
  6213. isLog = axis.isLog,
  6214. isDatetimeAxis = axis.isDatetimeAxis,
  6215. isXAxis = axis.isXAxis,
  6216. isLinked = axis.isLinked,
  6217. tickPositioner = axis.options.tickPositioner,
  6218. maxPadding = options.maxPadding,
  6219. minPadding = options.minPadding,
  6220. length,
  6221. linkedParentExtremes,
  6222. tickIntervalOption = options.tickInterval,
  6223. minTickIntervalOption = options.minTickInterval,
  6224. tickPixelIntervalOption = options.tickPixelInterval,
  6225. tickPositions,
  6226. keepTwoTicksOnly,
  6227. categories = axis.categories;
  6228. // linked axis gets the extremes from the parent axis
  6229. if (isLinked) {
  6230. axis.linkedParent = chart[axis.coll][options.linkedTo];
  6231. linkedParentExtremes = axis.linkedParent.getExtremes();
  6232. axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin);
  6233. axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax);
  6234. if (options.type !== axis.linkedParent.options.type) {
  6235. error(11, 1); // Can't link axes of different type
  6236. }
  6237. } else { // initial min and max from the extreme data values
  6238. axis.min = pick(axis.userMin, options.min, axis.dataMin);
  6239. axis.max = pick(axis.userMax, options.max, axis.dataMax);
  6240. }
  6241. if (isLog) {
  6242. if (!secondPass && mathMin(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978
  6243. error(10, 1); // Can't plot negative values on log axis
  6244. }
  6245. axis.min = correctFloat(log2lin(axis.min)); // correctFloat cures #934
  6246. axis.max = correctFloat(log2lin(axis.max));
  6247. }
  6248. // handle zoomed range
  6249. if (axis.range && defined(axis.max)) {
  6250. axis.userMin = axis.min = mathMax(axis.min, axis.max - axis.range); // #618
  6251. axis.userMax = axis.max;
  6252. axis.range = null; // don't use it when running setExtremes
  6253. }
  6254. // Hook for adjusting this.min and this.max. Used by bubble series.
  6255. if (axis.beforePadding) {
  6256. axis.beforePadding();
  6257. }
  6258. // adjust min and max for the minimum range
  6259. axis.adjustForMinRange();
  6260. // Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding
  6261. // into account, we do this after computing tick interval (#1337).
  6262. if (!categories && !axis.axisPointRange && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) {
  6263. length = axis.max - axis.min;
  6264. if (length) {
  6265. if (!defined(options.min) && !defined(axis.userMin) && minPadding && (axis.dataMin < 0 || !axis.ignoreMinPadding)) {
  6266. axis.min -= length * minPadding;
  6267. }
  6268. if (!defined(options.max) && !defined(axis.userMax) && maxPadding && (axis.dataMax > 0 || !axis.ignoreMaxPadding)) {
  6269. axis.max += length * maxPadding;
  6270. }
  6271. }
  6272. }
  6273. // Stay within floor and ceiling
  6274. if (isNumber(options.floor)) {
  6275. axis.min = mathMax(axis.min, options.floor);
  6276. }
  6277. if (isNumber(options.ceiling)) {
  6278. axis.max = mathMin(axis.max, options.ceiling);
  6279. }
  6280. // get tickInterval
  6281. if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) {
  6282. axis.tickInterval = 1;
  6283. } else if (isLinked && !tickIntervalOption &&
  6284. tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) {
  6285. axis.tickInterval = axis.linkedParent.tickInterval;
  6286. } else {
  6287. axis.tickInterval = pick(
  6288. tickIntervalOption,
  6289. categories ? // for categoried axis, 1 is default, for linear axis use tickPix
  6290. 1 :
  6291. // don't let it be more than the data range
  6292. (axis.max - axis.min) * tickPixelIntervalOption / mathMax(axis.len, tickPixelIntervalOption)
  6293. );
  6294. // For squished axes, set only two ticks
  6295. if (!defined(tickIntervalOption) && axis.len < tickPixelIntervalOption && !this.isRadial &&
  6296. !this.isLog && !categories && options.startOnTick && options.endOnTick) {
  6297. keepTwoTicksOnly = true;
  6298. axis.tickInterval /= 4; // tick extremes closer to the real values
  6299. }
  6300. }
  6301. // Now we're finished detecting min and max, crop and group series data. This
  6302. // is in turn needed in order to find tick positions in ordinal axes.
  6303. if (isXAxis && !secondPass) {
  6304. each(axis.series, function (series) {
  6305. series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax);
  6306. });
  6307. }
  6308. // set the translation factor used in translate function
  6309. axis.setAxisTranslation(true);
  6310. // hook for ordinal axes and radial axes
  6311. if (axis.beforeSetTickPositions) {
  6312. axis.beforeSetTickPositions();
  6313. }
  6314. // hook for extensions, used in Highstock ordinal axes
  6315. if (axis.postProcessTickInterval) {
  6316. axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval);
  6317. }
  6318. // In column-like charts, don't cramp in more ticks than there are points (#1943)
  6319. if (axis.pointRange) {
  6320. axis.tickInterval = mathMax(axis.pointRange, axis.tickInterval);
  6321. }
  6322. // Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined.
  6323. if (!tickIntervalOption && axis.tickInterval < minTickIntervalOption) {
  6324. axis.tickInterval = minTickIntervalOption;
  6325. }
  6326. // for linear axes, get magnitude and normalize the interval
  6327. if (!isDatetimeAxis && !isLog) { // linear
  6328. if (!tickIntervalOption) {
  6329. axis.tickInterval = normalizeTickInterval(axis.tickInterval, null, getMagnitude(axis.tickInterval), options);
  6330. }
  6331. }
  6332. // get minorTickInterval
  6333. axis.minorTickInterval = options.minorTickInterval === 'auto' && axis.tickInterval ?
  6334. axis.tickInterval / 5 : options.minorTickInterval;
  6335. // find the tick positions
  6336. axis.tickPositions = tickPositions = options.tickPositions ?
  6337. [].concat(options.tickPositions) : // Work on a copy (#1565)
  6338. (tickPositioner && tickPositioner.apply(axis, [axis.min, axis.max]));
  6339. if (!tickPositions) {
  6340. // Too many ticks
  6341. if (!axis.ordinalPositions && (axis.max - axis.min) / axis.tickInterval > mathMax(2 * axis.len, 200)) {
  6342. error(19, true);
  6343. }
  6344. if (isDatetimeAxis) {
  6345. tickPositions = axis.getTimeTicks(
  6346. axis.normalizeTimeTickInterval(axis.tickInterval, options.units),
  6347. axis.min,
  6348. axis.max,
  6349. options.startOfWeek,
  6350. axis.ordinalPositions,
  6351. axis.closestPointRange,
  6352. true
  6353. );
  6354. } else if (isLog) {
  6355. tickPositions = axis.getLogTickPositions(axis.tickInterval, axis.min, axis.max);
  6356. } else {
  6357. tickPositions = axis.getLinearTickPositions(axis.tickInterval, axis.min, axis.max);
  6358. }
  6359. if (keepTwoTicksOnly) {
  6360. tickPositions.splice(1, tickPositions.length - 2);
  6361. }
  6362. axis.tickPositions = tickPositions;
  6363. }
  6364. if (!isLinked) {
  6365. // reset min/max or remove extremes based on start/end on tick
  6366. var roundedMin = tickPositions[0],
  6367. roundedMax = tickPositions[tickPositions.length - 1],
  6368. minPointOffset = axis.minPointOffset || 0,
  6369. singlePad;
  6370. if (options.startOnTick) {
  6371. axis.min = roundedMin;
  6372. } else if (axis.min - minPointOffset > roundedMin) {
  6373. tickPositions.shift();
  6374. }
  6375. if (options.endOnTick) {
  6376. axis.max = roundedMax;
  6377. } else if (axis.max + minPointOffset < roundedMax) {
  6378. tickPositions.pop();
  6379. }
  6380. // When there is only one point, or all points have the same value on this axis, then min
  6381. // and max are equal and tickPositions.length is 0 or 1. In this case, add some padding
  6382. // in order to center the point, but leave it with one tick. #1337.
  6383. if (tickPositions.length === 1) {
  6384. singlePad = mathAbs(axis.max) > 10e12 ? 1 : 0.001; // The lowest possible number to avoid extra padding on columns (#2619, #2846)
  6385. axis.min -= singlePad;
  6386. axis.max += singlePad;
  6387. }
  6388. }
  6389. },
  6390. /**
  6391. * Set the max ticks of either the x and y axis collection
  6392. */
  6393. setMaxTicks: function () {
  6394. var chart = this.chart,
  6395. maxTicks = chart.maxTicks || {},
  6396. tickPositions = this.tickPositions,
  6397. key = this._maxTicksKey = [this.coll, this.pos, this.len].join('-');
  6398. if (!this.isLinked && !this.isDatetimeAxis && tickPositions && tickPositions.length > (maxTicks[key] || 0) && this.options.alignTicks !== false) {
  6399. maxTicks[key] = tickPositions.length;
  6400. }
  6401. chart.maxTicks = maxTicks;
  6402. },
  6403. /**
  6404. * When using multiple axes, adjust the number of ticks to match the highest
  6405. * number of ticks in that group
  6406. */
  6407. adjustTickAmount: function () {
  6408. var axis = this,
  6409. chart = axis.chart,
  6410. key = axis._maxTicksKey,
  6411. tickPositions = axis.tickPositions,
  6412. maxTicks = chart.maxTicks;
  6413. if (maxTicks && maxTicks[key] && !axis.isDatetimeAxis && !axis.categories && !axis.isLinked &&
  6414. axis.options.alignTicks !== false && this.min !== UNDEFINED) {
  6415. var oldTickAmount = axis.tickAmount,
  6416. calculatedTickAmount = tickPositions.length,
  6417. tickAmount;
  6418. // set the axis-level tickAmount to use below
  6419. axis.tickAmount = tickAmount = maxTicks[key];
  6420. if (calculatedTickAmount < tickAmount) {
  6421. while (tickPositions.length < tickAmount) {
  6422. tickPositions.push(correctFloat(
  6423. tickPositions[tickPositions.length - 1] + axis.tickInterval
  6424. ));
  6425. }
  6426. axis.transA *= (calculatedTickAmount - 1) / (tickAmount - 1);
  6427. axis.max = tickPositions[tickPositions.length - 1];
  6428. }
  6429. if (defined(oldTickAmount) && tickAmount !== oldTickAmount) {
  6430. axis.isDirty = true;
  6431. }
  6432. }
  6433. },
  6434. /**
  6435. * Set the scale based on data min and max, user set min and max or options
  6436. *
  6437. */
  6438. setScale: function () {
  6439. var axis = this,
  6440. stacks = axis.stacks,
  6441. type,
  6442. i,
  6443. isDirtyData,
  6444. isDirtyAxisLength;
  6445. axis.oldMin = axis.min;
  6446. axis.oldMax = axis.max;
  6447. axis.oldAxisLength = axis.len;
  6448. // set the new axisLength
  6449. axis.setAxisSize();
  6450. //axisLength = horiz ? axisWidth : axisHeight;
  6451. isDirtyAxisLength = axis.len !== axis.oldAxisLength;
  6452. // is there new data?
  6453. each(axis.series, function (series) {
  6454. if (series.isDirtyData || series.isDirty ||
  6455. series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well
  6456. isDirtyData = true;
  6457. }
  6458. });
  6459. // do we really need to go through all this?
  6460. if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw ||
  6461. axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax) {
  6462. // reset stacks
  6463. if (!axis.isXAxis) {
  6464. for (type in stacks) {
  6465. for (i in stacks[type]) {
  6466. stacks[type][i].total = null;
  6467. stacks[type][i].cum = 0;
  6468. }
  6469. }
  6470. }
  6471. axis.forceRedraw = false;
  6472. // get data extremes if needed
  6473. axis.getSeriesExtremes();
  6474. // get fixed positions based on tickInterval
  6475. axis.setTickPositions();
  6476. // record old values to decide whether a rescale is necessary later on (#540)
  6477. axis.oldUserMin = axis.userMin;
  6478. axis.oldUserMax = axis.userMax;
  6479. // Mark as dirty if it is not already set to dirty and extremes have changed. #595.
  6480. if (!axis.isDirty) {
  6481. axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax;
  6482. }
  6483. } else if (!axis.isXAxis) {
  6484. if (axis.oldStacks) {
  6485. stacks = axis.stacks = axis.oldStacks;
  6486. }
  6487. // reset stacks
  6488. for (type in stacks) {
  6489. for (i in stacks[type]) {
  6490. stacks[type][i].cum = stacks[type][i].total;
  6491. }
  6492. }
  6493. }
  6494. // Set the maximum tick amount
  6495. axis.setMaxTicks();
  6496. },
  6497. /**
  6498. * Set the extremes and optionally redraw
  6499. * @param {Number} newMin
  6500. * @param {Number} newMax
  6501. * @param {Boolean} redraw
  6502. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  6503. * configuration
  6504. * @param {Object} eventArguments
  6505. *
  6506. */
  6507. setExtremes: function (newMin, newMax, redraw, animation, eventArguments) {
  6508. var axis = this,
  6509. chart = axis.chart;
  6510. redraw = pick(redraw, true); // defaults to true
  6511. // Extend the arguments with min and max
  6512. eventArguments = extend(eventArguments, {
  6513. min: newMin,
  6514. max: newMax
  6515. });
  6516. // Fire the event
  6517. fireEvent(axis, 'setExtremes', eventArguments, function () { // the default event handler
  6518. axis.userMin = newMin;
  6519. axis.userMax = newMax;
  6520. axis.eventArgs = eventArguments;
  6521. // Mark for running afterSetExtremes
  6522. axis.isDirtyExtremes = true;
  6523. // redraw
  6524. if (redraw) {
  6525. chart.redraw(animation);
  6526. }
  6527. });
  6528. },
  6529. /**
  6530. * Overridable method for zooming chart. Pulled out in a separate method to allow overriding
  6531. * in stock charts.
  6532. */
  6533. zoom: function (newMin, newMax) {
  6534. var dataMin = this.dataMin,
  6535. dataMax = this.dataMax,
  6536. options = this.options;
  6537. // Prevent pinch zooming out of range. Check for defined is for #1946. #1734.
  6538. if (!this.allowZoomOutside) {
  6539. if (defined(dataMin) && newMin <= mathMin(dataMin, pick(options.min, dataMin))) {
  6540. newMin = UNDEFINED;
  6541. }
  6542. if (defined(dataMax) && newMax >= mathMax(dataMax, pick(options.max, dataMax))) {
  6543. newMax = UNDEFINED;
  6544. }
  6545. }
  6546. // In full view, displaying the reset zoom button is not required
  6547. this.displayBtn = newMin !== UNDEFINED || newMax !== UNDEFINED;
  6548. // Do it
  6549. this.setExtremes(
  6550. newMin,
  6551. newMax,
  6552. false,
  6553. UNDEFINED,
  6554. { trigger: 'zoom' }
  6555. );
  6556. return true;
  6557. },
  6558. /**
  6559. * Update the axis metrics
  6560. */
  6561. setAxisSize: function () {
  6562. var chart = this.chart,
  6563. options = this.options,
  6564. offsetLeft = options.offsetLeft || 0,
  6565. offsetRight = options.offsetRight || 0,
  6566. horiz = this.horiz,
  6567. width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight),
  6568. height = pick(options.height, chart.plotHeight),
  6569. top = pick(options.top, chart.plotTop),
  6570. left = pick(options.left, chart.plotLeft + offsetLeft),
  6571. percentRegex = /%$/; // docs
  6572. // Check for percentage based input values
  6573. if (percentRegex.test(height)) {
  6574. height = parseInt(height, 10) / 100 * chart.plotHeight;
  6575. }
  6576. if (percentRegex.test(top)) {
  6577. top = parseInt(top, 10) / 100 * chart.plotHeight + chart.plotTop;
  6578. }
  6579. // Expose basic values to use in Series object and navigator
  6580. this.left = left;
  6581. this.top = top;
  6582. this.width = width;
  6583. this.height = height;
  6584. this.bottom = chart.chartHeight - height - top;
  6585. this.right = chart.chartWidth - width - left;
  6586. // Direction agnostic properties
  6587. this.len = mathMax(horiz ? width : height, 0); // mathMax fixes #905
  6588. this.pos = horiz ? left : top; // distance from SVG origin
  6589. },
  6590. /**
  6591. * Get the actual axis extremes
  6592. */
  6593. getExtremes: function () {
  6594. var axis = this,
  6595. isLog = axis.isLog;
  6596. return {
  6597. min: isLog ? correctFloat(lin2log(axis.min)) : axis.min,
  6598. max: isLog ? correctFloat(lin2log(axis.max)) : axis.max,
  6599. dataMin: axis.dataMin,
  6600. dataMax: axis.dataMax,
  6601. userMin: axis.userMin,
  6602. userMax: axis.userMax
  6603. };
  6604. },
  6605. /**
  6606. * Get the zero plane either based on zero or on the min or max value.
  6607. * Used in bar and area plots
  6608. */
  6609. getThreshold: function (threshold) {
  6610. var axis = this,
  6611. isLog = axis.isLog;
  6612. var realMin = isLog ? lin2log(axis.min) : axis.min,
  6613. realMax = isLog ? lin2log(axis.max) : axis.max;
  6614. if (realMin > threshold || threshold === null) {
  6615. threshold = realMin;
  6616. } else if (realMax < threshold) {
  6617. threshold = realMax;
  6618. }
  6619. return axis.translate(threshold, 0, 1, 0, 1);
  6620. },
  6621. /**
  6622. * Compute auto alignment for the axis label based on which side the axis is on
  6623. * and the given rotation for the label
  6624. */
  6625. autoLabelAlign: function (rotation) {
  6626. var ret,
  6627. angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360;
  6628. if (angle > 15 && angle < 165) {
  6629. ret = 'right';
  6630. } else if (angle > 195 && angle < 345) {
  6631. ret = 'left';
  6632. } else {
  6633. ret = 'center';
  6634. }
  6635. return ret;
  6636. },
  6637. /**
  6638. * Render the tick labels to a preliminary position to get their sizes
  6639. */
  6640. getOffset: function () {
  6641. var axis = this,
  6642. chart = axis.chart,
  6643. renderer = chart.renderer,
  6644. options = axis.options,
  6645. tickPositions = axis.tickPositions,
  6646. ticks = axis.ticks,
  6647. horiz = axis.horiz,
  6648. side = axis.side,
  6649. invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side,
  6650. hasData,
  6651. showAxis,
  6652. titleOffset = 0,
  6653. titleOffsetOption,
  6654. titleMargin = 0,
  6655. axisTitleOptions = options.title,
  6656. labelOptions = options.labels,
  6657. labelOffset = 0, // reset
  6658. axisOffset = chart.axisOffset,
  6659. clipOffset = chart.clipOffset,
  6660. directionFactor = [-1, 1, 1, -1][side],
  6661. n,
  6662. i,
  6663. autoStaggerLines = 1,
  6664. maxStaggerLines = pick(labelOptions.maxStaggerLines, 5),
  6665. sortedPositions,
  6666. lastRight,
  6667. overlap,
  6668. pos,
  6669. bBox,
  6670. x,
  6671. w,
  6672. lineNo,
  6673. lineHeightCorrection = side === 2 ? renderer.fontMetrics(labelOptions.style.fontSize).b : 0;
  6674. // For reuse in Axis.render
  6675. axis.hasData = hasData = (axis.hasVisibleSeries || (defined(axis.min) && defined(axis.max) && !!tickPositions));
  6676. axis.showAxis = showAxis = hasData || pick(options.showEmpty, true);
  6677. // Set/reset staggerLines
  6678. axis.staggerLines = axis.horiz && labelOptions.staggerLines;
  6679. // Create the axisGroup and gridGroup elements on first iteration
  6680. if (!axis.axisGroup) {
  6681. axis.gridGroup = renderer.g('grid')
  6682. .attr({ zIndex: options.gridZIndex || 1 })
  6683. .add();
  6684. axis.axisGroup = renderer.g('axis')
  6685. .attr({ zIndex: options.zIndex || 2 })
  6686. .add();
  6687. axis.labelGroup = renderer.g('axis-labels')
  6688. .attr({ zIndex: labelOptions.zIndex || 7 })
  6689. .addClass(PREFIX + axis.coll.toLowerCase() + '-labels')
  6690. .add();
  6691. }
  6692. if (hasData || axis.isLinked) {
  6693. // Set the explicit or automatic label alignment
  6694. axis.labelAlign = pick(labelOptions.align || axis.autoLabelAlign(labelOptions.rotation));
  6695. // Generate ticks
  6696. each(tickPositions, function (pos) {
  6697. if (!ticks[pos]) {
  6698. ticks[pos] = new Tick(axis, pos);
  6699. } else {
  6700. ticks[pos].addLabel(); // update labels depending on tick interval
  6701. }
  6702. });
  6703. // Handle automatic stagger lines
  6704. if (axis.horiz && !axis.staggerLines && maxStaggerLines && !labelOptions.rotation) {
  6705. sortedPositions = axis.reversed ? [].concat(tickPositions).reverse() : tickPositions;
  6706. while (autoStaggerLines < maxStaggerLines) {
  6707. lastRight = [];
  6708. overlap = false;
  6709. for (i = 0; i < sortedPositions.length; i++) {
  6710. pos = sortedPositions[i];
  6711. bBox = ticks[pos].label && ticks[pos].label.getBBox();
  6712. w = bBox ? bBox.width : 0;
  6713. lineNo = i % autoStaggerLines;
  6714. if (w) {
  6715. x = axis.translate(pos); // don't handle log
  6716. if (lastRight[lineNo] !== UNDEFINED && x < lastRight[lineNo]) {
  6717. overlap = true;
  6718. }
  6719. lastRight[lineNo] = x + w;
  6720. }
  6721. }
  6722. if (overlap) {
  6723. autoStaggerLines++;
  6724. } else {
  6725. break;
  6726. }
  6727. }
  6728. if (autoStaggerLines > 1) {
  6729. axis.staggerLines = autoStaggerLines;
  6730. }
  6731. }
  6732. each(tickPositions, function (pos) {
  6733. // left side must be align: right and right side must have align: left for labels
  6734. if (side === 0 || side === 2 || { 1: 'left', 3: 'right' }[side] === axis.labelAlign) {
  6735. // get the highest offset
  6736. labelOffset = mathMax(
  6737. ticks[pos].getLabelSize(),
  6738. labelOffset
  6739. );
  6740. }
  6741. });
  6742. if (axis.staggerLines) {
  6743. labelOffset *= axis.staggerLines;
  6744. axis.labelOffset = labelOffset;
  6745. }
  6746. } else { // doesn't have data
  6747. for (n in ticks) {
  6748. ticks[n].destroy();
  6749. delete ticks[n];
  6750. }
  6751. }
  6752. if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) {
  6753. if (!axis.axisTitle) {
  6754. axis.axisTitle = renderer.text(
  6755. axisTitleOptions.text,
  6756. 0,
  6757. 0,
  6758. axisTitleOptions.useHTML
  6759. )
  6760. .attr({
  6761. zIndex: 7,
  6762. rotation: axisTitleOptions.rotation || 0,
  6763. align:
  6764. axisTitleOptions.textAlign ||
  6765. { low: 'left', middle: 'center', high: 'right' }[axisTitleOptions.align]
  6766. })
  6767. .addClass(PREFIX + this.coll.toLowerCase() + '-title')
  6768. .css(axisTitleOptions.style)
  6769. .add(axis.axisGroup);
  6770. axis.axisTitle.isNew = true;
  6771. }
  6772. if (showAxis) {
  6773. titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width'];
  6774. titleMargin = pick(axisTitleOptions.margin, horiz ? 5 : 10);
  6775. titleOffsetOption = axisTitleOptions.offset;
  6776. }
  6777. // hide or show the title depending on whether showEmpty is set
  6778. axis.axisTitle[showAxis ? 'show' : 'hide']();
  6779. }
  6780. // handle automatic or user set offset
  6781. axis.offset = directionFactor * pick(options.offset, axisOffset[side]);
  6782. axis.axisTitleMargin =
  6783. pick(titleOffsetOption,
  6784. labelOffset + titleMargin +
  6785. (labelOffset && (directionFactor * options.labels[horiz ? 'y' : 'x'] - lineHeightCorrection))
  6786. );
  6787. axisOffset[side] = mathMax(
  6788. axisOffset[side],
  6789. axis.axisTitleMargin + titleOffset + directionFactor * axis.offset
  6790. );
  6791. clipOffset[invertedSide] = mathMax(clipOffset[invertedSide], mathFloor(options.lineWidth / 2) * 2);
  6792. },
  6793. /**
  6794. * Get the path for the axis line
  6795. */
  6796. getLinePath: function (lineWidth) {
  6797. var chart = this.chart,
  6798. opposite = this.opposite,
  6799. offset = this.offset,
  6800. horiz = this.horiz,
  6801. lineLeft = this.left + (opposite ? this.width : 0) + offset,
  6802. lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset;
  6803. if (opposite) {
  6804. lineWidth *= -1; // crispify the other way - #1480, #1687
  6805. }
  6806. return chart.renderer.crispLine([
  6807. M,
  6808. horiz ?
  6809. this.left :
  6810. lineLeft,
  6811. horiz ?
  6812. lineTop :
  6813. this.top,
  6814. L,
  6815. horiz ?
  6816. chart.chartWidth - this.right :
  6817. lineLeft,
  6818. horiz ?
  6819. lineTop :
  6820. chart.chartHeight - this.bottom
  6821. ], lineWidth);
  6822. },
  6823. /**
  6824. * Position the title
  6825. */
  6826. getTitlePosition: function () {
  6827. // compute anchor points for each of the title align options
  6828. var horiz = this.horiz,
  6829. axisLeft = this.left,
  6830. axisTop = this.top,
  6831. axisLength = this.len,
  6832. axisTitleOptions = this.options.title,
  6833. margin = horiz ? axisLeft : axisTop,
  6834. opposite = this.opposite,
  6835. offset = this.offset,
  6836. fontSize = pInt(axisTitleOptions.style.fontSize || 12),
  6837. // the position in the length direction of the axis
  6838. alongAxis = {
  6839. low: margin + (horiz ? 0 : axisLength),
  6840. middle: margin + axisLength / 2,
  6841. high: margin + (horiz ? axisLength : 0)
  6842. }[axisTitleOptions.align],
  6843. // the position in the perpendicular direction of the axis
  6844. offAxis = (horiz ? axisTop + this.height : axisLeft) +
  6845. (horiz ? 1 : -1) * // horizontal axis reverses the margin
  6846. (opposite ? -1 : 1) * // so does opposite axes
  6847. this.axisTitleMargin +
  6848. (this.side === 2 ? fontSize : 0);
  6849. return {
  6850. x: horiz ?
  6851. alongAxis :
  6852. offAxis + (opposite ? this.width : 0) + offset +
  6853. (axisTitleOptions.x || 0), // x
  6854. y: horiz ?
  6855. offAxis - (opposite ? this.height : 0) + offset :
  6856. alongAxis + (axisTitleOptions.y || 0) // y
  6857. };
  6858. },
  6859. /**
  6860. * Render the axis
  6861. */
  6862. render: function () {
  6863. var axis = this,
  6864. horiz = axis.horiz,
  6865. reversed = axis.reversed,
  6866. chart = axis.chart,
  6867. renderer = chart.renderer,
  6868. options = axis.options,
  6869. isLog = axis.isLog,
  6870. isLinked = axis.isLinked,
  6871. tickPositions = axis.tickPositions,
  6872. sortedPositions,
  6873. axisTitle = axis.axisTitle,
  6874. ticks = axis.ticks,
  6875. minorTicks = axis.minorTicks,
  6876. alternateBands = axis.alternateBands,
  6877. stackLabelOptions = options.stackLabels,
  6878. alternateGridColor = options.alternateGridColor,
  6879. tickmarkOffset = axis.tickmarkOffset,
  6880. lineWidth = options.lineWidth,
  6881. linePath,
  6882. hasRendered = chart.hasRendered,
  6883. slideInTicks = hasRendered && defined(axis.oldMin) && !isNaN(axis.oldMin),
  6884. hasData = axis.hasData,
  6885. showAxis = axis.showAxis,
  6886. from,
  6887. overflow = options.labels.overflow,
  6888. justifyLabels = axis.justifyLabels = horiz && overflow !== false,
  6889. to;
  6890. // Reset
  6891. axis.labelEdge.length = 0;
  6892. axis.justifyToPlot = overflow === 'justify';
  6893. // Mark all elements inActive before we go over and mark the active ones
  6894. each([ticks, minorTicks, alternateBands], function (coll) {
  6895. var pos;
  6896. for (pos in coll) {
  6897. coll[pos].isActive = false;
  6898. }
  6899. });
  6900. // If the series has data draw the ticks. Else only the line and title
  6901. if (hasData || isLinked) {
  6902. // minor ticks
  6903. if (axis.minorTickInterval && !axis.categories) {
  6904. each(axis.getMinorTickPositions(), function (pos) {
  6905. if (!minorTicks[pos]) {
  6906. minorTicks[pos] = new Tick(axis, pos, 'minor');
  6907. }
  6908. // render new ticks in old position
  6909. if (slideInTicks && minorTicks[pos].isNew) {
  6910. minorTicks[pos].render(null, true);
  6911. }
  6912. minorTicks[pos].render(null, false, 1);
  6913. });
  6914. }
  6915. // Major ticks. Pull out the first item and render it last so that
  6916. // we can get the position of the neighbour label. #808.
  6917. if (tickPositions.length) { // #1300
  6918. sortedPositions = tickPositions.slice();
  6919. if ((horiz && reversed) || (!horiz && !reversed)) {
  6920. sortedPositions.reverse();
  6921. }
  6922. if (justifyLabels) {
  6923. sortedPositions = sortedPositions.slice(1).concat([sortedPositions[0]]);
  6924. }
  6925. each(sortedPositions, function (pos, i) {
  6926. // Reorganize the indices
  6927. if (justifyLabels) {
  6928. i = (i === sortedPositions.length - 1) ? 0 : i + 1;
  6929. }
  6930. // linked axes need an extra check to find out if
  6931. if (!isLinked || (pos >= axis.min && pos <= axis.max)) {
  6932. if (!ticks[pos]) {
  6933. ticks[pos] = new Tick(axis, pos);
  6934. }
  6935. // render new ticks in old position
  6936. if (slideInTicks && ticks[pos].isNew) {
  6937. ticks[pos].render(i, true, 0.1);
  6938. }
  6939. ticks[pos].render(i, false, 1);
  6940. }
  6941. });
  6942. // In a categorized axis, the tick marks are displayed between labels. So
  6943. // we need to add a tick mark and grid line at the left edge of the X axis.
  6944. if (tickmarkOffset && axis.min === 0) {
  6945. if (!ticks[-1]) {
  6946. ticks[-1] = new Tick(axis, -1, null, true);
  6947. }
  6948. ticks[-1].render(-1);
  6949. }
  6950. }
  6951. // alternate grid color
  6952. if (alternateGridColor) {
  6953. each(tickPositions, function (pos, i) {
  6954. if (i % 2 === 0 && pos < axis.max) {
  6955. if (!alternateBands[pos]) {
  6956. alternateBands[pos] = new Highcharts.PlotLineOrBand(axis);
  6957. }
  6958. from = pos + tickmarkOffset; // #949
  6959. to = tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] + tickmarkOffset : axis.max;
  6960. alternateBands[pos].options = {
  6961. from: isLog ? lin2log(from) : from,
  6962. to: isLog ? lin2log(to) : to,
  6963. color: alternateGridColor
  6964. };
  6965. alternateBands[pos].render();
  6966. alternateBands[pos].isActive = true;
  6967. }
  6968. });
  6969. }
  6970. // custom plot lines and bands
  6971. if (!axis._addedPlotLB) { // only first time
  6972. each((options.plotLines || []).concat(options.plotBands || []), function (plotLineOptions) {
  6973. axis.addPlotBandOrLine(plotLineOptions);
  6974. });
  6975. axis._addedPlotLB = true;
  6976. }
  6977. } // end if hasData
  6978. // Remove inactive ticks
  6979. each([ticks, minorTicks, alternateBands], function (coll) {
  6980. var pos,
  6981. i,
  6982. forDestruction = [],
  6983. delay = globalAnimation ? globalAnimation.duration || 500 : 0,
  6984. destroyInactiveItems = function () {
  6985. i = forDestruction.length;
  6986. while (i--) {
  6987. // When resizing rapidly, the same items may be destroyed in different timeouts,
  6988. // or the may be reactivated
  6989. if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) {
  6990. coll[forDestruction[i]].destroy();
  6991. delete coll[forDestruction[i]];
  6992. }
  6993. }
  6994. };
  6995. for (pos in coll) {
  6996. if (!coll[pos].isActive) {
  6997. // Render to zero opacity
  6998. coll[pos].render(pos, false, 0);
  6999. coll[pos].isActive = false;
  7000. forDestruction.push(pos);
  7001. }
  7002. }
  7003. // When the objects are finished fading out, destroy them
  7004. if (coll === alternateBands || !chart.hasRendered || !delay) {
  7005. destroyInactiveItems();
  7006. } else if (delay) {
  7007. setTimeout(destroyInactiveItems, delay);
  7008. }
  7009. });
  7010. // Static items. As the axis group is cleared on subsequent calls
  7011. // to render, these items are added outside the group.
  7012. // axis line
  7013. if (lineWidth) {
  7014. linePath = axis.getLinePath(lineWidth);
  7015. if (!axis.axisLine) {
  7016. axis.axisLine = renderer.path(linePath)
  7017. .attr({
  7018. stroke: options.lineColor,
  7019. 'stroke-width': lineWidth,
  7020. zIndex: 7
  7021. })
  7022. .add(axis.axisGroup);
  7023. } else {
  7024. axis.axisLine.animate({ d: linePath });
  7025. }
  7026. // show or hide the line depending on options.showEmpty
  7027. axis.axisLine[showAxis ? 'show' : 'hide']();
  7028. }
  7029. if (axisTitle && showAxis) {
  7030. axisTitle[axisTitle.isNew ? 'attr' : 'animate'](
  7031. axis.getTitlePosition()
  7032. );
  7033. axisTitle.isNew = false;
  7034. }
  7035. // Stacked totals:
  7036. if (stackLabelOptions && stackLabelOptions.enabled) {
  7037. axis.renderStackTotals();
  7038. }
  7039. // End stacked totals
  7040. axis.isDirty = false;
  7041. },
  7042. /**
  7043. * Redraw the axis to reflect changes in the data or axis extremes
  7044. */
  7045. redraw: function () {
  7046. var axis = this,
  7047. chart = axis.chart,
  7048. pointer = chart.pointer;
  7049. // hide tooltip and hover states
  7050. if (pointer) {
  7051. pointer.reset(true);
  7052. }
  7053. // render the axis
  7054. axis.render();
  7055. // move plot lines and bands
  7056. each(axis.plotLinesAndBands, function (plotLine) {
  7057. plotLine.render();
  7058. });
  7059. // mark associated series as dirty and ready for redraw
  7060. each(axis.series, function (series) {
  7061. series.isDirty = true;
  7062. });
  7063. },
  7064. /**
  7065. * Destroys an Axis instance.
  7066. */
  7067. destroy: function (keepEvents) {
  7068. var axis = this,
  7069. stacks = axis.stacks,
  7070. stackKey,
  7071. plotLinesAndBands = axis.plotLinesAndBands,
  7072. i;
  7073. // Remove the events
  7074. if (!keepEvents) {
  7075. removeEvent(axis);
  7076. }
  7077. // Destroy each stack total
  7078. for (stackKey in stacks) {
  7079. destroyObjectProperties(stacks[stackKey]);
  7080. stacks[stackKey] = null;
  7081. }
  7082. // Destroy collections
  7083. each([axis.ticks, axis.minorTicks, axis.alternateBands], function (coll) {
  7084. destroyObjectProperties(coll);
  7085. });
  7086. i = plotLinesAndBands.length;
  7087. while (i--) { // #1975
  7088. plotLinesAndBands[i].destroy();
  7089. }
  7090. // Destroy local variables
  7091. each(['stackTotalGroup', 'axisLine', 'axisTitle', 'axisGroup', 'cross', 'gridGroup', 'labelGroup'], function (prop) {
  7092. if (axis[prop]) {
  7093. axis[prop] = axis[prop].destroy();
  7094. }
  7095. });
  7096. // Destroy crosshair
  7097. if (this.cross) {
  7098. this.cross.destroy();
  7099. }
  7100. },
  7101. /**
  7102. * Draw the crosshair
  7103. */
  7104. drawCrosshair: function (e, point) {
  7105. if (!this.crosshair) { return; }// Do not draw crosshairs if you don't have too.
  7106. if ((defined(point) || !pick(this.crosshair.snap, true)) === false) {
  7107. this.hideCrosshair();
  7108. return;
  7109. }
  7110. var path,
  7111. options = this.crosshair,
  7112. animation = options.animation,
  7113. pos;
  7114. // Get the path
  7115. if (!pick(options.snap, true)) {
  7116. pos = (this.horiz ? e.chartX - this.pos : this.len - e.chartY + this.pos);
  7117. } else if (defined(point)) {
  7118. /*jslint eqeq: true*/
  7119. pos = (this.chart.inverted != this.horiz) ? point.plotX : this.len - point.plotY;
  7120. /*jslint eqeq: false*/
  7121. }
  7122. if (this.isRadial) {
  7123. path = this.getPlotLinePath(this.isXAxis ? point.x : pick(point.stackY, point.y));
  7124. } else {
  7125. path = this.getPlotLinePath(null, null, null, null, pos);
  7126. }
  7127. if (path === null) {
  7128. this.hideCrosshair();
  7129. return;
  7130. }
  7131. // Draw the cross
  7132. if (this.cross) {
  7133. this.cross
  7134. .attr({ visibility: VISIBLE })[animation ? 'animate' : 'attr']({ d: path }, animation);
  7135. } else {
  7136. var attribs = {
  7137. 'stroke-width': options.width || 1,
  7138. stroke: options.color || '#C0C0C0',
  7139. zIndex: options.zIndex || 2
  7140. };
  7141. if (options.dashStyle) {
  7142. attribs.dashstyle = options.dashStyle;
  7143. }
  7144. this.cross = this.chart.renderer.path(path).attr(attribs).add();
  7145. }
  7146. },
  7147. /**
  7148. * Hide the crosshair.
  7149. */
  7150. hideCrosshair: function () {
  7151. if (this.cross) {
  7152. this.cross.hide();
  7153. }
  7154. }
  7155. }; // end Axis
  7156. extend(Axis.prototype, AxisPlotLineOrBandExtension);
  7157. /**
  7158. * Set the tick positions to a time unit that makes sense, for example
  7159. * on the first of each month or on every Monday. Return an array
  7160. * with the time positions. Used in datetime axes as well as for grouping
  7161. * data on a datetime axis.
  7162. *
  7163. * @param {Object} normalizedInterval The interval in axis values (ms) and the count
  7164. * @param {Number} min The minimum in axis values
  7165. * @param {Number} max The maximum in axis values
  7166. * @param {Number} startOfWeek
  7167. */
  7168. Axis.prototype.getTimeTicks = function (normalizedInterval, min, max, startOfWeek) {
  7169. var tickPositions = [],
  7170. i,
  7171. higherRanks = {},
  7172. useUTC = defaultOptions.global.useUTC,
  7173. minYear, // used in months and years as a basis for Date.UTC()
  7174. minDate = new Date(min - timezoneOffset),
  7175. interval = normalizedInterval.unitRange,
  7176. count = normalizedInterval.count;
  7177. if (defined(min)) { // #1300
  7178. if (interval >= timeUnits[SECOND]) { // second
  7179. minDate.setMilliseconds(0);
  7180. minDate.setSeconds(interval >= timeUnits[MINUTE] ? 0 :
  7181. count * mathFloor(minDate.getSeconds() / count));
  7182. }
  7183. if (interval >= timeUnits[MINUTE]) { // minute
  7184. minDate[setMinutes](interval >= timeUnits[HOUR] ? 0 :
  7185. count * mathFloor(minDate[getMinutes]() / count));
  7186. }
  7187. if (interval >= timeUnits[HOUR]) { // hour
  7188. minDate[setHours](interval >= timeUnits[DAY] ? 0 :
  7189. count * mathFloor(minDate[getHours]() / count));
  7190. }
  7191. if (interval >= timeUnits[DAY]) { // day
  7192. minDate[setDate](interval >= timeUnits[MONTH] ? 1 :
  7193. count * mathFloor(minDate[getDate]() / count));
  7194. }
  7195. if (interval >= timeUnits[MONTH]) { // month
  7196. minDate[setMonth](interval >= timeUnits[YEAR] ? 0 :
  7197. count * mathFloor(minDate[getMonth]() / count));
  7198. minYear = minDate[getFullYear]();
  7199. }
  7200. if (interval >= timeUnits[YEAR]) { // year
  7201. minYear -= minYear % count;
  7202. minDate[setFullYear](minYear);
  7203. }
  7204. // week is a special case that runs outside the hierarchy
  7205. if (interval === timeUnits[WEEK]) {
  7206. // get start of current week, independent of count
  7207. minDate[setDate](minDate[getDate]() - minDate[getDay]() +
  7208. pick(startOfWeek, 1));
  7209. }
  7210. // get tick positions
  7211. i = 1;
  7212. if (timezoneOffset) {
  7213. minDate = new Date(minDate.getTime() + timezoneOffset);
  7214. }
  7215. minYear = minDate[getFullYear]();
  7216. var time = minDate.getTime(),
  7217. minMonth = minDate[getMonth](),
  7218. minDateDate = minDate[getDate](),
  7219. localTimezoneOffset = useUTC ?
  7220. timezoneOffset :
  7221. (24 * 3600 * 1000 + minDate.getTimezoneOffset() * 60 * 1000) % (24 * 3600 * 1000); // #950
  7222. // iterate and add tick positions at appropriate values
  7223. while (time < max) {
  7224. tickPositions.push(time);
  7225. // if the interval is years, use Date.UTC to increase years
  7226. if (interval === timeUnits[YEAR]) {
  7227. time = makeTime(minYear + i * count, 0);
  7228. // if the interval is months, use Date.UTC to increase months
  7229. } else if (interval === timeUnits[MONTH]) {
  7230. time = makeTime(minYear, minMonth + i * count);
  7231. // if we're using global time, the interval is not fixed as it jumps
  7232. // one hour at the DST crossover
  7233. } else if (!useUTC && (interval === timeUnits[DAY] || interval === timeUnits[WEEK])) {
  7234. time = makeTime(minYear, minMonth, minDateDate +
  7235. i * count * (interval === timeUnits[DAY] ? 1 : 7));
  7236. // else, the interval is fixed and we use simple addition
  7237. } else {
  7238. time += interval * count;
  7239. }
  7240. i++;
  7241. }
  7242. // push the last time
  7243. tickPositions.push(time);
  7244. // mark new days if the time is dividible by day (#1649, #1760)
  7245. each(grep(tickPositions, function (time) {
  7246. return interval <= timeUnits[HOUR] && time % timeUnits[DAY] === localTimezoneOffset;
  7247. }), function (time) {
  7248. higherRanks[time] = DAY;
  7249. });
  7250. }
  7251. // record information on the chosen unit - for dynamic label formatter
  7252. tickPositions.info = extend(normalizedInterval, {
  7253. higherRanks: higherRanks,
  7254. totalRange: interval * count
  7255. });
  7256. return tickPositions;
  7257. };
  7258. /**
  7259. * Get a normalized tick interval for dates. Returns a configuration object with
  7260. * unit range (interval), count and name. Used to prepare data for getTimeTicks.
  7261. * Previously this logic was part of getTimeTicks, but as getTimeTicks now runs
  7262. * of segments in stock charts, the normalizing logic was extracted in order to
  7263. * prevent it for running over again for each segment having the same interval.
  7264. * #662, #697.
  7265. */
  7266. Axis.prototype.normalizeTimeTickInterval = function (tickInterval, unitsOption) {
  7267. var units = unitsOption || [[
  7268. MILLISECOND, // unit name
  7269. [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples
  7270. ], [
  7271. SECOND,
  7272. [1, 2, 5, 10, 15, 30]
  7273. ], [
  7274. MINUTE,
  7275. [1, 2, 5, 10, 15, 30]
  7276. ], [
  7277. HOUR,
  7278. [1, 2, 3, 4, 6, 8, 12]
  7279. ], [
  7280. DAY,
  7281. [1, 2]
  7282. ], [
  7283. WEEK,
  7284. [1, 2]
  7285. ], [
  7286. MONTH,
  7287. [1, 2, 3, 4, 6]
  7288. ], [
  7289. YEAR,
  7290. null
  7291. ]],
  7292. unit = units[units.length - 1], // default unit is years
  7293. interval = timeUnits[unit[0]],
  7294. multiples = unit[1],
  7295. count,
  7296. i;
  7297. // loop through the units to find the one that best fits the tickInterval
  7298. for (i = 0; i < units.length; i++) {
  7299. unit = units[i];
  7300. interval = timeUnits[unit[0]];
  7301. multiples = unit[1];
  7302. if (units[i + 1]) {
  7303. // lessThan is in the middle between the highest multiple and the next unit.
  7304. var lessThan = (interval * multiples[multiples.length - 1] +
  7305. timeUnits[units[i + 1][0]]) / 2;
  7306. // break and keep the current unit
  7307. if (tickInterval <= lessThan) {
  7308. break;
  7309. }
  7310. }
  7311. }
  7312. // prevent 2.5 years intervals, though 25, 250 etc. are allowed
  7313. if (interval === timeUnits[YEAR] && tickInterval < 5 * interval) {
  7314. multiples = [1, 2, 5];
  7315. }
  7316. // get the count
  7317. count = normalizeTickInterval(
  7318. tickInterval / interval,
  7319. multiples,
  7320. unit[0] === YEAR ? mathMax(getMagnitude(tickInterval / interval), 1) : 1 // #1913, #2360
  7321. );
  7322. return {
  7323. unitRange: interval,
  7324. count: count,
  7325. unitName: unit[0]
  7326. };
  7327. };/**
  7328. * Methods defined on the Axis prototype
  7329. */
  7330. /**
  7331. * Set the tick positions of a logarithmic axis
  7332. */
  7333. Axis.prototype.getLogTickPositions = function (interval, min, max, minor) {
  7334. var axis = this,
  7335. options = axis.options,
  7336. axisLength = axis.len,
  7337. // Since we use this method for both major and minor ticks,
  7338. // use a local variable and return the result
  7339. positions = [];
  7340. // Reset
  7341. if (!minor) {
  7342. axis._minorAutoInterval = null;
  7343. }
  7344. // First case: All ticks fall on whole logarithms: 1, 10, 100 etc.
  7345. if (interval >= 0.5) {
  7346. interval = mathRound(interval);
  7347. positions = axis.getLinearTickPositions(interval, min, max);
  7348. // Second case: We need intermediary ticks. For example
  7349. // 1, 2, 4, 6, 8, 10, 20, 40 etc.
  7350. } else if (interval >= 0.08) {
  7351. var roundedMin = mathFloor(min),
  7352. intermediate,
  7353. i,
  7354. j,
  7355. len,
  7356. pos,
  7357. lastPos,
  7358. break2;
  7359. if (interval > 0.3) {
  7360. intermediate = [1, 2, 4];
  7361. } else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc
  7362. intermediate = [1, 2, 4, 6, 8];
  7363. } else { // 0.1 equals ten minor ticks per 1, 10, 100 etc
  7364. intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  7365. }
  7366. for (i = roundedMin; i < max + 1 && !break2; i++) {
  7367. len = intermediate.length;
  7368. for (j = 0; j < len && !break2; j++) {
  7369. pos = log2lin(lin2log(i) * intermediate[j]);
  7370. if (pos > min && (!minor || lastPos <= max)) { // #1670
  7371. positions.push(lastPos);
  7372. }
  7373. if (lastPos > max) {
  7374. break2 = true;
  7375. }
  7376. lastPos = pos;
  7377. }
  7378. }
  7379. // Third case: We are so deep in between whole logarithmic values that
  7380. // we might as well handle the tick positions like a linear axis. For
  7381. // example 1.01, 1.02, 1.03, 1.04.
  7382. } else {
  7383. var realMin = lin2log(min),
  7384. realMax = lin2log(max),
  7385. tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'],
  7386. filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption,
  7387. tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1),
  7388. totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength;
  7389. interval = pick(
  7390. filteredTickIntervalOption,
  7391. axis._minorAutoInterval,
  7392. (realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1)
  7393. );
  7394. interval = normalizeTickInterval(
  7395. interval,
  7396. null,
  7397. getMagnitude(interval)
  7398. );
  7399. positions = map(axis.getLinearTickPositions(
  7400. interval,
  7401. realMin,
  7402. realMax
  7403. ), log2lin);
  7404. if (!minor) {
  7405. axis._minorAutoInterval = interval / 5;
  7406. }
  7407. }
  7408. // Set the axis-level tickInterval variable
  7409. if (!minor) {
  7410. axis.tickInterval = interval;
  7411. }
  7412. return positions;
  7413. };/**
  7414. * The tooltip object
  7415. * @param {Object} chart The chart instance
  7416. * @param {Object} options Tooltip options
  7417. */
  7418. var Tooltip = Highcharts.Tooltip = function () {
  7419. this.init.apply(this, arguments);
  7420. };
  7421. Tooltip.prototype = {
  7422. init: function (chart, options) {
  7423. var borderWidth = options.borderWidth,
  7424. style = options.style,
  7425. padding = pInt(style.padding);
  7426. // Save the chart and options
  7427. this.chart = chart;
  7428. this.options = options;
  7429. // Keep track of the current series
  7430. //this.currentSeries = UNDEFINED;
  7431. // List of crosshairs
  7432. this.crosshairs = [];
  7433. // Current values of x and y when animating
  7434. this.now = { x: 0, y: 0 };
  7435. // The tooltip is initially hidden
  7436. this.isHidden = true;
  7437. // create the label
  7438. this.label = chart.renderer.label('', 0, 0, options.shape || 'callout', null, null, options.useHTML, null, 'tooltip')
  7439. .attr({
  7440. padding: padding,
  7441. fill: options.backgroundColor,
  7442. 'stroke-width': borderWidth,
  7443. r: options.borderRadius,
  7444. zIndex: 8
  7445. })
  7446. .css(style)
  7447. .css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117)
  7448. .add()
  7449. .attr({ y: -9999 }); // #2301, #2657
  7450. // When using canVG the shadow shows up as a gray circle
  7451. // even if the tooltip is hidden.
  7452. if (!useCanVG) {
  7453. this.label.shadow(options.shadow);
  7454. }
  7455. // Public property for getting the shared state.
  7456. this.shared = options.shared;
  7457. },
  7458. /**
  7459. * Destroy the tooltip and its elements.
  7460. */
  7461. destroy: function () {
  7462. // Destroy and clear local variables
  7463. if (this.label) {
  7464. this.label = this.label.destroy();
  7465. }
  7466. clearTimeout(this.hideTimer);
  7467. clearTimeout(this.tooltipTimeout);
  7468. },
  7469. /**
  7470. * Provide a soft movement for the tooltip
  7471. *
  7472. * @param {Number} x
  7473. * @param {Number} y
  7474. * @private
  7475. */
  7476. move: function (x, y, anchorX, anchorY) {
  7477. var tooltip = this,
  7478. now = tooltip.now,
  7479. animate = tooltip.options.animation !== false && !tooltip.isHidden,
  7480. skipAnchor = tooltip.followPointer || tooltip.len > 1;
  7481. // get intermediate values for animation
  7482. extend(now, {
  7483. x: animate ? (2 * now.x + x) / 3 : x,
  7484. y: animate ? (now.y + y) / 2 : y,
  7485. anchorX: skipAnchor ? UNDEFINED : animate ? (2 * now.anchorX + anchorX) / 3 : anchorX,
  7486. anchorY: skipAnchor ? UNDEFINED : animate ? (now.anchorY + anchorY) / 2 : anchorY
  7487. });
  7488. // move to the intermediate value
  7489. tooltip.label.attr(now);
  7490. // run on next tick of the mouse tracker
  7491. if (animate && (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1)) {
  7492. // never allow two timeouts
  7493. clearTimeout(this.tooltipTimeout);
  7494. // set the fixed interval ticking for the smooth tooltip
  7495. this.tooltipTimeout = setTimeout(function () {
  7496. // The interval function may still be running during destroy, so check that the chart is really there before calling.
  7497. if (tooltip) {
  7498. tooltip.move(x, y, anchorX, anchorY);
  7499. }
  7500. }, 32);
  7501. }
  7502. },
  7503. /**
  7504. * Hide the tooltip
  7505. */
  7506. hide: function () {
  7507. var tooltip = this,
  7508. hoverPoints;
  7509. clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766)
  7510. if (!this.isHidden) {
  7511. hoverPoints = this.chart.hoverPoints;
  7512. this.hideTimer = setTimeout(function () {
  7513. tooltip.label.fadeOut();
  7514. tooltip.isHidden = true;
  7515. }, pick(this.options.hideDelay, 500));
  7516. // hide previous hoverPoints and set new
  7517. if (hoverPoints) {
  7518. each(hoverPoints, function (point) {
  7519. point.setState();
  7520. });
  7521. }
  7522. this.chart.hoverPoints = null;
  7523. }
  7524. },
  7525. /**
  7526. * Extendable method to get the anchor position of the tooltip
  7527. * from a point or set of points
  7528. */
  7529. getAnchor: function (points, mouseEvent) {
  7530. var ret,
  7531. chart = this.chart,
  7532. inverted = chart.inverted,
  7533. plotTop = chart.plotTop,
  7534. plotX = 0,
  7535. plotY = 0,
  7536. yAxis;
  7537. points = splat(points);
  7538. // Pie uses a special tooltipPos
  7539. ret = points[0].tooltipPos;
  7540. // When tooltip follows mouse, relate the position to the mouse
  7541. if (this.followPointer && mouseEvent) {
  7542. if (mouseEvent.chartX === UNDEFINED) {
  7543. mouseEvent = chart.pointer.normalize(mouseEvent);
  7544. }
  7545. ret = [
  7546. mouseEvent.chartX - chart.plotLeft,
  7547. mouseEvent.chartY - plotTop
  7548. ];
  7549. }
  7550. // When shared, use the average position
  7551. if (!ret) {
  7552. each(points, function (point) {
  7553. yAxis = point.series.yAxis;
  7554. plotX += point.plotX;
  7555. plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) +
  7556. (!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151
  7557. });
  7558. plotX /= points.length;
  7559. plotY /= points.length;
  7560. ret = [
  7561. inverted ? chart.plotWidth - plotY : plotX,
  7562. this.shared && !inverted && points.length > 1 && mouseEvent ?
  7563. mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424)
  7564. inverted ? chart.plotHeight - plotX : plotY
  7565. ];
  7566. }
  7567. return map(ret, mathRound);
  7568. },
  7569. /**
  7570. * Place the tooltip in a chart without spilling over
  7571. * and not covering the point it self.
  7572. */
  7573. getPosition: function (boxWidth, boxHeight, point) {
  7574. var chart = this.chart,
  7575. distance = this.distance,
  7576. ret = {},
  7577. swapped,
  7578. first = ['y', chart.chartHeight, boxHeight, point.plotY + chart.plotTop],
  7579. second = ['x', chart.chartWidth, boxWidth, point.plotX + chart.plotLeft],
  7580. // The far side is right or bottom
  7581. preferFarSide = point.ttBelow || (chart.inverted && !point.negative) || (!chart.inverted && point.negative),
  7582. /**
  7583. * Handle the preferred dimension. When the preferred dimension is tooltip
  7584. * on top or bottom of the point, it will look for space there.
  7585. */
  7586. firstDimension = function (dim, outerSize, innerSize, point) {
  7587. var roomLeft = innerSize < point - distance,
  7588. roomRight = point + distance + innerSize < outerSize,
  7589. alignedLeft = point - distance - innerSize,
  7590. alignedRight = point + distance;
  7591. if (preferFarSide && roomRight) {
  7592. ret[dim] = alignedRight;
  7593. } else if (!preferFarSide && roomLeft) {
  7594. ret[dim] = alignedLeft;
  7595. } else if (roomLeft) {
  7596. ret[dim] = alignedLeft;
  7597. } else if (roomRight) {
  7598. ret[dim] = alignedRight;
  7599. } else {
  7600. return false;
  7601. }
  7602. },
  7603. /**
  7604. * Handle the secondary dimension. If the preferred dimension is tooltip
  7605. * on top or bottom of the point, the second dimension is to align the tooltip
  7606. * above the point, trying to align center but allowing left or right
  7607. * align within the chart box.
  7608. */
  7609. secondDimension = function (dim, outerSize, innerSize, point) {
  7610. // Too close to the edge, return false and swap dimensions
  7611. if (point < distance || point > outerSize - distance) {
  7612. return false;
  7613. // Align left/top
  7614. } else if (point < innerSize / 2) {
  7615. ret[dim] = 1;
  7616. // Align right/bottom
  7617. } else if (point > outerSize - innerSize / 2) {
  7618. ret[dim] = outerSize - innerSize - 2;
  7619. // Align center
  7620. } else {
  7621. ret[dim] = point - innerSize / 2;
  7622. }
  7623. },
  7624. /**
  7625. * Swap the dimensions
  7626. */
  7627. swap = function (count) {
  7628. var temp = first;
  7629. first = second;
  7630. second = temp;
  7631. swapped = count;
  7632. },
  7633. run = function () {
  7634. if (firstDimension.apply(0, first) !== false) {
  7635. if (secondDimension.apply(0, second) === false && !swapped) {
  7636. swap(true);
  7637. run();
  7638. }
  7639. } else if (!swapped) {
  7640. swap(true);
  7641. run();
  7642. } else {
  7643. ret.x = ret.y = 0;
  7644. }
  7645. };
  7646. // Under these conditions, prefer the tooltip on the side of the point
  7647. if (chart.inverted || this.len > 1) {
  7648. swap();
  7649. }
  7650. run();
  7651. return ret;
  7652. },
  7653. /**
  7654. * In case no user defined formatter is given, this will be used. Note that the context
  7655. * here is an object holding point, series, x, y etc.
  7656. */
  7657. defaultFormatter: function (tooltip) {
  7658. var items = this.points || splat(this),
  7659. series = items[0].series,
  7660. s;
  7661. // build the header
  7662. s = [tooltip.tooltipHeaderFormatter(items[0])];
  7663. // build the values
  7664. each(items, function (item) {
  7665. series = item.series;
  7666. s.push((series.tooltipFormatter && series.tooltipFormatter(item)) ||
  7667. item.point.tooltipFormatter(series.tooltipOptions.pointFormat));
  7668. });
  7669. // footer
  7670. s.push(tooltip.options.footerFormat || '');
  7671. return s.join('');
  7672. },
  7673. /**
  7674. * Refresh the tooltip's text and position.
  7675. * @param {Object} point
  7676. */
  7677. refresh: function (point, mouseEvent) {
  7678. var tooltip = this,
  7679. chart = tooltip.chart,
  7680. label = tooltip.label,
  7681. options = tooltip.options,
  7682. x,
  7683. y,
  7684. anchor,
  7685. textConfig = {},
  7686. text,
  7687. pointConfig = [],
  7688. formatter = options.formatter || tooltip.defaultFormatter,
  7689. hoverPoints = chart.hoverPoints,
  7690. borderColor,
  7691. shared = tooltip.shared,
  7692. currentSeries;
  7693. clearTimeout(this.hideTimer);
  7694. // get the reference point coordinates (pie charts use tooltipPos)
  7695. tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer;
  7696. anchor = tooltip.getAnchor(point, mouseEvent);
  7697. x = anchor[0];
  7698. y = anchor[1];
  7699. // shared tooltip, array is sent over
  7700. if (shared && !(point.series && point.series.noSharedTooltip)) {
  7701. // hide previous hoverPoints and set new
  7702. chart.hoverPoints = point;
  7703. if (hoverPoints) {
  7704. each(hoverPoints, function (point) {
  7705. point.setState();
  7706. });
  7707. }
  7708. each(point, function (item) {
  7709. item.setState(HOVER_STATE);
  7710. pointConfig.push(item.getLabelConfig());
  7711. });
  7712. textConfig = {
  7713. x: point[0].category,
  7714. y: point[0].y
  7715. };
  7716. textConfig.points = pointConfig;
  7717. this.len = pointConfig.length;
  7718. point = point[0];
  7719. // single point tooltip
  7720. } else {
  7721. textConfig = point.getLabelConfig();
  7722. }
  7723. text = formatter.call(textConfig, tooltip);
  7724. // register the current series
  7725. currentSeries = point.series;
  7726. this.distance = pick(currentSeries.tooltipOptions.distance, 16);
  7727. // update the inner HTML
  7728. if (text === false) {
  7729. this.hide();
  7730. } else {
  7731. // show it
  7732. if (tooltip.isHidden) {
  7733. stop(label);
  7734. label.attr('opacity', 1).show();
  7735. }
  7736. // update text
  7737. label.attr({
  7738. text: text
  7739. });
  7740. // set the stroke color of the box
  7741. borderColor = options.borderColor || point.color || currentSeries.color || '#606060';
  7742. label.attr({
  7743. stroke: borderColor
  7744. });
  7745. tooltip.updatePosition({ plotX: x, plotY: y, negative: point.negative, ttBelow: point.ttBelow });
  7746. this.isHidden = false;
  7747. }
  7748. fireEvent(chart, 'tooltipRefresh', {
  7749. text: text,
  7750. x: x + chart.plotLeft,
  7751. y: y + chart.plotTop,
  7752. borderColor: borderColor
  7753. });
  7754. },
  7755. /**
  7756. * Find the new position and perform the move
  7757. */
  7758. updatePosition: function (point) {
  7759. var chart = this.chart,
  7760. label = this.label,
  7761. pos = (this.options.positioner || this.getPosition).call(
  7762. this,
  7763. label.width,
  7764. label.height,
  7765. point
  7766. );
  7767. // do the move
  7768. this.move(
  7769. mathRound(pos.x),
  7770. mathRound(pos.y),
  7771. point.plotX + chart.plotLeft,
  7772. point.plotY + chart.plotTop
  7773. );
  7774. },
  7775. /**
  7776. * Format the header of the tooltip
  7777. */
  7778. tooltipHeaderFormatter: function (point) {
  7779. var series = point.series,
  7780. tooltipOptions = series.tooltipOptions,
  7781. dateTimeLabelFormats = tooltipOptions.dateTimeLabelFormats,
  7782. xDateFormat = tooltipOptions.xDateFormat,
  7783. xAxis = series.xAxis,
  7784. isDateTime = xAxis && xAxis.options.type === 'datetime' && isNumber(point.key),
  7785. headerFormat = tooltipOptions.headerFormat,
  7786. closestPointRange = xAxis && xAxis.closestPointRange,
  7787. n;
  7788. // Guess the best date format based on the closest point distance (#568)
  7789. if (isDateTime && !xDateFormat) {
  7790. if (closestPointRange) {
  7791. for (n in timeUnits) {
  7792. if (timeUnits[n] >= closestPointRange ||
  7793. // If the point is placed every day at 23:59, we need to show
  7794. // the minutes as well. This logic only works for time units less than
  7795. // a day, since all higher time units are dividable by those. #2637.
  7796. (timeUnits[n] <= timeUnits[DAY] && point.key % timeUnits[n] > 0)) {
  7797. xDateFormat = dateTimeLabelFormats[n];
  7798. break;
  7799. }
  7800. }
  7801. } else {
  7802. xDateFormat = dateTimeLabelFormats.day;
  7803. }
  7804. xDateFormat = xDateFormat || dateTimeLabelFormats.year; // #2546, 2581
  7805. }
  7806. // Insert the header date format if any
  7807. if (isDateTime && xDateFormat) {
  7808. headerFormat = headerFormat.replace('{point.key}', '{point.key:' + xDateFormat + '}');
  7809. }
  7810. return format(headerFormat, {
  7811. point: point,
  7812. series: series
  7813. });
  7814. }
  7815. };
  7816. var hoverChartIndex;
  7817. // Global flag for touch support
  7818. hasTouch = doc.documentElement.ontouchstart !== UNDEFINED;
  7819. /**
  7820. * The mouse tracker object. All methods starting with "on" are primary DOM event handlers.
  7821. * Subsequent methods should be named differently from what they are doing.
  7822. * @param {Object} chart The Chart instance
  7823. * @param {Object} options The root options object
  7824. */
  7825. var Pointer = Highcharts.Pointer = function (chart, options) {
  7826. this.init(chart, options);
  7827. };
  7828. Pointer.prototype = {
  7829. /**
  7830. * Initialize Pointer
  7831. */
  7832. init: function (chart, options) {
  7833. var chartOptions = options.chart,
  7834. chartEvents = chartOptions.events,
  7835. zoomType = useCanVG ? '' : chartOptions.zoomType,
  7836. inverted = chart.inverted,
  7837. zoomX,
  7838. zoomY;
  7839. // Store references
  7840. this.options = options;
  7841. this.chart = chart;
  7842. // Zoom status
  7843. this.zoomX = zoomX = /x/.test(zoomType);
  7844. this.zoomY = zoomY = /y/.test(zoomType);
  7845. this.zoomHor = (zoomX && !inverted) || (zoomY && inverted);
  7846. this.zoomVert = (zoomY && !inverted) || (zoomX && inverted);
  7847. this.hasZoom = zoomX || zoomY;
  7848. // Do we need to handle click on a touch device?
  7849. this.runChartClick = chartEvents && !!chartEvents.click;
  7850. this.pinchDown = [];
  7851. this.lastValidTouch = {};
  7852. if (Highcharts.Tooltip && options.tooltip.enabled) {
  7853. chart.tooltip = new Tooltip(chart, options.tooltip);
  7854. this.followTouchMove = options.tooltip.followTouchMove;
  7855. }
  7856. this.setDOMEvents();
  7857. },
  7858. /**
  7859. * Add crossbrowser support for chartX and chartY
  7860. * @param {Object} e The event object in standard browsers
  7861. */
  7862. normalize: function (e, chartPosition) {
  7863. var chartX,
  7864. chartY,
  7865. ePos;
  7866. // common IE normalizing
  7867. e = e || window.event;
  7868. // Framework specific normalizing (#1165)
  7869. e = washMouseEvent(e);
  7870. // More IE normalizing, needs to go after washMouseEvent
  7871. if (!e.target) {
  7872. e.target = e.srcElement;
  7873. }
  7874. // iOS (#2757)
  7875. ePos = e.touches ? (e.touches.length ? e.touches.item(0) : e.changedTouches[0]) : e;
  7876. // Get mouse position
  7877. if (!chartPosition) {
  7878. this.chartPosition = chartPosition = offset(this.chart.container);
  7879. }
  7880. // chartX and chartY
  7881. if (ePos.pageX === UNDEFINED) { // IE < 9. #886.
  7882. chartX = mathMax(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is
  7883. // for IE10 quirks mode within framesets
  7884. chartY = e.y;
  7885. } else {
  7886. chartX = ePos.pageX - chartPosition.left;
  7887. chartY = ePos.pageY - chartPosition.top;
  7888. }
  7889. return extend(e, {
  7890. chartX: mathRound(chartX),
  7891. chartY: mathRound(chartY)
  7892. });
  7893. },
  7894. /**
  7895. * Get the click position in terms of axis values.
  7896. *
  7897. * @param {Object} e A pointer event
  7898. */
  7899. getCoordinates: function (e) {
  7900. var coordinates = {
  7901. xAxis: [],
  7902. yAxis: []
  7903. };
  7904. each(this.chart.axes, function (axis) {
  7905. coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({
  7906. axis: axis,
  7907. value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY'])
  7908. });
  7909. });
  7910. return coordinates;
  7911. },
  7912. /**
  7913. * Return the index in the tooltipPoints array, corresponding to pixel position in
  7914. * the plot area.
  7915. */
  7916. getIndex: function (e) {
  7917. var chart = this.chart;
  7918. return chart.inverted ?
  7919. chart.plotHeight + chart.plotTop - e.chartY :
  7920. e.chartX - chart.plotLeft;
  7921. },
  7922. /**
  7923. * With line type charts with a single tracker, get the point closest to the mouse.
  7924. * Run Point.onMouseOver and display tooltip for the point or points.
  7925. */
  7926. runPointActions: function (e) {
  7927. var pointer = this,
  7928. chart = pointer.chart,
  7929. series = chart.series,
  7930. tooltip = chart.tooltip,
  7931. followPointer,
  7932. point,
  7933. points,
  7934. hoverPoint = chart.hoverPoint,
  7935. hoverSeries = chart.hoverSeries,
  7936. i,
  7937. j,
  7938. distance = chart.chartWidth,
  7939. index = pointer.getIndex(e),
  7940. anchor;
  7941. // shared tooltip
  7942. if (tooltip && pointer.options.tooltip.shared && !(hoverSeries && hoverSeries.noSharedTooltip)) {
  7943. points = [];
  7944. // loop over all series and find the ones with points closest to the mouse
  7945. i = series.length;
  7946. for (j = 0; j < i; j++) {
  7947. if (series[j].visible &&
  7948. series[j].options.enableMouseTracking !== false &&
  7949. !series[j].noSharedTooltip && series[j].singularTooltips !== true && series[j].tooltipPoints.length) {
  7950. point = series[j].tooltipPoints[index];
  7951. if (point && point.series) { // not a dummy point, #1544
  7952. point._dist = mathAbs(index - point.clientX);
  7953. distance = mathMin(distance, point._dist);
  7954. points.push(point);
  7955. }
  7956. }
  7957. }
  7958. // remove furthest points
  7959. i = points.length;
  7960. while (i--) {
  7961. if (points[i]._dist > distance) {
  7962. points.splice(i, 1);
  7963. }
  7964. }
  7965. // refresh the tooltip if necessary
  7966. if (points.length && (points[0].clientX !== pointer.hoverX)) {
  7967. tooltip.refresh(points, e);
  7968. pointer.hoverX = points[0].clientX;
  7969. }
  7970. }
  7971. // Separate tooltip and general mouse events
  7972. followPointer = hoverSeries && hoverSeries.tooltipOptions.followPointer;
  7973. if (hoverSeries && hoverSeries.tracker && !followPointer) { // #2584, #2830
  7974. // get the point
  7975. point = hoverSeries.tooltipPoints[index];
  7976. // a new point is hovered, refresh the tooltip
  7977. if (point && point !== hoverPoint) {
  7978. // trigger the events
  7979. point.onMouseOver(e);
  7980. }
  7981. } else if (tooltip && followPointer && !tooltip.isHidden) {
  7982. anchor = tooltip.getAnchor([{}], e);
  7983. tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] });
  7984. }
  7985. // Start the event listener to pick up the tooltip
  7986. if (tooltip && !pointer._onDocumentMouseMove) {
  7987. pointer._onDocumentMouseMove = function (e) {
  7988. if (charts[hoverChartIndex]) {
  7989. charts[hoverChartIndex].pointer.onDocumentMouseMove(e);
  7990. }
  7991. };
  7992. addEvent(doc, 'mousemove', pointer._onDocumentMouseMove);
  7993. }
  7994. // Draw independent crosshairs
  7995. each(chart.axes, function (axis) {
  7996. axis.drawCrosshair(e, pick(point, hoverPoint));
  7997. });
  7998. },
  7999. /**
  8000. * Reset the tracking by hiding the tooltip, the hover series state and the hover point
  8001. *
  8002. * @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible
  8003. */
  8004. reset: function (allowMove) {
  8005. var pointer = this,
  8006. chart = pointer.chart,
  8007. hoverSeries = chart.hoverSeries,
  8008. hoverPoint = chart.hoverPoint,
  8009. tooltip = chart.tooltip,
  8010. tooltipPoints = tooltip && tooltip.shared ? chart.hoverPoints : hoverPoint;
  8011. // Narrow in allowMove
  8012. allowMove = allowMove && tooltip && tooltipPoints;
  8013. // Check if the points have moved outside the plot area, #1003
  8014. if (allowMove && splat(tooltipPoints)[0].plotX === UNDEFINED) {
  8015. allowMove = false;
  8016. }
  8017. // Just move the tooltip, #349
  8018. if (allowMove) {
  8019. tooltip.refresh(tooltipPoints);
  8020. if (hoverPoint) { // #2500
  8021. hoverPoint.setState(hoverPoint.state, true);
  8022. }
  8023. // Full reset
  8024. } else {
  8025. if (hoverPoint) {
  8026. hoverPoint.onMouseOut();
  8027. }
  8028. if (hoverSeries) {
  8029. hoverSeries.onMouseOut();
  8030. }
  8031. if (tooltip) {
  8032. tooltip.hide();
  8033. }
  8034. if (pointer._onDocumentMouseMove) {
  8035. removeEvent(doc, 'mousemove', pointer._onDocumentMouseMove);
  8036. pointer._onDocumentMouseMove = null;
  8037. }
  8038. // Remove crosshairs
  8039. each(chart.axes, function (axis) {
  8040. axis.hideCrosshair();
  8041. });
  8042. pointer.hoverX = null;
  8043. }
  8044. },
  8045. /**
  8046. * Scale series groups to a certain scale and translation
  8047. */
  8048. scaleGroups: function (attribs, clip) {
  8049. var chart = this.chart,
  8050. seriesAttribs;
  8051. // Scale each series
  8052. each(chart.series, function (series) {
  8053. seriesAttribs = attribs || series.getPlotBox(); // #1701
  8054. if (series.xAxis && series.xAxis.zoomEnabled) {
  8055. series.group.attr(seriesAttribs);
  8056. if (series.markerGroup) {
  8057. series.markerGroup.attr(seriesAttribs);
  8058. series.markerGroup.clip(clip ? chart.clipRect : null);
  8059. }
  8060. if (series.dataLabelsGroup) {
  8061. series.dataLabelsGroup.attr(seriesAttribs);
  8062. }
  8063. }
  8064. });
  8065. // Clip
  8066. chart.clipRect.attr(clip || chart.clipBox);
  8067. },
  8068. /**
  8069. * Start a drag operation
  8070. */
  8071. dragStart: function (e) {
  8072. var chart = this.chart;
  8073. // Record the start position
  8074. chart.mouseIsDown = e.type;
  8075. chart.cancelClick = false;
  8076. chart.mouseDownX = this.mouseDownX = e.chartX;
  8077. chart.mouseDownY = this.mouseDownY = e.chartY;
  8078. },
  8079. /**
  8080. * Perform a drag operation in response to a mousemove event while the mouse is down
  8081. */
  8082. drag: function (e) {
  8083. var chart = this.chart,
  8084. chartOptions = chart.options.chart,
  8085. chartX = e.chartX,
  8086. chartY = e.chartY,
  8087. zoomHor = this.zoomHor,
  8088. zoomVert = this.zoomVert,
  8089. plotLeft = chart.plotLeft,
  8090. plotTop = chart.plotTop,
  8091. plotWidth = chart.plotWidth,
  8092. plotHeight = chart.plotHeight,
  8093. clickedInside,
  8094. size,
  8095. mouseDownX = this.mouseDownX,
  8096. mouseDownY = this.mouseDownY;
  8097. // If the mouse is outside the plot area, adjust to cooordinates
  8098. // inside to prevent the selection marker from going outside
  8099. if (chartX < plotLeft) {
  8100. chartX = plotLeft;
  8101. } else if (chartX > plotLeft + plotWidth) {
  8102. chartX = plotLeft + plotWidth;
  8103. }
  8104. if (chartY < plotTop) {
  8105. chartY = plotTop;
  8106. } else if (chartY > plotTop + plotHeight) {
  8107. chartY = plotTop + plotHeight;
  8108. }
  8109. // determine if the mouse has moved more than 10px
  8110. this.hasDragged = Math.sqrt(
  8111. Math.pow(mouseDownX - chartX, 2) +
  8112. Math.pow(mouseDownY - chartY, 2)
  8113. );
  8114. if (this.hasDragged > 10) {
  8115. clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop);
  8116. // make a selection
  8117. if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside) {
  8118. if (!this.selectionMarker) {
  8119. this.selectionMarker = chart.renderer.rect(
  8120. plotLeft,
  8121. plotTop,
  8122. zoomHor ? 1 : plotWidth,
  8123. zoomVert ? 1 : plotHeight,
  8124. 0
  8125. )
  8126. .attr({
  8127. fill: chartOptions.selectionMarkerFill || 'rgba(69,114,167,0.25)',
  8128. zIndex: 7
  8129. })
  8130. .add();
  8131. }
  8132. }
  8133. // adjust the width of the selection marker
  8134. if (this.selectionMarker && zoomHor) {
  8135. size = chartX - mouseDownX;
  8136. this.selectionMarker.attr({
  8137. width: mathAbs(size),
  8138. x: (size > 0 ? 0 : size) + mouseDownX
  8139. });
  8140. }
  8141. // adjust the height of the selection marker
  8142. if (this.selectionMarker && zoomVert) {
  8143. size = chartY - mouseDownY;
  8144. this.selectionMarker.attr({
  8145. height: mathAbs(size),
  8146. y: (size > 0 ? 0 : size) + mouseDownY
  8147. });
  8148. }
  8149. // panning
  8150. if (clickedInside && !this.selectionMarker && chartOptions.panning) {
  8151. chart.pan(e, chartOptions.panning);
  8152. }
  8153. }
  8154. },
  8155. /**
  8156. * On mouse up or touch end across the entire document, drop the selection.
  8157. */
  8158. drop: function (e) {
  8159. var chart = this.chart,
  8160. hasPinched = this.hasPinched;
  8161. if (this.selectionMarker) {
  8162. var selectionData = {
  8163. xAxis: [],
  8164. yAxis: [],
  8165. originalEvent: e.originalEvent || e
  8166. },
  8167. selectionBox = this.selectionMarker,
  8168. selectionLeft = selectionBox.attr ? selectionBox.attr('x') : selectionBox.x,
  8169. selectionTop = selectionBox.attr ? selectionBox.attr('y') : selectionBox.y,
  8170. selectionWidth = selectionBox.attr ? selectionBox.attr('width') : selectionBox.width,
  8171. selectionHeight = selectionBox.attr ? selectionBox.attr('height') : selectionBox.height,
  8172. runZoom;
  8173. // a selection has been made
  8174. if (this.hasDragged || hasPinched) {
  8175. // record each axis' min and max
  8176. each(chart.axes, function (axis) {
  8177. if (axis.zoomEnabled) {
  8178. var horiz = axis.horiz,
  8179. selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop)),
  8180. selectionMax = axis.toValue((horiz ? selectionLeft + selectionWidth : selectionTop + selectionHeight));
  8181. if (!isNaN(selectionMin) && !isNaN(selectionMax)) { // #859
  8182. selectionData[axis.coll].push({
  8183. axis: axis,
  8184. min: mathMin(selectionMin, selectionMax), // for reversed axes,
  8185. max: mathMax(selectionMin, selectionMax)
  8186. });
  8187. runZoom = true;
  8188. }
  8189. }
  8190. });
  8191. if (runZoom) {
  8192. fireEvent(chart, 'selection', selectionData, function (args) {
  8193. chart.zoom(extend(args, hasPinched ? { animation: false } : null));
  8194. });
  8195. }
  8196. }
  8197. this.selectionMarker = this.selectionMarker.destroy();
  8198. // Reset scaling preview
  8199. if (hasPinched) {
  8200. this.scaleGroups();
  8201. }
  8202. }
  8203. // Reset all
  8204. if (chart) { // it may be destroyed on mouse up - #877
  8205. css(chart.container, { cursor: chart._cursor });
  8206. chart.cancelClick = this.hasDragged > 10; // #370
  8207. chart.mouseIsDown = this.hasDragged = this.hasPinched = false;
  8208. this.pinchDown = [];
  8209. }
  8210. },
  8211. onContainerMouseDown: function (e) {
  8212. e = this.normalize(e);
  8213. // issue #295, dragging not always working in Firefox
  8214. if (e.preventDefault) {
  8215. e.preventDefault();
  8216. }
  8217. this.dragStart(e);
  8218. },
  8219. onDocumentMouseUp: function (e) {
  8220. if (charts[hoverChartIndex]) {
  8221. charts[hoverChartIndex].pointer.drop(e);
  8222. }
  8223. },
  8224. /**
  8225. * Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea.
  8226. * Issue #149 workaround. The mouseleave event does not always fire.
  8227. */
  8228. onDocumentMouseMove: function (e) {
  8229. var chart = this.chart,
  8230. chartPosition = this.chartPosition,
  8231. hoverSeries = chart.hoverSeries;
  8232. e = this.normalize(e, chartPosition);
  8233. // If we're outside, hide the tooltip
  8234. if (chartPosition && hoverSeries && !this.inClass(e.target, 'highcharts-tracker') &&
  8235. !chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
  8236. this.reset();
  8237. }
  8238. },
  8239. /**
  8240. * When mouse leaves the container, hide the tooltip.
  8241. */
  8242. onContainerMouseLeave: function () {
  8243. var chart = charts[hoverChartIndex];
  8244. if (chart) {
  8245. chart.pointer.reset();
  8246. chart.pointer.chartPosition = null; // also reset the chart position, used in #149 fix
  8247. }
  8248. },
  8249. // The mousemove, touchmove and touchstart event handler
  8250. onContainerMouseMove: function (e) {
  8251. var chart = this.chart;
  8252. hoverChartIndex = chart.index;
  8253. // normalize
  8254. e = this.normalize(e);
  8255. if (chart.mouseIsDown === 'mousedown') {
  8256. this.drag(e);
  8257. }
  8258. // Show the tooltip and run mouse over events (#977)
  8259. if ((this.inClass(e.target, 'highcharts-tracker') ||
  8260. chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) {
  8261. this.runPointActions(e);
  8262. }
  8263. },
  8264. /**
  8265. * Utility to detect whether an element has, or has a parent with, a specific
  8266. * class name. Used on detection of tracker objects and on deciding whether
  8267. * hovering the tooltip should cause the active series to mouse out.
  8268. */
  8269. inClass: function (element, className) {
  8270. var elemClassName;
  8271. while (element) {
  8272. elemClassName = attr(element, 'class');
  8273. if (elemClassName) {
  8274. if (elemClassName.indexOf(className) !== -1) {
  8275. return true;
  8276. } else if (elemClassName.indexOf(PREFIX + 'container') !== -1) {
  8277. return false;
  8278. }
  8279. }
  8280. element = element.parentNode;
  8281. }
  8282. },
  8283. onTrackerMouseOut: function (e) {
  8284. var series = this.chart.hoverSeries,
  8285. relatedTarget = e.relatedTarget || e.toElement,
  8286. relatedSeries = relatedTarget && relatedTarget.point && relatedTarget.point.series; // #2499
  8287. if (series && !series.options.stickyTracking && !this.inClass(relatedTarget, PREFIX + 'tooltip') &&
  8288. relatedSeries !== series) {
  8289. series.onMouseOut();
  8290. }
  8291. },
  8292. onContainerClick: function (e) {
  8293. var chart = this.chart,
  8294. hoverPoint = chart.hoverPoint,
  8295. plotLeft = chart.plotLeft,
  8296. plotTop = chart.plotTop;
  8297. e = this.normalize(e);
  8298. e.cancelBubble = true; // IE specific
  8299. if (!chart.cancelClick) {
  8300. // On tracker click, fire the series and point events. #783, #1583
  8301. if (hoverPoint && this.inClass(e.target, PREFIX + 'tracker')) {
  8302. // the series click event
  8303. fireEvent(hoverPoint.series, 'click', extend(e, {
  8304. point: hoverPoint
  8305. }));
  8306. // the point click event
  8307. if (chart.hoverPoint) { // it may be destroyed (#1844)
  8308. hoverPoint.firePointEvent('click', e);
  8309. }
  8310. // When clicking outside a tracker, fire a chart event
  8311. } else {
  8312. extend(e, this.getCoordinates(e));
  8313. // fire a click event in the chart
  8314. if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) {
  8315. fireEvent(chart, 'click', e);
  8316. }
  8317. }
  8318. }
  8319. },
  8320. /**
  8321. * Set the JS DOM events on the container and document. This method should contain
  8322. * a one-to-one assignment between methods and their handlers. Any advanced logic should
  8323. * be moved to the handler reflecting the event's name.
  8324. */
  8325. setDOMEvents: function () {
  8326. var pointer = this,
  8327. container = pointer.chart.container;
  8328. container.onmousedown = function (e) {
  8329. pointer.onContainerMouseDown(e);
  8330. };
  8331. container.onmousemove = function (e) {
  8332. pointer.onContainerMouseMove(e);
  8333. };
  8334. container.onclick = function (e) {
  8335. pointer.onContainerClick(e);
  8336. };
  8337. addEvent(container, 'mouseleave', pointer.onContainerMouseLeave);
  8338. if (chartCount === 1) {
  8339. addEvent(doc, 'mouseup', pointer.onDocumentMouseUp);
  8340. }
  8341. if (hasTouch) {
  8342. container.ontouchstart = function (e) {
  8343. pointer.onContainerTouchStart(e);
  8344. };
  8345. container.ontouchmove = function (e) {
  8346. pointer.onContainerTouchMove(e);
  8347. };
  8348. if (chartCount === 1) {
  8349. addEvent(doc, 'touchend', pointer.onDocumentTouchEnd);
  8350. }
  8351. }
  8352. },
  8353. /**
  8354. * Destroys the Pointer object and disconnects DOM events.
  8355. */
  8356. destroy: function () {
  8357. var prop;
  8358. removeEvent(this.chart.container, 'mouseleave', this.onContainerMouseLeave);
  8359. if (!chartCount) {
  8360. removeEvent(doc, 'mouseup', this.onDocumentMouseUp);
  8361. removeEvent(doc, 'touchend', this.onDocumentTouchEnd);
  8362. }
  8363. // memory and CPU leak
  8364. clearInterval(this.tooltipTimeout);
  8365. for (prop in this) {
  8366. this[prop] = null;
  8367. }
  8368. }
  8369. };
  8370. /* Support for touch devices */
  8371. extend(Highcharts.Pointer.prototype, {
  8372. /**
  8373. * Run translation operations
  8374. */
  8375. pinchTranslate: function (pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) {
  8376. if (this.zoomHor || this.pinchHor) {
  8377. this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
  8378. }
  8379. if (this.zoomVert || this.pinchVert) {
  8380. this.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
  8381. }
  8382. },
  8383. /**
  8384. * Run translation operations for each direction (horizontal and vertical) independently
  8385. */
  8386. pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch, forcedScale) {
  8387. var chart = this.chart,
  8388. xy = horiz ? 'x' : 'y',
  8389. XY = horiz ? 'X' : 'Y',
  8390. sChartXY = 'chart' + XY,
  8391. wh = horiz ? 'width' : 'height',
  8392. plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')],
  8393. selectionWH,
  8394. selectionXY,
  8395. clipXY,
  8396. scale = forcedScale || 1,
  8397. inverted = chart.inverted,
  8398. bounds = chart.bounds[horiz ? 'h' : 'v'],
  8399. singleTouch = pinchDown.length === 1,
  8400. touch0Start = pinchDown[0][sChartXY],
  8401. touch0Now = touches[0][sChartXY],
  8402. touch1Start = !singleTouch && pinchDown[1][sChartXY],
  8403. touch1Now = !singleTouch && touches[1][sChartXY],
  8404. outOfBounds,
  8405. transformScale,
  8406. scaleKey,
  8407. setScale = function () {
  8408. if (!singleTouch && mathAbs(touch0Start - touch1Start) > 20) { // Don't zoom if fingers are too close on this axis
  8409. scale = forcedScale || mathAbs(touch0Now - touch1Now) / mathAbs(touch0Start - touch1Start);
  8410. }
  8411. clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start;
  8412. selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale;
  8413. };
  8414. // Set the scale, first pass
  8415. setScale();
  8416. selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not
  8417. // Out of bounds
  8418. if (selectionXY < bounds.min) {
  8419. selectionXY = bounds.min;
  8420. outOfBounds = true;
  8421. } else if (selectionXY + selectionWH > bounds.max) {
  8422. selectionXY = bounds.max - selectionWH;
  8423. outOfBounds = true;
  8424. }
  8425. // Is the chart dragged off its bounds, determined by dataMin and dataMax?
  8426. if (outOfBounds) {
  8427. // Modify the touchNow position in order to create an elastic drag movement. This indicates
  8428. // to the user that the chart is responsive but can't be dragged further.
  8429. touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]);
  8430. if (!singleTouch) {
  8431. touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]);
  8432. }
  8433. // Set the scale, second pass to adapt to the modified touchNow positions
  8434. setScale();
  8435. } else {
  8436. lastValidTouch[xy] = [touch0Now, touch1Now];
  8437. }
  8438. // Set geometry for clipping, selection and transformation
  8439. if (!inverted) { // TODO: implement clipping for inverted charts
  8440. clip[xy] = clipXY - plotLeftTop;
  8441. clip[wh] = selectionWH;
  8442. }
  8443. scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY;
  8444. transformScale = inverted ? 1 / scale : scale;
  8445. selectionMarker[wh] = selectionWH;
  8446. selectionMarker[xy] = selectionXY;
  8447. transform[scaleKey] = scale;
  8448. transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start));
  8449. },
  8450. /**
  8451. * Handle touch events with two touches
  8452. */
  8453. pinch: function (e) {
  8454. var self = this,
  8455. chart = self.chart,
  8456. pinchDown = self.pinchDown,
  8457. followTouchMove = self.followTouchMove,
  8458. touches = e.touches,
  8459. touchesLength = touches.length,
  8460. lastValidTouch = self.lastValidTouch,
  8461. hasZoom = self.hasZoom,
  8462. selectionMarker = self.selectionMarker,
  8463. transform = {},
  8464. fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, PREFIX + 'tracker') &&
  8465. chart.runTrackerClick) || chart.runChartClick),
  8466. clip = {};
  8467. // On touch devices, only proceed to trigger click if a handler is defined
  8468. if ((hasZoom || followTouchMove) && !fireClickEvent) {
  8469. e.preventDefault();
  8470. }
  8471. // Normalize each touch
  8472. map(touches, function (e) {
  8473. return self.normalize(e);
  8474. });
  8475. // Register the touch start position
  8476. if (e.type === 'touchstart') {
  8477. each(touches, function (e, i) {
  8478. pinchDown[i] = { chartX: e.chartX, chartY: e.chartY };
  8479. });
  8480. lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX];
  8481. lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY];
  8482. // Identify the data bounds in pixels
  8483. each(chart.axes, function (axis) {
  8484. if (axis.zoomEnabled) {
  8485. var bounds = chart.bounds[axis.horiz ? 'h' : 'v'],
  8486. minPixelPadding = axis.minPixelPadding,
  8487. min = axis.toPixels(axis.dataMin),
  8488. max = axis.toPixels(axis.dataMax),
  8489. absMin = mathMin(min, max),
  8490. absMax = mathMax(min, max);
  8491. // Store the bounds for use in the touchmove handler
  8492. bounds.min = mathMin(axis.pos, absMin - minPixelPadding);
  8493. bounds.max = mathMax(axis.pos + axis.len, absMax + minPixelPadding);
  8494. }
  8495. });
  8496. // Event type is touchmove, handle panning and pinching
  8497. } else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first
  8498. // Set the marker
  8499. if (!selectionMarker) {
  8500. self.selectionMarker = selectionMarker = extend({
  8501. destroy: noop
  8502. }, chart.plotBox);
  8503. }
  8504. self.pinchTranslate(pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
  8505. self.hasPinched = hasZoom;
  8506. // Scale and translate the groups to provide visual feedback during pinching
  8507. self.scaleGroups(transform, clip);
  8508. // Optionally move the tooltip on touchmove
  8509. if (!hasZoom && followTouchMove && touchesLength === 1) {
  8510. this.runPointActions(self.normalize(e));
  8511. }
  8512. }
  8513. },
  8514. onContainerTouchStart: function (e) {
  8515. var chart = this.chart;
  8516. hoverChartIndex = chart.index;
  8517. if (e.touches.length === 1) {
  8518. e = this.normalize(e);
  8519. if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
  8520. // Run mouse events and display tooltip etc
  8521. this.runPointActions(e);
  8522. this.pinch(e);
  8523. } else {
  8524. // Hide the tooltip on touching outside the plot area (#1203)
  8525. this.reset();
  8526. }
  8527. } else if (e.touches.length === 2) {
  8528. this.pinch(e);
  8529. }
  8530. },
  8531. onContainerTouchMove: function (e) {
  8532. if (e.touches.length === 1 || e.touches.length === 2) {
  8533. this.pinch(e);
  8534. }
  8535. },
  8536. onDocumentTouchEnd: function (e) {
  8537. if (charts[hoverChartIndex]) {
  8538. charts[hoverChartIndex].pointer.drop(e);
  8539. }
  8540. }
  8541. });
  8542. if (win.PointerEvent || win.MSPointerEvent) {
  8543. // The touches object keeps track of the points being touched at all times
  8544. var touches = {},
  8545. hasPointerEvent = !!win.PointerEvent,
  8546. getWebkitTouches = function () {
  8547. var key, fake = [];
  8548. fake.item = function (i) { return this[i]; };
  8549. for (key in touches) {
  8550. if (touches.hasOwnProperty(key)) {
  8551. fake.push({
  8552. pageX: touches[key].pageX,
  8553. pageY: touches[key].pageY,
  8554. target: touches[key].target
  8555. });
  8556. }
  8557. }
  8558. return fake;
  8559. },
  8560. translateMSPointer = function (e, method, wktype, callback) {
  8561. var p;
  8562. e = e.originalEvent || e;
  8563. if ((e.pointerType === 'touch' || e.pointerType === e.MSPOINTER_TYPE_TOUCH) && charts[hoverChartIndex]) {
  8564. callback(e);
  8565. p = charts[hoverChartIndex].pointer;
  8566. p[method]({
  8567. type: wktype,
  8568. target: e.currentTarget,
  8569. preventDefault: noop,
  8570. touches: getWebkitTouches()
  8571. });
  8572. }
  8573. };
  8574. /**
  8575. * Extend the Pointer prototype with methods for each event handler and more
  8576. */
  8577. extend(Pointer.prototype, {
  8578. onContainerPointerDown: function (e) {
  8579. translateMSPointer(e, 'onContainerTouchStart', 'touchstart', function (e) {
  8580. touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY, target: e.currentTarget };
  8581. });
  8582. },
  8583. onContainerPointerMove: function (e) {
  8584. translateMSPointer(e, 'onContainerTouchMove', 'touchmove', function (e) {
  8585. touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY };
  8586. if (!touches[e.pointerId].target) {
  8587. touches[e.pointerId].target = e.currentTarget;
  8588. }
  8589. });
  8590. },
  8591. onDocumentPointerUp: function (e) {
  8592. translateMSPointer(e, 'onContainerTouchEnd', 'touchend', function (e) {
  8593. delete touches[e.pointerId];
  8594. });
  8595. },
  8596. /**
  8597. * Add or remove the MS Pointer specific events
  8598. */
  8599. batchMSEvents: function (fn) {
  8600. fn(this.chart.container, hasPointerEvent ? 'pointerdown' : 'MSPointerDown', this.onContainerPointerDown);
  8601. fn(this.chart.container, hasPointerEvent ? 'pointermove' : 'MSPointerMove', this.onContainerPointerMove);
  8602. fn(doc, hasPointerEvent ? 'pointerup' : 'MSPointerUp', this.onDocumentPointerUp);
  8603. }
  8604. });
  8605. // Disable default IE actions for pinch and such on chart element
  8606. wrap(Pointer.prototype, 'init', function (proceed, chart, options) {
  8607. proceed.call(this, chart, options);
  8608. if (this.hasZoom || this.followTouchMove) {
  8609. css(chart.container, {
  8610. '-ms-touch-action': NONE,
  8611. 'touch-action': NONE
  8612. });
  8613. }
  8614. });
  8615. // Add IE specific touch events to chart
  8616. wrap(Pointer.prototype, 'setDOMEvents', function (proceed) {
  8617. proceed.apply(this);
  8618. if (this.hasZoom || this.followTouchMove) {
  8619. this.batchMSEvents(addEvent);
  8620. }
  8621. });
  8622. // Destroy MS events also
  8623. wrap(Pointer.prototype, 'destroy', function (proceed) {
  8624. this.batchMSEvents(removeEvent);
  8625. proceed.call(this);
  8626. });
  8627. }
  8628. /**
  8629. * The overview of the chart's series
  8630. */
  8631. var Legend = Highcharts.Legend = function (chart, options) {
  8632. this.init(chart, options);
  8633. };
  8634. Legend.prototype = {
  8635. /**
  8636. * Initialize the legend
  8637. */
  8638. init: function (chart, options) {
  8639. var legend = this,
  8640. itemStyle = options.itemStyle,
  8641. padding = pick(options.padding, 8),
  8642. itemMarginTop = options.itemMarginTop || 0;
  8643. this.options = options;
  8644. if (!options.enabled) {
  8645. return;
  8646. }
  8647. legend.baseline = pInt(itemStyle.fontSize) + 3 + itemMarginTop; // used in Series prototype
  8648. legend.itemStyle = itemStyle;
  8649. legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle);
  8650. legend.itemMarginTop = itemMarginTop;
  8651. legend.padding = padding;
  8652. legend.initialItemX = padding;
  8653. legend.initialItemY = padding - 5; // 5 is the number of pixels above the text
  8654. legend.maxItemWidth = 0;
  8655. legend.chart = chart;
  8656. legend.itemHeight = 0;
  8657. legend.lastLineHeight = 0;
  8658. legend.symbolWidth = pick(options.symbolWidth, 16);
  8659. legend.pages = [];
  8660. // Render it
  8661. legend.render();
  8662. // move checkboxes
  8663. addEvent(legend.chart, 'endResize', function () {
  8664. legend.positionCheckboxes();
  8665. });
  8666. },
  8667. /**
  8668. * Set the colors for the legend item
  8669. * @param {Object} item A Series or Point instance
  8670. * @param {Object} visible Dimmed or colored
  8671. */
  8672. colorizeItem: function (item, visible) {
  8673. var legend = this,
  8674. options = legend.options,
  8675. legendItem = item.legendItem,
  8676. legendLine = item.legendLine,
  8677. legendSymbol = item.legendSymbol,
  8678. hiddenColor = legend.itemHiddenStyle.color,
  8679. textColor = visible ? options.itemStyle.color : hiddenColor,
  8680. symbolColor = visible ? (item.legendColor || item.color || '#CCC') : hiddenColor,
  8681. markerOptions = item.options && item.options.marker,
  8682. symbolAttr = { fill: symbolColor },
  8683. key,
  8684. val;
  8685. if (legendItem) {
  8686. legendItem.css({ fill: textColor, color: textColor }); // color for #1553, oldIE
  8687. }
  8688. if (legendLine) {
  8689. legendLine.attr({ stroke: symbolColor });
  8690. }
  8691. if (legendSymbol) {
  8692. // Apply marker options
  8693. if (markerOptions && legendSymbol.isMarker) { // #585
  8694. symbolAttr.stroke = symbolColor;
  8695. markerOptions = item.convertAttribs(markerOptions);
  8696. for (key in markerOptions) {
  8697. val = markerOptions[key];
  8698. if (val !== UNDEFINED) {
  8699. symbolAttr[key] = val;
  8700. }
  8701. }
  8702. }
  8703. legendSymbol.attr(symbolAttr);
  8704. }
  8705. },
  8706. /**
  8707. * Position the legend item
  8708. * @param {Object} item A Series or Point instance
  8709. */
  8710. positionItem: function (item) {
  8711. var legend = this,
  8712. options = legend.options,
  8713. symbolPadding = options.symbolPadding,
  8714. ltr = !options.rtl,
  8715. legendItemPos = item._legendItemPos,
  8716. itemX = legendItemPos[0],
  8717. itemY = legendItemPos[1],
  8718. checkbox = item.checkbox;
  8719. if (item.legendGroup) {
  8720. item.legendGroup.translate(
  8721. ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4,
  8722. itemY
  8723. );
  8724. }
  8725. if (checkbox) {
  8726. checkbox.x = itemX;
  8727. checkbox.y = itemY;
  8728. }
  8729. },
  8730. /**
  8731. * Destroy a single legend item
  8732. * @param {Object} item The series or point
  8733. */
  8734. destroyItem: function (item) {
  8735. var checkbox = item.checkbox;
  8736. // destroy SVG elements
  8737. each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) {
  8738. if (item[key]) {
  8739. item[key] = item[key].destroy();
  8740. }
  8741. });
  8742. if (checkbox) {
  8743. discardElement(item.checkbox);
  8744. }
  8745. },
  8746. /**
  8747. * Destroys the legend.
  8748. */
  8749. destroy: function () {
  8750. var legend = this,
  8751. legendGroup = legend.group,
  8752. box = legend.box;
  8753. if (box) {
  8754. legend.box = box.destroy();
  8755. }
  8756. if (legendGroup) {
  8757. legend.group = legendGroup.destroy();
  8758. }
  8759. },
  8760. /**
  8761. * Position the checkboxes after the width is determined
  8762. */
  8763. positionCheckboxes: function (scrollOffset) {
  8764. var alignAttr = this.group.alignAttr,
  8765. translateY,
  8766. clipHeight = this.clipHeight || this.legendHeight;
  8767. if (alignAttr) {
  8768. translateY = alignAttr.translateY;
  8769. each(this.allItems, function (item) {
  8770. var checkbox = item.checkbox,
  8771. top;
  8772. if (checkbox) {
  8773. top = (translateY + checkbox.y + (scrollOffset || 0) + 3);
  8774. css(checkbox, {
  8775. left: (alignAttr.translateX + item.checkboxOffset + checkbox.x - 20) + PX,
  8776. top: top + PX,
  8777. display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE
  8778. });
  8779. }
  8780. });
  8781. }
  8782. },
  8783. /**
  8784. * Render the legend title on top of the legend
  8785. */
  8786. renderTitle: function () {
  8787. var options = this.options,
  8788. padding = this.padding,
  8789. titleOptions = options.title,
  8790. titleHeight = 0,
  8791. bBox;
  8792. if (titleOptions.text) {
  8793. if (!this.title) {
  8794. this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title')
  8795. .attr({ zIndex: 1 })
  8796. .css(titleOptions.style)
  8797. .add(this.group);
  8798. }
  8799. bBox = this.title.getBBox();
  8800. titleHeight = bBox.height;
  8801. this.offsetWidth = bBox.width; // #1717
  8802. this.contentGroup.attr({ translateY: titleHeight });
  8803. }
  8804. this.titleHeight = titleHeight;
  8805. },
  8806. /**
  8807. * Render a single specific legend item
  8808. * @param {Object} item A series or point
  8809. */
  8810. renderItem: function (item) {
  8811. var legend = this,
  8812. chart = legend.chart,
  8813. renderer = chart.renderer,
  8814. options = legend.options,
  8815. horizontal = options.layout === 'horizontal',
  8816. symbolWidth = legend.symbolWidth,
  8817. symbolPadding = options.symbolPadding,
  8818. itemStyle = legend.itemStyle,
  8819. itemHiddenStyle = legend.itemHiddenStyle,
  8820. padding = legend.padding,
  8821. itemDistance = horizontal ? pick(options.itemDistance, 20) : 0, // docs
  8822. ltr = !options.rtl,
  8823. itemHeight,
  8824. widthOption = options.width,
  8825. itemMarginBottom = options.itemMarginBottom || 0,
  8826. itemMarginTop = legend.itemMarginTop,
  8827. initialItemX = legend.initialItemX,
  8828. bBox,
  8829. itemWidth,
  8830. li = item.legendItem,
  8831. series = item.series && item.series.drawLegendSymbol ? item.series : item,
  8832. seriesOptions = series.options,
  8833. showCheckbox = legend.createCheckboxForItem && seriesOptions && seriesOptions.showCheckbox,
  8834. useHTML = options.useHTML;
  8835. if (!li) { // generate it once, later move it
  8836. // Generate the group box
  8837. // A group to hold the symbol and text. Text is to be appended in Legend class.
  8838. item.legendGroup = renderer.g('legend-item')
  8839. .attr({ zIndex: 1 })
  8840. .add(legend.scrollGroup);
  8841. // Draw the legend symbol inside the group box
  8842. series.drawLegendSymbol(legend, item);
  8843. // Generate the list item text and add it to the group
  8844. item.legendItem = li = renderer.text(
  8845. options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item),
  8846. ltr ? symbolWidth + symbolPadding : -symbolPadding,
  8847. legend.baseline,
  8848. useHTML
  8849. )
  8850. .css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021)
  8851. .attr({
  8852. align: ltr ? 'left' : 'right',
  8853. zIndex: 2
  8854. })
  8855. .add(item.legendGroup);
  8856. if (legend.setItemEvents) {
  8857. legend.setItemEvents(item, li, useHTML, itemStyle, itemHiddenStyle);
  8858. }
  8859. // Colorize the items
  8860. legend.colorizeItem(item, item.visible);
  8861. // add the HTML checkbox on top
  8862. if (showCheckbox) {
  8863. legend.createCheckboxForItem(item);
  8864. }
  8865. }
  8866. // calculate the positions for the next line
  8867. bBox = li.getBBox();
  8868. itemWidth = item.checkboxOffset =
  8869. options.itemWidth ||
  8870. item.legendItemWidth ||
  8871. symbolWidth + symbolPadding + bBox.width + itemDistance + (showCheckbox ? 20 : 0);
  8872. legend.itemHeight = itemHeight = mathRound(item.legendItemHeight || bBox.height);
  8873. // if the item exceeds the width, start a new line
  8874. if (horizontal && legend.itemX - initialItemX + itemWidth >
  8875. (widthOption || (chart.chartWidth - 2 * padding - initialItemX - options.x))) {
  8876. legend.itemX = initialItemX;
  8877. legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom;
  8878. legend.lastLineHeight = 0; // reset for next line
  8879. }
  8880. // If the item exceeds the height, start a new column
  8881. /*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) {
  8882. legend.itemY = legend.initialItemY;
  8883. legend.itemX += legend.maxItemWidth;
  8884. legend.maxItemWidth = 0;
  8885. }*/
  8886. // Set the edge positions
  8887. legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth);
  8888. legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom;
  8889. legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915
  8890. // cache the position of the newly generated or reordered items
  8891. item._legendItemPos = [legend.itemX, legend.itemY];
  8892. // advance
  8893. if (horizontal) {
  8894. legend.itemX += itemWidth;
  8895. } else {
  8896. legend.itemY += itemMarginTop + itemHeight + itemMarginBottom;
  8897. legend.lastLineHeight = itemHeight;
  8898. }
  8899. // the width of the widest item
  8900. legend.offsetWidth = widthOption || mathMax(
  8901. (horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding,
  8902. legend.offsetWidth
  8903. );
  8904. },
  8905. /**
  8906. * Get all items, which is one item per series for normal series and one item per point
  8907. * for pie series.
  8908. */
  8909. getAllItems: function () {
  8910. var allItems = [];
  8911. each(this.chart.series, function (series) {
  8912. var seriesOptions = series.options;
  8913. // Handle showInLegend. If the series is linked to another series, defaults to false.
  8914. if (!pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? UNDEFINED : false, true)) {
  8915. return;
  8916. }
  8917. // use points or series for the legend item depending on legendType
  8918. allItems = allItems.concat(
  8919. series.legendItems ||
  8920. (seriesOptions.legendType === 'point' ?
  8921. series.data :
  8922. series)
  8923. );
  8924. });
  8925. return allItems;
  8926. },
  8927. /**
  8928. * Render the legend. This method can be called both before and after
  8929. * chart.render. If called after, it will only rearrange items instead
  8930. * of creating new ones.
  8931. */
  8932. render: function () {
  8933. var legend = this,
  8934. chart = legend.chart,
  8935. renderer = chart.renderer,
  8936. legendGroup = legend.group,
  8937. allItems,
  8938. display,
  8939. legendWidth,
  8940. legendHeight,
  8941. box = legend.box,
  8942. options = legend.options,
  8943. padding = legend.padding,
  8944. legendBorderWidth = options.borderWidth,
  8945. legendBackgroundColor = options.backgroundColor;
  8946. legend.itemX = legend.initialItemX;
  8947. legend.itemY = legend.initialItemY;
  8948. legend.offsetWidth = 0;
  8949. legend.lastItemY = 0;
  8950. if (!legendGroup) {
  8951. legend.group = legendGroup = renderer.g('legend')
  8952. .attr({ zIndex: 7 })
  8953. .add();
  8954. legend.contentGroup = renderer.g()
  8955. .attr({ zIndex: 1 }) // above background
  8956. .add(legendGroup);
  8957. legend.scrollGroup = renderer.g()
  8958. .add(legend.contentGroup);
  8959. }
  8960. legend.renderTitle();
  8961. // add each series or point
  8962. allItems = legend.getAllItems();
  8963. // sort by legendIndex
  8964. stableSort(allItems, function (a, b) {
  8965. return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0);
  8966. });
  8967. // reversed legend
  8968. if (options.reversed) {
  8969. allItems.reverse();
  8970. }
  8971. legend.allItems = allItems;
  8972. legend.display = display = !!allItems.length;
  8973. // render the items
  8974. each(allItems, function (item) {
  8975. legend.renderItem(item);
  8976. });
  8977. // Draw the border
  8978. legendWidth = options.width || legend.offsetWidth;
  8979. legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight;
  8980. legendHeight = legend.handleOverflow(legendHeight);
  8981. if (legendBorderWidth || legendBackgroundColor) {
  8982. legendWidth += padding;
  8983. legendHeight += padding;
  8984. if (!box) {
  8985. legend.box = box = renderer.rect(
  8986. 0,
  8987. 0,
  8988. legendWidth,
  8989. legendHeight,
  8990. options.borderRadius,
  8991. legendBorderWidth || 0
  8992. ).attr({
  8993. stroke: options.borderColor,
  8994. 'stroke-width': legendBorderWidth || 0,
  8995. fill: legendBackgroundColor || NONE
  8996. })
  8997. .add(legendGroup)
  8998. .shadow(options.shadow);
  8999. box.isNew = true;
  9000. } else if (legendWidth > 0 && legendHeight > 0) {
  9001. box[box.isNew ? 'attr' : 'animate'](
  9002. box.crisp({ width: legendWidth, height: legendHeight })
  9003. );
  9004. box.isNew = false;
  9005. }
  9006. // hide the border if no items
  9007. box[display ? 'show' : 'hide']();
  9008. }
  9009. legend.legendWidth = legendWidth;
  9010. legend.legendHeight = legendHeight;
  9011. // Now that the legend width and height are established, put the items in the
  9012. // final position
  9013. each(allItems, function (item) {
  9014. legend.positionItem(item);
  9015. });
  9016. // 1.x compatibility: positioning based on style
  9017. /*var props = ['left', 'right', 'top', 'bottom'],
  9018. prop,
  9019. i = 4;
  9020. while (i--) {
  9021. prop = props[i];
  9022. if (options.style[prop] && options.style[prop] !== 'auto') {
  9023. options[i < 2 ? 'align' : 'verticalAlign'] = prop;
  9024. options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1);
  9025. }
  9026. }*/
  9027. if (display) {
  9028. legendGroup.align(extend({
  9029. width: legendWidth,
  9030. height: legendHeight
  9031. }, options), true, 'spacingBox');
  9032. }
  9033. if (!chart.isResizing) {
  9034. this.positionCheckboxes();
  9035. }
  9036. },
  9037. /**
  9038. * Set up the overflow handling by adding navigation with up and down arrows below the
  9039. * legend.
  9040. */
  9041. handleOverflow: function (legendHeight) {
  9042. var legend = this,
  9043. chart = this.chart,
  9044. renderer = chart.renderer,
  9045. options = this.options,
  9046. optionsY = options.y,
  9047. alignTop = options.verticalAlign === 'top',
  9048. spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding,
  9049. maxHeight = options.maxHeight,
  9050. clipHeight,
  9051. clipRect = this.clipRect,
  9052. navOptions = options.navigation,
  9053. animation = pick(navOptions.animation, true),
  9054. arrowSize = navOptions.arrowSize || 12,
  9055. nav = this.nav,
  9056. pages = this.pages,
  9057. lastY,
  9058. allItems = this.allItems;
  9059. // Adjust the height
  9060. if (options.layout === 'horizontal') {
  9061. spaceHeight /= 2;
  9062. }
  9063. if (maxHeight) {
  9064. spaceHeight = mathMin(spaceHeight, maxHeight);
  9065. }
  9066. // Reset the legend height and adjust the clipping rectangle
  9067. pages.length = 0;
  9068. if (legendHeight > spaceHeight && !options.useHTML) {
  9069. this.clipHeight = clipHeight = spaceHeight - 20 - this.titleHeight - this.padding;
  9070. this.currentPage = pick(this.currentPage, 1);
  9071. this.fullHeight = legendHeight;
  9072. // Fill pages with Y positions so that the top of each a legend item defines
  9073. // the scroll top for each page (#2098)
  9074. each(allItems, function (item, i) {
  9075. var y = item._legendItemPos[1],
  9076. h = mathRound(item.legendItem.getBBox().height),
  9077. len = pages.length;
  9078. if (!len || (y - pages[len - 1] > clipHeight && (lastY || y) !== pages[len - 1])) {
  9079. pages.push(lastY || y);
  9080. len++;
  9081. }
  9082. if (i === allItems.length - 1 && y + h - pages[len - 1] > clipHeight) {
  9083. pages.push(y);
  9084. }
  9085. if (y !== lastY) {
  9086. lastY = y;
  9087. }
  9088. });
  9089. // Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787)
  9090. if (!clipRect) {
  9091. clipRect = legend.clipRect = renderer.clipRect(0, this.padding, 9999, 0);
  9092. legend.contentGroup.clip(clipRect);
  9093. }
  9094. clipRect.attr({
  9095. height: clipHeight
  9096. });
  9097. // Add navigation elements
  9098. if (!nav) {
  9099. this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group);
  9100. this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize)
  9101. .on('click', function () {
  9102. legend.scroll(-1, animation);
  9103. })
  9104. .add(nav);
  9105. this.pager = renderer.text('', 15, 10)
  9106. .css(navOptions.style)
  9107. .add(nav);
  9108. this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize)
  9109. .on('click', function () {
  9110. legend.scroll(1, animation);
  9111. })
  9112. .add(nav);
  9113. }
  9114. // Set initial position
  9115. legend.scroll(0);
  9116. legendHeight = spaceHeight;
  9117. } else if (nav) {
  9118. clipRect.attr({
  9119. height: chart.chartHeight
  9120. });
  9121. nav.hide();
  9122. this.scrollGroup.attr({
  9123. translateY: 1
  9124. });
  9125. this.clipHeight = 0; // #1379
  9126. }
  9127. return legendHeight;
  9128. },
  9129. /**
  9130. * Scroll the legend by a number of pages
  9131. * @param {Object} scrollBy
  9132. * @param {Object} animation
  9133. */
  9134. scroll: function (scrollBy, animation) {
  9135. var pages = this.pages,
  9136. pageCount = pages.length,
  9137. currentPage = this.currentPage + scrollBy,
  9138. clipHeight = this.clipHeight,
  9139. navOptions = this.options.navigation,
  9140. activeColor = navOptions.activeColor,
  9141. inactiveColor = navOptions.inactiveColor,
  9142. pager = this.pager,
  9143. padding = this.padding,
  9144. scrollOffset;
  9145. // When resizing while looking at the last page
  9146. if (currentPage > pageCount) {
  9147. currentPage = pageCount;
  9148. }
  9149. if (currentPage > 0) {
  9150. if (animation !== UNDEFINED) {
  9151. setAnimation(animation, this.chart);
  9152. }
  9153. this.nav.attr({
  9154. translateX: padding,
  9155. translateY: clipHeight + this.padding + 7 + this.titleHeight,
  9156. visibility: VISIBLE
  9157. });
  9158. this.up.attr({
  9159. fill: currentPage === 1 ? inactiveColor : activeColor
  9160. })
  9161. .css({
  9162. cursor: currentPage === 1 ? 'default' : 'pointer'
  9163. });
  9164. pager.attr({
  9165. text: currentPage + '/' + pageCount
  9166. });
  9167. this.down.attr({
  9168. x: 18 + this.pager.getBBox().width, // adjust to text width
  9169. fill: currentPage === pageCount ? inactiveColor : activeColor
  9170. })
  9171. .css({
  9172. cursor: currentPage === pageCount ? 'default' : 'pointer'
  9173. });
  9174. scrollOffset = -pages[currentPage - 1] + this.initialItemY;
  9175. this.scrollGroup.animate({
  9176. translateY: scrollOffset
  9177. });
  9178. this.currentPage = currentPage;
  9179. this.positionCheckboxes(scrollOffset);
  9180. }
  9181. }
  9182. };
  9183. /*
  9184. * LegendSymbolMixin
  9185. */
  9186. var LegendSymbolMixin = Highcharts.LegendSymbolMixin = {
  9187. /**
  9188. * Get the series' symbol in the legend
  9189. *
  9190. * @param {Object} legend The legend object
  9191. * @param {Object} item The series (this) or point
  9192. */
  9193. drawRectangle: function (legend, item) {
  9194. var symbolHeight = legend.options.symbolHeight || 12;
  9195. item.legendSymbol = this.chart.renderer.rect(
  9196. 0,
  9197. legend.baseline - 5 - (symbolHeight / 2),
  9198. legend.symbolWidth,
  9199. symbolHeight,
  9200. legend.options.symbolRadius || 0
  9201. ).attr({
  9202. zIndex: 3
  9203. }).add(item.legendGroup);
  9204. },
  9205. /**
  9206. * Get the series' symbol in the legend. This method should be overridable to create custom
  9207. * symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols.
  9208. *
  9209. * @param {Object} legend The legend object
  9210. */
  9211. drawLineMarker: function (legend) {
  9212. var options = this.options,
  9213. markerOptions = options.marker,
  9214. radius,
  9215. legendOptions = legend.options,
  9216. legendSymbol,
  9217. symbolWidth = legend.symbolWidth,
  9218. renderer = this.chart.renderer,
  9219. legendItemGroup = this.legendGroup,
  9220. verticalCenter = legend.baseline - mathRound(renderer.fontMetrics(legendOptions.itemStyle.fontSize).b * 0.3),
  9221. attr;
  9222. // Draw the line
  9223. if (options.lineWidth) {
  9224. attr = {
  9225. 'stroke-width': options.lineWidth
  9226. };
  9227. if (options.dashStyle) {
  9228. attr.dashstyle = options.dashStyle;
  9229. }
  9230. this.legendLine = renderer.path([
  9231. M,
  9232. 0,
  9233. verticalCenter,
  9234. L,
  9235. symbolWidth,
  9236. verticalCenter
  9237. ])
  9238. .attr(attr)
  9239. .add(legendItemGroup);
  9240. }
  9241. // Draw the marker
  9242. if (markerOptions && markerOptions.enabled !== false) {
  9243. radius = markerOptions.radius;
  9244. this.legendSymbol = legendSymbol = renderer.symbol(
  9245. this.symbol,
  9246. (symbolWidth / 2) - radius,
  9247. verticalCenter - radius,
  9248. 2 * radius,
  9249. 2 * radius
  9250. )
  9251. .add(legendItemGroup);
  9252. legendSymbol.isMarker = true;
  9253. }
  9254. }
  9255. };
  9256. // Workaround for #2030, horizontal legend items not displaying in IE11 Preview,
  9257. // and for #2580, a similar drawing flaw in Firefox 26.
  9258. // TODO: Explore if there's a general cause for this. The problem may be related
  9259. // to nested group elements, as the legend item texts are within 4 group elements.
  9260. if (/Trident\/7\.0/.test(userAgent) || isFirefox) {
  9261. wrap(Legend.prototype, 'positionItem', function (proceed, item) {
  9262. var legend = this,
  9263. runPositionItem = function () { // If chart destroyed in sync, this is undefined (#2030)
  9264. if (item._legendItemPos) {
  9265. proceed.call(legend, item);
  9266. }
  9267. };
  9268. // Do it now, for export and to get checkbox placement
  9269. runPositionItem();
  9270. // Do it after to work around the core issue
  9271. setTimeout(runPositionItem);
  9272. });
  9273. }
  9274. /**
  9275. * The chart class
  9276. * @param {Object} options
  9277. * @param {Function} callback Function to run when the chart has loaded
  9278. */
  9279. function Chart() {
  9280. this.init.apply(this, arguments);
  9281. }
  9282. Chart.prototype = {
  9283. /**
  9284. * Initialize the chart
  9285. */
  9286. init: function (userOptions, callback) {
  9287. // Handle regular options
  9288. var options,
  9289. seriesOptions = userOptions.series; // skip merging data points to increase performance
  9290. userOptions.series = null;
  9291. options = merge(defaultOptions, userOptions); // do the merge
  9292. options.series = userOptions.series = seriesOptions; // set back the series data
  9293. this.userOptions = userOptions;
  9294. var optionsChart = options.chart;
  9295. // Create margin & spacing array
  9296. this.margin = this.splashArray('margin', optionsChart);
  9297. this.spacing = this.splashArray('spacing', optionsChart);
  9298. var chartEvents = optionsChart.events;
  9299. //this.runChartClick = chartEvents && !!chartEvents.click;
  9300. this.bounds = { h: {}, v: {} }; // Pixel data bounds for touch zoom
  9301. this.callback = callback;
  9302. this.isResizing = 0;
  9303. this.options = options;
  9304. //chartTitleOptions = UNDEFINED;
  9305. //chartSubtitleOptions = UNDEFINED;
  9306. this.axes = [];
  9307. this.series = [];
  9308. this.hasCartesianSeries = optionsChart.showAxes;
  9309. //this.axisOffset = UNDEFINED;
  9310. //this.maxTicks = UNDEFINED; // handle the greatest amount of ticks on grouped axes
  9311. //this.inverted = UNDEFINED;
  9312. //this.loadingShown = UNDEFINED;
  9313. //this.container = UNDEFINED;
  9314. //this.chartWidth = UNDEFINED;
  9315. //this.chartHeight = UNDEFINED;
  9316. //this.marginRight = UNDEFINED;
  9317. //this.marginBottom = UNDEFINED;
  9318. //this.containerWidth = UNDEFINED;
  9319. //this.containerHeight = UNDEFINED;
  9320. //this.oldChartWidth = UNDEFINED;
  9321. //this.oldChartHeight = UNDEFINED;
  9322. //this.renderTo = UNDEFINED;
  9323. //this.renderToClone = UNDEFINED;
  9324. //this.spacingBox = UNDEFINED
  9325. //this.legend = UNDEFINED;
  9326. // Elements
  9327. //this.chartBackground = UNDEFINED;
  9328. //this.plotBackground = UNDEFINED;
  9329. //this.plotBGImage = UNDEFINED;
  9330. //this.plotBorder = UNDEFINED;
  9331. //this.loadingDiv = UNDEFINED;
  9332. //this.loadingSpan = UNDEFINED;
  9333. var chart = this,
  9334. eventType;
  9335. // Add the chart to the global lookup
  9336. chart.index = charts.length;
  9337. charts.push(chart);
  9338. chartCount++;
  9339. // Set up auto resize
  9340. if (optionsChart.reflow !== false) {
  9341. addEvent(chart, 'load', function () {
  9342. chart.initReflow();
  9343. });
  9344. }
  9345. // Chart event handlers
  9346. if (chartEvents) {
  9347. for (eventType in chartEvents) {
  9348. addEvent(chart, eventType, chartEvents[eventType]);
  9349. }
  9350. }
  9351. chart.xAxis = [];
  9352. chart.yAxis = [];
  9353. // Expose methods and variables
  9354. chart.animation = useCanVG ? false : pick(optionsChart.animation, true);
  9355. chart.pointCount = 0;
  9356. chart.counters = new ChartCounters();
  9357. chart.firstRender();
  9358. },
  9359. /**
  9360. * Initialize an individual series, called internally before render time
  9361. */
  9362. initSeries: function (options) {
  9363. var chart = this,
  9364. optionsChart = chart.options.chart,
  9365. type = options.type || optionsChart.type || optionsChart.defaultSeriesType,
  9366. series,
  9367. constr = seriesTypes[type];
  9368. // No such series type
  9369. if (!constr) {
  9370. error(17, true);
  9371. }
  9372. series = new constr();
  9373. series.init(this, options);
  9374. return series;
  9375. },
  9376. /**
  9377. * Check whether a given point is within the plot area
  9378. *
  9379. * @param {Number} plotX Pixel x relative to the plot area
  9380. * @param {Number} plotY Pixel y relative to the plot area
  9381. * @param {Boolean} inverted Whether the chart is inverted
  9382. */
  9383. isInsidePlot: function (plotX, plotY, inverted) {
  9384. var x = inverted ? plotY : plotX,
  9385. y = inverted ? plotX : plotY;
  9386. return x >= 0 &&
  9387. x <= this.plotWidth &&
  9388. y >= 0 &&
  9389. y <= this.plotHeight;
  9390. },
  9391. /**
  9392. * Adjust all axes tick amounts
  9393. */
  9394. adjustTickAmounts: function () {
  9395. if (this.options.chart.alignTicks !== false) {
  9396. each(this.axes, function (axis) {
  9397. axis.adjustTickAmount();
  9398. });
  9399. }
  9400. this.maxTicks = null;
  9401. },
  9402. /**
  9403. * Redraw legend, axes or series based on updated data
  9404. *
  9405. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  9406. * configuration
  9407. */
  9408. redraw: function (animation) {
  9409. var chart = this,
  9410. axes = chart.axes,
  9411. series = chart.series,
  9412. pointer = chart.pointer,
  9413. legend = chart.legend,
  9414. redrawLegend = chart.isDirtyLegend,
  9415. hasStackedSeries,
  9416. hasDirtyStacks,
  9417. isDirtyBox = chart.isDirtyBox, // todo: check if it has actually changed?
  9418. seriesLength = series.length,
  9419. i = seriesLength,
  9420. serie,
  9421. renderer = chart.renderer,
  9422. isHiddenChart = renderer.isHidden(),
  9423. afterRedraw = [];
  9424. setAnimation(animation, chart);
  9425. if (isHiddenChart) {
  9426. chart.cloneRenderTo();
  9427. }
  9428. // Adjust title layout (reflow multiline text)
  9429. chart.layOutTitles();
  9430. // link stacked series
  9431. while (i--) {
  9432. serie = series[i];
  9433. if (serie.options.stacking) {
  9434. hasStackedSeries = true;
  9435. if (serie.isDirty) {
  9436. hasDirtyStacks = true;
  9437. break;
  9438. }
  9439. }
  9440. }
  9441. if (hasDirtyStacks) { // mark others as dirty
  9442. i = seriesLength;
  9443. while (i--) {
  9444. serie = series[i];
  9445. if (serie.options.stacking) {
  9446. serie.isDirty = true;
  9447. }
  9448. }
  9449. }
  9450. // handle updated data in the series
  9451. each(series, function (serie) {
  9452. if (serie.isDirty) { // prepare the data so axis can read it
  9453. if (serie.options.legendType === 'point') {
  9454. redrawLegend = true;
  9455. }
  9456. }
  9457. });
  9458. // handle added or removed series
  9459. if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed
  9460. // draw legend graphics
  9461. legend.render();
  9462. chart.isDirtyLegend = false;
  9463. }
  9464. // reset stacks
  9465. if (hasStackedSeries) {
  9466. chart.getStacks();
  9467. }
  9468. if (chart.hasCartesianSeries) {
  9469. if (!chart.isResizing) {
  9470. // reset maxTicks
  9471. chart.maxTicks = null;
  9472. // set axes scales
  9473. each(axes, function (axis) {
  9474. axis.setScale();
  9475. });
  9476. }
  9477. chart.adjustTickAmounts();
  9478. chart.getMargins();
  9479. // If one axis is dirty, all axes must be redrawn (#792, #2169)
  9480. each(axes, function (axis) {
  9481. if (axis.isDirty) {
  9482. isDirtyBox = true;
  9483. }
  9484. });
  9485. // redraw axes
  9486. each(axes, function (axis) {
  9487. // Fire 'afterSetExtremes' only if extremes are set
  9488. if (axis.isDirtyExtremes) { // #821
  9489. axis.isDirtyExtremes = false;
  9490. afterRedraw.push(function () { // prevent a recursive call to chart.redraw() (#1119)
  9491. fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751
  9492. delete axis.eventArgs;
  9493. });
  9494. }
  9495. if (isDirtyBox || hasStackedSeries) {
  9496. axis.redraw();
  9497. }
  9498. });
  9499. }
  9500. // the plot areas size has changed
  9501. if (isDirtyBox) {
  9502. chart.drawChartBox();
  9503. }
  9504. // redraw affected series
  9505. each(series, function (serie) {
  9506. if (serie.isDirty && serie.visible &&
  9507. (!serie.isCartesian || serie.xAxis)) { // issue #153
  9508. serie.redraw();
  9509. }
  9510. });
  9511. // move tooltip or reset
  9512. if (pointer) {
  9513. pointer.reset(true);
  9514. }
  9515. // redraw if canvas
  9516. renderer.draw();
  9517. // fire the event
  9518. fireEvent(chart, 'redraw'); // jQuery breaks this when calling it from addEvent. Overwrites chart.redraw
  9519. if (isHiddenChart) {
  9520. chart.cloneRenderTo(true);
  9521. }
  9522. // Fire callbacks that are put on hold until after the redraw
  9523. each(afterRedraw, function (callback) {
  9524. callback.call();
  9525. });
  9526. },
  9527. /**
  9528. * Get an axis, series or point object by id.
  9529. * @param id {String} The id as given in the configuration options
  9530. */
  9531. get: function (id) {
  9532. var chart = this,
  9533. axes = chart.axes,
  9534. series = chart.series;
  9535. var i,
  9536. j,
  9537. points;
  9538. // search axes
  9539. for (i = 0; i < axes.length; i++) {
  9540. if (axes[i].options.id === id) {
  9541. return axes[i];
  9542. }
  9543. }
  9544. // search series
  9545. for (i = 0; i < series.length; i++) {
  9546. if (series[i].options.id === id) {
  9547. return series[i];
  9548. }
  9549. }
  9550. // search points
  9551. for (i = 0; i < series.length; i++) {
  9552. points = series[i].points || [];
  9553. for (j = 0; j < points.length; j++) {
  9554. if (points[j].id === id) {
  9555. return points[j];
  9556. }
  9557. }
  9558. }
  9559. return null;
  9560. },
  9561. /**
  9562. * Create the Axis instances based on the config options
  9563. */
  9564. getAxes: function () {
  9565. var chart = this,
  9566. options = this.options,
  9567. xAxisOptions = options.xAxis = splat(options.xAxis || {}),
  9568. yAxisOptions = options.yAxis = splat(options.yAxis || {}),
  9569. optionsArray,
  9570. axis;
  9571. // make sure the options are arrays and add some members
  9572. each(xAxisOptions, function (axis, i) {
  9573. axis.index = i;
  9574. axis.isX = true;
  9575. });
  9576. each(yAxisOptions, function (axis, i) {
  9577. axis.index = i;
  9578. });
  9579. // concatenate all axis options into one array
  9580. optionsArray = xAxisOptions.concat(yAxisOptions);
  9581. each(optionsArray, function (axisOptions) {
  9582. axis = new Axis(chart, axisOptions);
  9583. });
  9584. chart.adjustTickAmounts();
  9585. },
  9586. /**
  9587. * Get the currently selected points from all series
  9588. */
  9589. getSelectedPoints: function () {
  9590. var points = [];
  9591. each(this.series, function (serie) {
  9592. points = points.concat(grep(serie.points || [], function (point) {
  9593. return point.selected;
  9594. }));
  9595. });
  9596. return points;
  9597. },
  9598. /**
  9599. * Get the currently selected series
  9600. */
  9601. getSelectedSeries: function () {
  9602. return grep(this.series, function (serie) {
  9603. return serie.selected;
  9604. });
  9605. },
  9606. /**
  9607. * Generate stacks for each series and calculate stacks total values
  9608. */
  9609. getStacks: function () {
  9610. var chart = this;
  9611. // reset stacks for each yAxis
  9612. each(chart.yAxis, function (axis) {
  9613. if (axis.stacks && axis.hasVisibleSeries) {
  9614. axis.oldStacks = axis.stacks;
  9615. }
  9616. });
  9617. each(chart.series, function (series) {
  9618. if (series.options.stacking && (series.visible === true || chart.options.chart.ignoreHiddenSeries === false)) {
  9619. series.stackKey = series.type + pick(series.options.stack, '');
  9620. }
  9621. });
  9622. },
  9623. /**
  9624. * Show the title and subtitle of the chart
  9625. *
  9626. * @param titleOptions {Object} New title options
  9627. * @param subtitleOptions {Object} New subtitle options
  9628. *
  9629. */
  9630. setTitle: function (titleOptions, subtitleOptions, redraw) {
  9631. var chart = this,
  9632. options = chart.options,
  9633. chartTitleOptions,
  9634. chartSubtitleOptions;
  9635. chartTitleOptions = options.title = merge(options.title, titleOptions);
  9636. chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions);
  9637. // add title and subtitle
  9638. each([
  9639. ['title', titleOptions, chartTitleOptions],
  9640. ['subtitle', subtitleOptions, chartSubtitleOptions]
  9641. ], function (arr) {
  9642. var name = arr[0],
  9643. title = chart[name],
  9644. titleOptions = arr[1],
  9645. chartTitleOptions = arr[2];
  9646. if (title && titleOptions) {
  9647. chart[name] = title = title.destroy(); // remove old
  9648. }
  9649. if (chartTitleOptions && chartTitleOptions.text && !title) {
  9650. chart[name] = chart.renderer.text(
  9651. chartTitleOptions.text,
  9652. 0,
  9653. 0,
  9654. chartTitleOptions.useHTML
  9655. )
  9656. .attr({
  9657. align: chartTitleOptions.align,
  9658. 'class': PREFIX + name,
  9659. zIndex: chartTitleOptions.zIndex || 4
  9660. })
  9661. .css(chartTitleOptions.style)
  9662. .add();
  9663. }
  9664. });
  9665. chart.layOutTitles(redraw);
  9666. },
  9667. /**
  9668. * Lay out the chart titles and cache the full offset height for use in getMargins
  9669. */
  9670. layOutTitles: function (redraw) {
  9671. var titleOffset = 0,
  9672. title = this.title,
  9673. subtitle = this.subtitle,
  9674. options = this.options,
  9675. titleOptions = options.title,
  9676. subtitleOptions = options.subtitle,
  9677. requiresDirtyBox,
  9678. autoWidth = this.spacingBox.width - 44; // 44 makes room for default context button
  9679. if (title) {
  9680. title
  9681. .css({ width: (titleOptions.width || autoWidth) + PX })
  9682. .align(extend({ y: 15 }, titleOptions), false, 'spacingBox');
  9683. if (!titleOptions.floating && !titleOptions.verticalAlign) {
  9684. titleOffset = title.getBBox().height;
  9685. }
  9686. }
  9687. if (subtitle) {
  9688. subtitle
  9689. .css({ width: (subtitleOptions.width || autoWidth) + PX })
  9690. .align(extend({ y: titleOffset + titleOptions.margin }, subtitleOptions), false, 'spacingBox');
  9691. if (!subtitleOptions.floating && !subtitleOptions.verticalAlign) {
  9692. titleOffset = mathCeil(titleOffset + subtitle.getBBox().height);
  9693. }
  9694. }
  9695. requiresDirtyBox = this.titleOffset !== titleOffset;
  9696. this.titleOffset = titleOffset; // used in getMargins
  9697. if (!this.isDirtyBox && requiresDirtyBox) {
  9698. this.isDirtyBox = requiresDirtyBox;
  9699. // Redraw if necessary (#2719, #2744)
  9700. if (this.hasRendered && pick(redraw, true) && this.isDirtyBox) {
  9701. this.redraw();
  9702. }
  9703. }
  9704. },
  9705. /**
  9706. * Get chart width and height according to options and container size
  9707. */
  9708. getChartSize: function () {
  9709. var chart = this,
  9710. optionsChart = chart.options.chart,
  9711. widthOption = optionsChart.width,
  9712. heightOption = optionsChart.height,
  9713. renderTo = chart.renderToClone || chart.renderTo;
  9714. // get inner width and height from jQuery (#824)
  9715. if (!defined(widthOption)) {
  9716. chart.containerWidth = adapterRun(renderTo, 'width');
  9717. }
  9718. if (!defined(heightOption)) {
  9719. chart.containerHeight = adapterRun(renderTo, 'height');
  9720. }
  9721. chart.chartWidth = mathMax(0, widthOption || chart.containerWidth || 600); // #1393, 1460
  9722. chart.chartHeight = mathMax(0, pick(heightOption,
  9723. // the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7:
  9724. chart.containerHeight > 19 ? chart.containerHeight : 400));
  9725. },
  9726. /**
  9727. * Create a clone of the chart's renderTo div and place it outside the viewport to allow
  9728. * size computation on chart.render and chart.redraw
  9729. */
  9730. cloneRenderTo: function (revert) {
  9731. var clone = this.renderToClone,
  9732. container = this.container;
  9733. // Destroy the clone and bring the container back to the real renderTo div
  9734. if (revert) {
  9735. if (clone) {
  9736. this.renderTo.appendChild(container);
  9737. discardElement(clone);
  9738. delete this.renderToClone;
  9739. }
  9740. // Set up the clone
  9741. } else {
  9742. if (container && container.parentNode === this.renderTo) {
  9743. this.renderTo.removeChild(container); // do not clone this
  9744. }
  9745. this.renderToClone = clone = this.renderTo.cloneNode(0);
  9746. css(clone, {
  9747. position: ABSOLUTE,
  9748. top: '-9999px',
  9749. display: 'block' // #833
  9750. });
  9751. if (clone.style.setProperty) { // #2631
  9752. clone.style.setProperty('display', 'block', 'important');
  9753. }
  9754. doc.body.appendChild(clone);
  9755. if (container) {
  9756. clone.appendChild(container);
  9757. }
  9758. }
  9759. },
  9760. /**
  9761. * Get the containing element, determine the size and create the inner container
  9762. * div to hold the chart
  9763. */
  9764. getContainer: function () {
  9765. var chart = this,
  9766. container,
  9767. optionsChart = chart.options.chart,
  9768. chartWidth,
  9769. chartHeight,
  9770. renderTo,
  9771. indexAttrName = 'data-highcharts-chart',
  9772. oldChartIndex,
  9773. containerId;
  9774. chart.renderTo = renderTo = optionsChart.renderTo;
  9775. containerId = PREFIX + idCounter++;
  9776. if (isString(renderTo)) {
  9777. chart.renderTo = renderTo = doc.getElementById(renderTo);
  9778. }
  9779. // Display an error if the renderTo is wrong
  9780. if (!renderTo) {
  9781. error(13, true);
  9782. }
  9783. // If the container already holds a chart, destroy it. The check for hasRendered is there
  9784. // because web pages that are saved to disk from the browser, will preserve the data-highcharts-chart
  9785. // attribute and the SVG contents, but not an interactive chart. So in this case,
  9786. // charts[oldChartIndex] will point to the wrong chart if any (#2609).
  9787. oldChartIndex = pInt(attr(renderTo, indexAttrName));
  9788. if (!isNaN(oldChartIndex) && charts[oldChartIndex] && charts[oldChartIndex].hasRendered) {
  9789. charts[oldChartIndex].destroy();
  9790. }
  9791. // Make a reference to the chart from the div
  9792. attr(renderTo, indexAttrName, chart.index);
  9793. // remove previous chart
  9794. renderTo.innerHTML = '';
  9795. // If the container doesn't have an offsetWidth, it has or is a child of a node
  9796. // that has display:none. We need to temporarily move it out to a visible
  9797. // state to determine the size, else the legend and tooltips won't render
  9798. // properly. The allowClone option is used in sparklines as a micro optimization,
  9799. // saving about 1-2 ms each chart.
  9800. if (!optionsChart.skipClone && !renderTo.offsetWidth) {
  9801. chart.cloneRenderTo();
  9802. }
  9803. // get the width and height
  9804. chart.getChartSize();
  9805. chartWidth = chart.chartWidth;
  9806. chartHeight = chart.chartHeight;
  9807. // create the inner container
  9808. chart.container = container = createElement(DIV, {
  9809. className: PREFIX + 'container' +
  9810. (optionsChart.className ? ' ' + optionsChart.className : ''),
  9811. id: containerId
  9812. }, extend({
  9813. position: RELATIVE,
  9814. overflow: HIDDEN, // needed for context menu (avoid scrollbars) and
  9815. // content overflow in IE
  9816. width: chartWidth + PX,
  9817. height: chartHeight + PX,
  9818. textAlign: 'left',
  9819. lineHeight: 'normal', // #427
  9820. zIndex: 0, // #1072
  9821. '-webkit-tap-highlight-color': 'rgba(0,0,0,0)'
  9822. }, optionsChart.style),
  9823. chart.renderToClone || renderTo
  9824. );
  9825. // cache the cursor (#1650)
  9826. chart._cursor = container.style.cursor;
  9827. // Initialize the renderer
  9828. chart.renderer =
  9829. optionsChart.forExport ? // force SVG, used for SVG export
  9830. new SVGRenderer(container, chartWidth, chartHeight, optionsChart.style, true) :
  9831. new Renderer(container, chartWidth, chartHeight, optionsChart.style);
  9832. if (useCanVG) {
  9833. // If we need canvg library, extend and configure the renderer
  9834. // to get the tracker for translating mouse events
  9835. chart.renderer.create(chart, container, chartWidth, chartHeight);
  9836. }
  9837. },
  9838. /**
  9839. * Calculate margins by rendering axis labels in a preliminary position. Title,
  9840. * subtitle and legend have already been rendered at this stage, but will be
  9841. * moved into their final positions
  9842. */
  9843. getMargins: function () {
  9844. var chart = this,
  9845. spacing = chart.spacing,
  9846. axisOffset,
  9847. legend = chart.legend,
  9848. margin = chart.margin,
  9849. legendOptions = chart.options.legend,
  9850. legendMargin = pick(legendOptions.margin, 20),
  9851. legendX = legendOptions.x,
  9852. legendY = legendOptions.y,
  9853. align = legendOptions.align,
  9854. verticalAlign = legendOptions.verticalAlign,
  9855. titleOffset = chart.titleOffset;
  9856. chart.resetMargins();
  9857. axisOffset = chart.axisOffset;
  9858. // Adjust for title and subtitle
  9859. if (titleOffset && !defined(margin[0])) {
  9860. chart.plotTop = mathMax(chart.plotTop, titleOffset + chart.options.title.margin + spacing[0]);
  9861. }
  9862. // Adjust for legend
  9863. if (legend.display && !legendOptions.floating) {
  9864. if (align === 'right') { // horizontal alignment handled first
  9865. if (!defined(margin[1])) {
  9866. chart.marginRight = mathMax(
  9867. chart.marginRight,
  9868. legend.legendWidth - legendX + legendMargin + spacing[1]
  9869. );
  9870. }
  9871. } else if (align === 'left') {
  9872. if (!defined(margin[3])) {
  9873. chart.plotLeft = mathMax(
  9874. chart.plotLeft,
  9875. legend.legendWidth + legendX + legendMargin + spacing[3]
  9876. );
  9877. }
  9878. } else if (verticalAlign === 'top') {
  9879. if (!defined(margin[0])) {
  9880. chart.plotTop = mathMax(
  9881. chart.plotTop,
  9882. legend.legendHeight + legendY + legendMargin + spacing[0]
  9883. );
  9884. }
  9885. } else if (verticalAlign === 'bottom') {
  9886. if (!defined(margin[2])) {
  9887. chart.marginBottom = mathMax(
  9888. chart.marginBottom,
  9889. legend.legendHeight - legendY + legendMargin + spacing[2]
  9890. );
  9891. }
  9892. }
  9893. }
  9894. // adjust for scroller
  9895. if (chart.extraBottomMargin) {
  9896. chart.marginBottom += chart.extraBottomMargin;
  9897. }
  9898. if (chart.extraTopMargin) {
  9899. chart.plotTop += chart.extraTopMargin;
  9900. }
  9901. // pre-render axes to get labels offset width
  9902. if (chart.hasCartesianSeries) {
  9903. each(chart.axes, function (axis) {
  9904. axis.getOffset();
  9905. });
  9906. }
  9907. if (!defined(margin[3])) {
  9908. chart.plotLeft += axisOffset[3];
  9909. }
  9910. if (!defined(margin[0])) {
  9911. chart.plotTop += axisOffset[0];
  9912. }
  9913. if (!defined(margin[2])) {
  9914. chart.marginBottom += axisOffset[2];
  9915. }
  9916. if (!defined(margin[1])) {
  9917. chart.marginRight += axisOffset[1];
  9918. }
  9919. chart.setChartSize();
  9920. },
  9921. /**
  9922. * Resize the chart to its container if size is not explicitly set
  9923. */
  9924. reflow: function (e) {
  9925. var chart = this,
  9926. optionsChart = chart.options.chart,
  9927. renderTo = chart.renderTo,
  9928. width = optionsChart.width || adapterRun(renderTo, 'width'),
  9929. height = optionsChart.height || adapterRun(renderTo, 'height'),
  9930. target = e ? e.target : win, // #805 - MooTools doesn't supply e
  9931. doReflow = function () {
  9932. if (chart.container) { // It may have been destroyed in the meantime (#1257)
  9933. chart.setSize(width, height, false);
  9934. chart.hasUserSize = null;
  9935. }
  9936. };
  9937. // Width and height checks for display:none. Target is doc in IE8 and Opera,
  9938. // win in Firefox, Chrome and IE9.
  9939. if (!chart.hasUserSize && width && height && (target === win || target === doc)) {
  9940. if (width !== chart.containerWidth || height !== chart.containerHeight) {
  9941. clearTimeout(chart.reflowTimeout);
  9942. if (e) { // Called from window.resize
  9943. chart.reflowTimeout = setTimeout(doReflow, 100);
  9944. } else { // Called directly (#2224)
  9945. doReflow();
  9946. }
  9947. }
  9948. chart.containerWidth = width;
  9949. chart.containerHeight = height;
  9950. }
  9951. },
  9952. /**
  9953. * Add the event handlers necessary for auto resizing
  9954. */
  9955. initReflow: function () {
  9956. var chart = this,
  9957. reflow = function (e) {
  9958. chart.reflow(e);
  9959. };
  9960. addEvent(win, 'resize', reflow);
  9961. addEvent(chart, 'destroy', function () {
  9962. removeEvent(win, 'resize', reflow);
  9963. });
  9964. },
  9965. /**
  9966. * Resize the chart to a given width and height
  9967. * @param {Number} width
  9968. * @param {Number} height
  9969. * @param {Object|Boolean} animation
  9970. */
  9971. setSize: function (width, height, animation) {
  9972. var chart = this,
  9973. chartWidth,
  9974. chartHeight,
  9975. fireEndResize;
  9976. // Handle the isResizing counter
  9977. chart.isResizing += 1;
  9978. fireEndResize = function () {
  9979. if (chart) {
  9980. fireEvent(chart, 'endResize', null, function () {
  9981. chart.isResizing -= 1;
  9982. });
  9983. }
  9984. };
  9985. // set the animation for the current process
  9986. setAnimation(animation, chart);
  9987. chart.oldChartHeight = chart.chartHeight;
  9988. chart.oldChartWidth = chart.chartWidth;
  9989. if (defined(width)) {
  9990. chart.chartWidth = chartWidth = mathMax(0, mathRound(width));
  9991. chart.hasUserSize = !!chartWidth;
  9992. }
  9993. if (defined(height)) {
  9994. chart.chartHeight = chartHeight = mathMax(0, mathRound(height));
  9995. }
  9996. // Resize the container with the global animation applied if enabled (#2503)
  9997. (globalAnimation ? animate : css)(chart.container, {
  9998. width: chartWidth + PX,
  9999. height: chartHeight + PX
  10000. }, globalAnimation);
  10001. chart.setChartSize(true);
  10002. chart.renderer.setSize(chartWidth, chartHeight, animation);
  10003. // handle axes
  10004. chart.maxTicks = null;
  10005. each(chart.axes, function (axis) {
  10006. axis.isDirty = true;
  10007. axis.setScale();
  10008. });
  10009. // make sure non-cartesian series are also handled
  10010. each(chart.series, function (serie) {
  10011. serie.isDirty = true;
  10012. });
  10013. chart.isDirtyLegend = true; // force legend redraw
  10014. chart.isDirtyBox = true; // force redraw of plot and chart border
  10015. chart.layOutTitles(); // #2857
  10016. chart.getMargins();
  10017. chart.redraw(animation);
  10018. chart.oldChartHeight = null;
  10019. fireEvent(chart, 'resize');
  10020. // fire endResize and set isResizing back
  10021. // If animation is disabled, fire without delay
  10022. if (globalAnimation === false) {
  10023. fireEndResize();
  10024. } else { // else set a timeout with the animation duration
  10025. setTimeout(fireEndResize, (globalAnimation && globalAnimation.duration) || 500);
  10026. }
  10027. },
  10028. /**
  10029. * Set the public chart properties. This is done before and after the pre-render
  10030. * to determine margin sizes
  10031. */
  10032. setChartSize: function (skipAxes) {
  10033. var chart = this,
  10034. inverted = chart.inverted,
  10035. renderer = chart.renderer,
  10036. chartWidth = chart.chartWidth,
  10037. chartHeight = chart.chartHeight,
  10038. optionsChart = chart.options.chart,
  10039. spacing = chart.spacing,
  10040. clipOffset = chart.clipOffset,
  10041. clipX,
  10042. clipY,
  10043. plotLeft,
  10044. plotTop,
  10045. plotWidth,
  10046. plotHeight,
  10047. plotBorderWidth;
  10048. chart.plotLeft = plotLeft = mathRound(chart.plotLeft);
  10049. chart.plotTop = plotTop = mathRound(chart.plotTop);
  10050. chart.plotWidth = plotWidth = mathMax(0, mathRound(chartWidth - plotLeft - chart.marginRight));
  10051. chart.plotHeight = plotHeight = mathMax(0, mathRound(chartHeight - plotTop - chart.marginBottom));
  10052. chart.plotSizeX = inverted ? plotHeight : plotWidth;
  10053. chart.plotSizeY = inverted ? plotWidth : plotHeight;
  10054. chart.plotBorderWidth = optionsChart.plotBorderWidth || 0;
  10055. // Set boxes used for alignment
  10056. chart.spacingBox = renderer.spacingBox = {
  10057. x: spacing[3],
  10058. y: spacing[0],
  10059. width: chartWidth - spacing[3] - spacing[1],
  10060. height: chartHeight - spacing[0] - spacing[2]
  10061. };
  10062. chart.plotBox = renderer.plotBox = {
  10063. x: plotLeft,
  10064. y: plotTop,
  10065. width: plotWidth,
  10066. height: plotHeight
  10067. };
  10068. plotBorderWidth = 2 * mathFloor(chart.plotBorderWidth / 2);
  10069. clipX = mathCeil(mathMax(plotBorderWidth, clipOffset[3]) / 2);
  10070. clipY = mathCeil(mathMax(plotBorderWidth, clipOffset[0]) / 2);
  10071. chart.clipBox = {
  10072. x: clipX,
  10073. y: clipY,
  10074. width: mathFloor(chart.plotSizeX - mathMax(plotBorderWidth, clipOffset[1]) / 2 - clipX),
  10075. height: mathFloor(chart.plotSizeY - mathMax(plotBorderWidth, clipOffset[2]) / 2 - clipY)
  10076. };
  10077. if (!skipAxes) {
  10078. each(chart.axes, function (axis) {
  10079. axis.setAxisSize();
  10080. axis.setAxisTranslation();
  10081. });
  10082. }
  10083. },
  10084. /**
  10085. * Initial margins before auto size margins are applied
  10086. */
  10087. resetMargins: function () {
  10088. var chart = this,
  10089. spacing = chart.spacing,
  10090. margin = chart.margin;
  10091. chart.plotTop = pick(margin[0], spacing[0]);
  10092. chart.marginRight = pick(margin[1], spacing[1]);
  10093. chart.marginBottom = pick(margin[2], spacing[2]);
  10094. chart.plotLeft = pick(margin[3], spacing[3]);
  10095. chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left
  10096. chart.clipOffset = [0, 0, 0, 0];
  10097. },
  10098. /**
  10099. * Draw the borders and backgrounds for chart and plot area
  10100. */
  10101. drawChartBox: function () {
  10102. var chart = this,
  10103. optionsChart = chart.options.chart,
  10104. renderer = chart.renderer,
  10105. chartWidth = chart.chartWidth,
  10106. chartHeight = chart.chartHeight,
  10107. chartBackground = chart.chartBackground,
  10108. plotBackground = chart.plotBackground,
  10109. plotBorder = chart.plotBorder,
  10110. plotBGImage = chart.plotBGImage,
  10111. chartBorderWidth = optionsChart.borderWidth || 0,
  10112. chartBackgroundColor = optionsChart.backgroundColor,
  10113. plotBackgroundColor = optionsChart.plotBackgroundColor,
  10114. plotBackgroundImage = optionsChart.plotBackgroundImage,
  10115. plotBorderWidth = optionsChart.plotBorderWidth || 0,
  10116. mgn,
  10117. bgAttr,
  10118. plotLeft = chart.plotLeft,
  10119. plotTop = chart.plotTop,
  10120. plotWidth = chart.plotWidth,
  10121. plotHeight = chart.plotHeight,
  10122. plotBox = chart.plotBox,
  10123. clipRect = chart.clipRect,
  10124. clipBox = chart.clipBox;
  10125. // Chart area
  10126. mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0);
  10127. if (chartBorderWidth || chartBackgroundColor) {
  10128. if (!chartBackground) {
  10129. bgAttr = {
  10130. fill: chartBackgroundColor || NONE
  10131. };
  10132. if (chartBorderWidth) { // #980
  10133. bgAttr.stroke = optionsChart.borderColor;
  10134. bgAttr['stroke-width'] = chartBorderWidth;
  10135. }
  10136. chart.chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn,
  10137. optionsChart.borderRadius, chartBorderWidth)
  10138. .attr(bgAttr)
  10139. .addClass(PREFIX + 'background')
  10140. .add()
  10141. .shadow(optionsChart.shadow);
  10142. } else { // resize
  10143. chartBackground.animate(
  10144. chartBackground.crisp({ width: chartWidth - mgn, height: chartHeight - mgn })
  10145. );
  10146. }
  10147. }
  10148. // Plot background
  10149. if (plotBackgroundColor) {
  10150. if (!plotBackground) {
  10151. chart.plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0)
  10152. .attr({
  10153. fill: plotBackgroundColor
  10154. })
  10155. .add()
  10156. .shadow(optionsChart.plotShadow);
  10157. } else {
  10158. plotBackground.animate(plotBox);
  10159. }
  10160. }
  10161. if (plotBackgroundImage) {
  10162. if (!plotBGImage) {
  10163. chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight)
  10164. .add();
  10165. } else {
  10166. plotBGImage.animate(plotBox);
  10167. }
  10168. }
  10169. // Plot clip
  10170. if (!clipRect) {
  10171. chart.clipRect = renderer.clipRect(clipBox);
  10172. } else {
  10173. clipRect.animate({
  10174. width: clipBox.width,
  10175. height: clipBox.height
  10176. });
  10177. }
  10178. // Plot area border
  10179. if (plotBorderWidth) {
  10180. if (!plotBorder) {
  10181. chart.plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, -plotBorderWidth)
  10182. .attr({
  10183. stroke: optionsChart.plotBorderColor,
  10184. 'stroke-width': plotBorderWidth,
  10185. fill: NONE,
  10186. zIndex: 1
  10187. })
  10188. .add();
  10189. } else {
  10190. plotBorder.animate(
  10191. plotBorder.crisp({ x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight })
  10192. );
  10193. }
  10194. }
  10195. // reset
  10196. chart.isDirtyBox = false;
  10197. },
  10198. /**
  10199. * Detect whether a certain chart property is needed based on inspecting its options
  10200. * and series. This mainly applies to the chart.invert property, and in extensions to
  10201. * the chart.angular and chart.polar properties.
  10202. */
  10203. propFromSeries: function () {
  10204. var chart = this,
  10205. optionsChart = chart.options.chart,
  10206. klass,
  10207. seriesOptions = chart.options.series,
  10208. i,
  10209. value;
  10210. each(['inverted', 'angular', 'polar'], function (key) {
  10211. // The default series type's class
  10212. klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType];
  10213. // Get the value from available chart-wide properties
  10214. value = (
  10215. chart[key] || // 1. it is set before
  10216. optionsChart[key] || // 2. it is set in the options
  10217. (klass && klass.prototype[key]) // 3. it's default series class requires it
  10218. );
  10219. // 4. Check if any the chart's series require it
  10220. i = seriesOptions && seriesOptions.length;
  10221. while (!value && i--) {
  10222. klass = seriesTypes[seriesOptions[i].type];
  10223. if (klass && klass.prototype[key]) {
  10224. value = true;
  10225. }
  10226. }
  10227. // Set the chart property
  10228. chart[key] = value;
  10229. });
  10230. },
  10231. /**
  10232. * Link two or more series together. This is done initially from Chart.render,
  10233. * and after Chart.addSeries and Series.remove.
  10234. */
  10235. linkSeries: function () {
  10236. var chart = this,
  10237. chartSeries = chart.series;
  10238. // Reset links
  10239. each(chartSeries, function (series) {
  10240. series.linkedSeries.length = 0;
  10241. });
  10242. // Apply new links
  10243. each(chartSeries, function (series) {
  10244. var linkedTo = series.options.linkedTo;
  10245. if (isString(linkedTo)) {
  10246. if (linkedTo === ':previous') {
  10247. linkedTo = chart.series[series.index - 1];
  10248. } else {
  10249. linkedTo = chart.get(linkedTo);
  10250. }
  10251. if (linkedTo) {
  10252. linkedTo.linkedSeries.push(series);
  10253. series.linkedParent = linkedTo;
  10254. }
  10255. }
  10256. });
  10257. },
  10258. /**
  10259. * Render series for the chart
  10260. */
  10261. renderSeries: function () {
  10262. each(this.series, function (serie) {
  10263. serie.translate();
  10264. if (serie.setTooltipPoints) {
  10265. serie.setTooltipPoints();
  10266. }
  10267. serie.render();
  10268. });
  10269. },
  10270. /**
  10271. * Render all graphics for the chart
  10272. */
  10273. render: function () {
  10274. var chart = this,
  10275. axes = chart.axes,
  10276. renderer = chart.renderer,
  10277. options = chart.options;
  10278. var labels = options.labels,
  10279. credits = options.credits,
  10280. creditsHref;
  10281. // Title
  10282. chart.setTitle();
  10283. // Legend
  10284. chart.legend = new Legend(chart, options.legend);
  10285. chart.getStacks(); // render stacks
  10286. // Get margins by pre-rendering axes
  10287. // set axes scales
  10288. each(axes, function (axis) {
  10289. axis.setScale();
  10290. });
  10291. chart.getMargins();
  10292. chart.maxTicks = null; // reset for second pass
  10293. each(axes, function (axis) {
  10294. axis.setTickPositions(true); // update to reflect the new margins
  10295. axis.setMaxTicks();
  10296. });
  10297. chart.adjustTickAmounts();
  10298. chart.getMargins(); // second pass to check for new labels
  10299. // Draw the borders and backgrounds
  10300. chart.drawChartBox();
  10301. // Axes
  10302. if (chart.hasCartesianSeries) {
  10303. each(axes, function (axis) {
  10304. axis.render();
  10305. });
  10306. }
  10307. // The series
  10308. if (!chart.seriesGroup) {
  10309. chart.seriesGroup = renderer.g('series-group')
  10310. .attr({ zIndex: 3 })
  10311. .add();
  10312. }
  10313. chart.renderSeries();
  10314. // Labels
  10315. if (labels.items) {
  10316. each(labels.items, function (label) {
  10317. var style = extend(labels.style, label.style),
  10318. x = pInt(style.left) + chart.plotLeft,
  10319. y = pInt(style.top) + chart.plotTop + 12;
  10320. // delete to prevent rewriting in IE
  10321. delete style.left;
  10322. delete style.top;
  10323. renderer.text(
  10324. label.html,
  10325. x,
  10326. y
  10327. )
  10328. .attr({ zIndex: 2 })
  10329. .css(style)
  10330. .add();
  10331. });
  10332. }
  10333. // Credits
  10334. if (credits.enabled && !chart.credits) {
  10335. creditsHref = credits.href;
  10336. chart.credits = renderer.text(
  10337. credits.text,
  10338. 0,
  10339. 0
  10340. )
  10341. .on('click', function () {
  10342. if (creditsHref) {
  10343. location.href = creditsHref;
  10344. }
  10345. })
  10346. .attr({
  10347. align: credits.position.align,
  10348. zIndex: 8
  10349. })
  10350. .css(credits.style)
  10351. .add()
  10352. .align(credits.position);
  10353. }
  10354. // Set flag
  10355. chart.hasRendered = true;
  10356. },
  10357. /**
  10358. * Clean up memory usage
  10359. */
  10360. destroy: function () {
  10361. var chart = this,
  10362. axes = chart.axes,
  10363. series = chart.series,
  10364. container = chart.container,
  10365. i,
  10366. parentNode = container && container.parentNode;
  10367. // fire the chart.destoy event
  10368. fireEvent(chart, 'destroy');
  10369. // Delete the chart from charts lookup array
  10370. charts[chart.index] = UNDEFINED;
  10371. chartCount--;
  10372. chart.renderTo.removeAttribute('data-highcharts-chart');
  10373. // remove events
  10374. removeEvent(chart);
  10375. // ==== Destroy collections:
  10376. // Destroy axes
  10377. i = axes.length;
  10378. while (i--) {
  10379. axes[i] = axes[i].destroy();
  10380. }
  10381. // Destroy each series
  10382. i = series.length;
  10383. while (i--) {
  10384. series[i] = series[i].destroy();
  10385. }
  10386. // ==== Destroy chart properties:
  10387. each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage',
  10388. 'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer', 'scroller',
  10389. 'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'], function (name) {
  10390. var prop = chart[name];
  10391. if (prop && prop.destroy) {
  10392. chart[name] = prop.destroy();
  10393. }
  10394. });
  10395. // remove container and all SVG
  10396. if (container) { // can break in IE when destroyed before finished loading
  10397. container.innerHTML = '';
  10398. removeEvent(container);
  10399. if (parentNode) {
  10400. discardElement(container);
  10401. }
  10402. }
  10403. // clean it all up
  10404. for (i in chart) {
  10405. delete chart[i];
  10406. }
  10407. },
  10408. /**
  10409. * VML namespaces can't be added until after complete. Listening
  10410. * for Perini's doScroll hack is not enough.
  10411. */
  10412. isReadyToRender: function () {
  10413. var chart = this;
  10414. // Note: in spite of JSLint's complaints, win == win.top is required
  10415. /*jslint eqeq: true*/
  10416. if ((!hasSVG && (win == win.top && doc.readyState !== 'complete')) || (useCanVG && !win.canvg)) {
  10417. /*jslint eqeq: false*/
  10418. if (useCanVG) {
  10419. // Delay rendering until canvg library is downloaded and ready
  10420. CanVGController.push(function () { chart.firstRender(); }, chart.options.global.canvasToolsURL);
  10421. } else {
  10422. doc.attachEvent('onreadystatechange', function () {
  10423. doc.detachEvent('onreadystatechange', chart.firstRender);
  10424. if (doc.readyState === 'complete') {
  10425. chart.firstRender();
  10426. }
  10427. });
  10428. }
  10429. return false;
  10430. }
  10431. return true;
  10432. },
  10433. /**
  10434. * Prepare for first rendering after all data are loaded
  10435. */
  10436. firstRender: function () {
  10437. var chart = this,
  10438. options = chart.options,
  10439. callback = chart.callback;
  10440. // Check whether the chart is ready to render
  10441. if (!chart.isReadyToRender()) {
  10442. return;
  10443. }
  10444. // Create the container
  10445. chart.getContainer();
  10446. // Run an early event after the container and renderer are established
  10447. fireEvent(chart, 'init');
  10448. chart.resetMargins();
  10449. chart.setChartSize();
  10450. // Set the common chart properties (mainly invert) from the given series
  10451. chart.propFromSeries();
  10452. // get axes
  10453. chart.getAxes();
  10454. // Initialize the series
  10455. each(options.series || [], function (serieOptions) {
  10456. chart.initSeries(serieOptions);
  10457. });
  10458. chart.linkSeries();
  10459. // Run an event after axes and series are initialized, but before render. At this stage,
  10460. // the series data is indexed and cached in the xData and yData arrays, so we can access
  10461. // those before rendering. Used in Highstock.
  10462. fireEvent(chart, 'beforeRender');
  10463. // depends on inverted and on margins being set
  10464. if (Highcharts.Pointer) {
  10465. chart.pointer = new Pointer(chart, options);
  10466. }
  10467. chart.render();
  10468. // add canvas
  10469. chart.renderer.draw();
  10470. // run callbacks
  10471. if (callback) {
  10472. callback.apply(chart, [chart]);
  10473. }
  10474. each(chart.callbacks, function (fn) {
  10475. fn.apply(chart, [chart]);
  10476. });
  10477. // If the chart was rendered outside the top container, put it back in
  10478. chart.cloneRenderTo(true);
  10479. fireEvent(chart, 'load');
  10480. },
  10481. /**
  10482. * Creates arrays for spacing and margin from given options.
  10483. */
  10484. splashArray: function (target, options) {
  10485. var oVar = options[target],
  10486. tArray = isObject(oVar) ? oVar : [oVar, oVar, oVar, oVar];
  10487. return [pick(options[target + 'Top'], tArray[0]),
  10488. pick(options[target + 'Right'], tArray[1]),
  10489. pick(options[target + 'Bottom'], tArray[2]),
  10490. pick(options[target + 'Left'], tArray[3])];
  10491. }
  10492. }; // end Chart
  10493. // Hook for exporting module
  10494. Chart.prototype.callbacks = [];
  10495. var CenteredSeriesMixin = Highcharts.CenteredSeriesMixin = {
  10496. /**
  10497. * Get the center of the pie based on the size and center options relative to the
  10498. * plot area. Borrowed by the polar and gauge series types.
  10499. */
  10500. getCenter: function () {
  10501. var options = this.options,
  10502. chart = this.chart,
  10503. slicingRoom = 2 * (options.slicedOffset || 0),
  10504. handleSlicingRoom,
  10505. plotWidth = chart.plotWidth - 2 * slicingRoom,
  10506. plotHeight = chart.plotHeight - 2 * slicingRoom,
  10507. centerOption = options.center,
  10508. positions = [pick(centerOption[0], '50%'), pick(centerOption[1], '50%'), options.size || '100%', options.innerSize || 0],
  10509. smallestSize = mathMin(plotWidth, plotHeight),
  10510. isPercent;
  10511. return map(positions, function (length, i) {
  10512. isPercent = /%$/.test(length);
  10513. handleSlicingRoom = i < 2 || (i === 2 && isPercent);
  10514. return (isPercent ?
  10515. // i == 0: centerX, relative to width
  10516. // i == 1: centerY, relative to height
  10517. // i == 2: size, relative to smallestSize
  10518. // i == 4: innerSize, relative to smallestSize
  10519. [plotWidth, plotHeight, smallestSize, smallestSize][i] *
  10520. pInt(length) / 100 :
  10521. length) + (handleSlicingRoom ? slicingRoom : 0);
  10522. });
  10523. }
  10524. };
  10525. /**
  10526. * The Point object and prototype. Inheritable and used as base for PiePoint
  10527. */
  10528. var Point = function () {};
  10529. Point.prototype = {
  10530. /**
  10531. * Initialize the point
  10532. * @param {Object} series The series object containing this point
  10533. * @param {Object} options The data in either number, array or object format
  10534. */
  10535. init: function (series, options, x) {
  10536. var point = this,
  10537. colors;
  10538. point.series = series;
  10539. point.applyOptions(options, x);
  10540. point.pointAttr = {};
  10541. if (series.options.colorByPoint) {
  10542. colors = series.options.colors || series.chart.options.colors;
  10543. point.color = point.color || colors[series.colorCounter++];
  10544. // loop back to zero
  10545. if (series.colorCounter === colors.length) {
  10546. series.colorCounter = 0;
  10547. }
  10548. }
  10549. series.chart.pointCount++;
  10550. return point;
  10551. },
  10552. /**
  10553. * Apply the options containing the x and y data and possible some extra properties.
  10554. * This is called on point init or from point.update.
  10555. *
  10556. * @param {Object} options
  10557. */
  10558. applyOptions: function (options, x) {
  10559. var point = this,
  10560. series = point.series,
  10561. pointValKey = series.pointValKey;
  10562. options = Point.prototype.optionsToObject.call(this, options);
  10563. // copy options directly to point
  10564. extend(point, options);
  10565. point.options = point.options ? extend(point.options, options) : options;
  10566. // For higher dimension series types. For instance, for ranges, point.y is mapped to point.low.
  10567. if (pointValKey) {
  10568. point.y = point[pointValKey];
  10569. }
  10570. // If no x is set by now, get auto incremented value. All points must have an
  10571. // x value, however the y value can be null to create a gap in the series
  10572. if (point.x === UNDEFINED && series) {
  10573. point.x = x === UNDEFINED ? series.autoIncrement() : x;
  10574. }
  10575. return point;
  10576. },
  10577. /**
  10578. * Transform number or array configs into objects
  10579. */
  10580. optionsToObject: function (options) {
  10581. var ret = {},
  10582. series = this.series,
  10583. pointArrayMap = series.pointArrayMap || ['y'],
  10584. valueCount = pointArrayMap.length,
  10585. firstItemType,
  10586. i = 0,
  10587. j = 0;
  10588. if (typeof options === 'number' || options === null) {
  10589. ret[pointArrayMap[0]] = options;
  10590. } else if (isArray(options)) {
  10591. // with leading x value
  10592. if (options.length > valueCount) {
  10593. firstItemType = typeof options[0];
  10594. if (firstItemType === 'string') {
  10595. ret.name = options[0];
  10596. } else if (firstItemType === 'number') {
  10597. ret.x = options[0];
  10598. }
  10599. i++;
  10600. }
  10601. while (j < valueCount) {
  10602. ret[pointArrayMap[j++]] = options[i++];
  10603. }
  10604. } else if (typeof options === 'object') {
  10605. ret = options;
  10606. // This is the fastest way to detect if there are individual point dataLabels that need
  10607. // to be considered in drawDataLabels. These can only occur in object configs.
  10608. if (options.dataLabels) {
  10609. series._hasPointLabels = true;
  10610. }
  10611. // Same approach as above for markers
  10612. if (options.marker) {
  10613. series._hasPointMarkers = true;
  10614. }
  10615. }
  10616. return ret;
  10617. },
  10618. /**
  10619. * Destroy a point to clear memory. Its reference still stays in series.data.
  10620. */
  10621. destroy: function () {
  10622. var point = this,
  10623. series = point.series,
  10624. chart = series.chart,
  10625. hoverPoints = chart.hoverPoints,
  10626. prop;
  10627. chart.pointCount--;
  10628. if (hoverPoints) {
  10629. point.setState();
  10630. erase(hoverPoints, point);
  10631. if (!hoverPoints.length) {
  10632. chart.hoverPoints = null;
  10633. }
  10634. }
  10635. if (point === chart.hoverPoint) {
  10636. point.onMouseOut();
  10637. }
  10638. // remove all events
  10639. if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive
  10640. removeEvent(point);
  10641. point.destroyElements();
  10642. }
  10643. if (point.legendItem) { // pies have legend items
  10644. chart.legend.destroyItem(point);
  10645. }
  10646. for (prop in point) {
  10647. point[prop] = null;
  10648. }
  10649. },
  10650. /**
  10651. * Destroy SVG elements associated with the point
  10652. */
  10653. destroyElements: function () {
  10654. var point = this,
  10655. props = ['graphic', 'dataLabel', 'dataLabelUpper', 'group', 'connector', 'shadowGroup'],
  10656. prop,
  10657. i = 6;
  10658. while (i--) {
  10659. prop = props[i];
  10660. if (point[prop]) {
  10661. point[prop] = point[prop].destroy();
  10662. }
  10663. }
  10664. },
  10665. /**
  10666. * Return the configuration hash needed for the data label and tooltip formatters
  10667. */
  10668. getLabelConfig: function () {
  10669. var point = this;
  10670. return {
  10671. x: point.category,
  10672. y: point.y,
  10673. key: point.name || point.category,
  10674. series: point.series,
  10675. point: point,
  10676. percentage: point.percentage,
  10677. total: point.total || point.stackTotal
  10678. };
  10679. },
  10680. /**
  10681. * Extendable method for formatting each point's tooltip line
  10682. *
  10683. * @return {String} A string to be concatenated in to the common tooltip text
  10684. */
  10685. tooltipFormatter: function (pointFormat) {
  10686. // Insert options for valueDecimals, valuePrefix, and valueSuffix
  10687. var series = this.series,
  10688. seriesTooltipOptions = series.tooltipOptions,
  10689. valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''),
  10690. valuePrefix = seriesTooltipOptions.valuePrefix || '',
  10691. valueSuffix = seriesTooltipOptions.valueSuffix || '';
  10692. // Loop over the point array map and replace unformatted values with sprintf formatting markup
  10693. each(series.pointArrayMap || ['y'], function (key) {
  10694. key = '{point.' + key; // without the closing bracket
  10695. if (valuePrefix || valueSuffix) {
  10696. pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix);
  10697. }
  10698. pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}');
  10699. });
  10700. return format(pointFormat, {
  10701. point: this,
  10702. series: this.series
  10703. });
  10704. },
  10705. /**
  10706. * Fire an event on the Point object. Must not be renamed to fireEvent, as this
  10707. * causes a name clash in MooTools
  10708. * @param {String} eventType
  10709. * @param {Object} eventArgs Additional event arguments
  10710. * @param {Function} defaultFunction Default event handler
  10711. */
  10712. firePointEvent: function (eventType, eventArgs, defaultFunction) {
  10713. var point = this,
  10714. series = this.series,
  10715. seriesOptions = series.options;
  10716. // load event handlers on demand to save time on mouseover/out
  10717. if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) {
  10718. this.importEvents();
  10719. }
  10720. // add default handler if in selection mode
  10721. if (eventType === 'click' && seriesOptions.allowPointSelect) {
  10722. defaultFunction = function (event) {
  10723. // Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera
  10724. point.select(null, event.ctrlKey || event.metaKey || event.shiftKey);
  10725. };
  10726. }
  10727. fireEvent(this, eventType, eventArgs, defaultFunction);
  10728. }
  10729. };/**
  10730. * @classDescription The base function which all other series types inherit from. The data in the series is stored
  10731. * in various arrays.
  10732. *
  10733. * - First, series.options.data contains all the original config options for
  10734. * each point whether added by options or methods like series.addPoint.
  10735. * - Next, series.data contains those values converted to points, but in case the series data length
  10736. * exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It
  10737. * only contains the points that have been created on demand.
  10738. * - Then there's series.points that contains all currently visible point objects. In case of cropping,
  10739. * the cropped-away points are not part of this array. The series.points array starts at series.cropStart
  10740. * compared to series.data and series.options.data. If however the series data is grouped, these can't
  10741. * be correlated one to one.
  10742. * - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points.
  10743. * - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points.
  10744. *
  10745. * @param {Object} chart
  10746. * @param {Object} options
  10747. */
  10748. var Series = function () {};
  10749. Series.prototype = {
  10750. isCartesian: true,
  10751. type: 'line',
  10752. pointClass: Point,
  10753. sorted: true, // requires the data to be sorted
  10754. requireSorting: true,
  10755. pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
  10756. stroke: 'lineColor',
  10757. 'stroke-width': 'lineWidth',
  10758. fill: 'fillColor',
  10759. r: 'radius'
  10760. },
  10761. axisTypes: ['xAxis', 'yAxis'],
  10762. colorCounter: 0,
  10763. parallelArrays: ['x', 'y'], // each point's x and y values are stored in this.xData and this.yData
  10764. init: function (chart, options) {
  10765. var series = this,
  10766. eventType,
  10767. events,
  10768. chartSeries = chart.series,
  10769. sortByIndex = function (a, b) {
  10770. return pick(a.options.index, a._i) - pick(b.options.index, b._i);
  10771. };
  10772. series.chart = chart;
  10773. series.options = options = series.setOptions(options); // merge with plotOptions
  10774. series.linkedSeries = [];
  10775. // bind the axes
  10776. series.bindAxes();
  10777. // set some variables
  10778. extend(series, {
  10779. name: options.name,
  10780. state: NORMAL_STATE,
  10781. pointAttr: {},
  10782. visible: options.visible !== false, // true by default
  10783. selected: options.selected === true // false by default
  10784. });
  10785. // special
  10786. if (useCanVG) {
  10787. options.animation = false;
  10788. }
  10789. // register event listeners
  10790. events = options.events;
  10791. for (eventType in events) {
  10792. addEvent(series, eventType, events[eventType]);
  10793. }
  10794. if (
  10795. (events && events.click) ||
  10796. (options.point && options.point.events && options.point.events.click) ||
  10797. options.allowPointSelect
  10798. ) {
  10799. chart.runTrackerClick = true;
  10800. }
  10801. series.getColor();
  10802. series.getSymbol();
  10803. // Set the data
  10804. each(series.parallelArrays, function (key) {
  10805. series[key + 'Data'] = [];
  10806. });
  10807. series.setData(options.data, false);
  10808. // Mark cartesian
  10809. if (series.isCartesian) {
  10810. chart.hasCartesianSeries = true;
  10811. }
  10812. // Register it in the chart
  10813. chartSeries.push(series);
  10814. series._i = chartSeries.length - 1;
  10815. // Sort series according to index option (#248, #1123, #2456)
  10816. stableSort(chartSeries, sortByIndex);
  10817. if (this.yAxis) {
  10818. stableSort(this.yAxis.series, sortByIndex);
  10819. }
  10820. each(chartSeries, function (series, i) {
  10821. series.index = i;
  10822. series.name = series.name || 'Series ' + (i + 1);
  10823. });
  10824. },
  10825. /**
  10826. * Set the xAxis and yAxis properties of cartesian series, and register the series
  10827. * in the axis.series array
  10828. */
  10829. bindAxes: function () {
  10830. var series = this,
  10831. seriesOptions = series.options,
  10832. chart = series.chart,
  10833. axisOptions;
  10834. each(series.axisTypes || [], function (AXIS) { // repeat for xAxis and yAxis
  10835. each(chart[AXIS], function (axis) { // loop through the chart's axis objects
  10836. axisOptions = axis.options;
  10837. // apply if the series xAxis or yAxis option mathches the number of the
  10838. // axis, or if undefined, use the first axis
  10839. if ((seriesOptions[AXIS] === axisOptions.index) ||
  10840. (seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) ||
  10841. (seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) {
  10842. // register this series in the axis.series lookup
  10843. axis.series.push(series);
  10844. // set this series.xAxis or series.yAxis reference
  10845. series[AXIS] = axis;
  10846. // mark dirty for redraw
  10847. axis.isDirty = true;
  10848. }
  10849. });
  10850. // The series needs an X and an Y axis
  10851. if (!series[AXIS] && series.optionalAxis !== AXIS) {
  10852. error(18, true);
  10853. }
  10854. });
  10855. },
  10856. /**
  10857. * For simple series types like line and column, the data values are held in arrays like
  10858. * xData and yData for quick lookup to find extremes and more. For multidimensional series
  10859. * like bubble and map, this can be extended with arrays like zData and valueData by
  10860. * adding to the series.parallelArrays array.
  10861. */
  10862. updateParallelArrays: function (point, i) {
  10863. var series = point.series,
  10864. args = arguments,
  10865. fn = typeof i === 'number' ?
  10866. // Insert the value in the given position
  10867. function (key) {
  10868. var val = key === 'y' && series.toYData ? series.toYData(point) : point[key];
  10869. series[key + 'Data'][i] = val;
  10870. } :
  10871. // Apply the method specified in i with the following arguments as arguments
  10872. function (key) {
  10873. Array.prototype[i].apply(series[key + 'Data'], Array.prototype.slice.call(args, 2));
  10874. };
  10875. each(series.parallelArrays, fn);
  10876. },
  10877. /**
  10878. * Return an auto incremented x value based on the pointStart and pointInterval options.
  10879. * This is only used if an x value is not given for the point that calls autoIncrement.
  10880. */
  10881. autoIncrement: function () {
  10882. var series = this,
  10883. options = series.options,
  10884. xIncrement = series.xIncrement;
  10885. xIncrement = pick(xIncrement, options.pointStart, 0);
  10886. series.pointInterval = pick(series.pointInterval, options.pointInterval, 1);
  10887. series.xIncrement = xIncrement + series.pointInterval;
  10888. return xIncrement;
  10889. },
  10890. /**
  10891. * Divide the series data into segments divided by null values.
  10892. */
  10893. getSegments: function () {
  10894. var series = this,
  10895. lastNull = -1,
  10896. segments = [],
  10897. i,
  10898. points = series.points,
  10899. pointsLength = points.length;
  10900. if (pointsLength) { // no action required for []
  10901. // if connect nulls, just remove null points
  10902. if (series.options.connectNulls) {
  10903. i = pointsLength;
  10904. while (i--) {
  10905. if (points[i].y === null) {
  10906. points.splice(i, 1);
  10907. }
  10908. }
  10909. if (points.length) {
  10910. segments = [points];
  10911. }
  10912. // else, split on null points
  10913. } else {
  10914. each(points, function (point, i) {
  10915. if (point.y === null) {
  10916. if (i > lastNull + 1) {
  10917. segments.push(points.slice(lastNull + 1, i));
  10918. }
  10919. lastNull = i;
  10920. } else if (i === pointsLength - 1) { // last value
  10921. segments.push(points.slice(lastNull + 1, i + 1));
  10922. }
  10923. });
  10924. }
  10925. }
  10926. // register it
  10927. series.segments = segments;
  10928. },
  10929. /**
  10930. * Set the series options by merging from the options tree
  10931. * @param {Object} itemOptions
  10932. */
  10933. setOptions: function (itemOptions) {
  10934. var chart = this.chart,
  10935. chartOptions = chart.options,
  10936. plotOptions = chartOptions.plotOptions,
  10937. userOptions = chart.userOptions || {},
  10938. userPlotOptions = userOptions.plotOptions || {},
  10939. typeOptions = plotOptions[this.type],
  10940. options;
  10941. this.userOptions = itemOptions;
  10942. options = merge(
  10943. typeOptions,
  10944. plotOptions.series,
  10945. itemOptions
  10946. );
  10947. // The tooltip options are merged between global and series specific options
  10948. this.tooltipOptions = merge(
  10949. defaultOptions.tooltip,
  10950. defaultOptions.plotOptions[this.type].tooltip,
  10951. userOptions.tooltip,
  10952. userPlotOptions.series && userPlotOptions.series.tooltip,
  10953. userPlotOptions[this.type] && userPlotOptions[this.type].tooltip,
  10954. itemOptions.tooltip
  10955. );
  10956. // Delete marker object if not allowed (#1125)
  10957. if (typeOptions.marker === null) {
  10958. delete options.marker;
  10959. }
  10960. return options;
  10961. },
  10962. /**
  10963. * Get the series' color
  10964. */
  10965. getColor: function () {
  10966. var options = this.options,
  10967. userOptions = this.userOptions,
  10968. defaultColors = this.chart.options.colors,
  10969. counters = this.chart.counters,
  10970. color,
  10971. colorIndex;
  10972. color = options.color || defaultPlotOptions[this.type].color;
  10973. if (!color && !options.colorByPoint) {
  10974. if (defined(userOptions._colorIndex)) { // after Series.update()
  10975. colorIndex = userOptions._colorIndex;
  10976. } else {
  10977. userOptions._colorIndex = counters.color;
  10978. colorIndex = counters.color++;
  10979. }
  10980. color = defaultColors[colorIndex];
  10981. }
  10982. this.color = color;
  10983. counters.wrapColor(defaultColors.length);
  10984. },
  10985. /**
  10986. * Get the series' symbol
  10987. */
  10988. getSymbol: function () {
  10989. var series = this,
  10990. userOptions = series.userOptions,
  10991. seriesMarkerOption = series.options.marker,
  10992. chart = series.chart,
  10993. defaultSymbols = chart.options.symbols,
  10994. counters = chart.counters,
  10995. symbolIndex;
  10996. series.symbol = seriesMarkerOption.symbol;
  10997. if (!series.symbol) {
  10998. if (defined(userOptions._symbolIndex)) { // after Series.update()
  10999. symbolIndex = userOptions._symbolIndex;
  11000. } else {
  11001. userOptions._symbolIndex = counters.symbol;
  11002. symbolIndex = counters.symbol++;
  11003. }
  11004. series.symbol = defaultSymbols[symbolIndex];
  11005. }
  11006. // don't substract radius in image symbols (#604)
  11007. if (/^url/.test(series.symbol)) {
  11008. seriesMarkerOption.radius = 0;
  11009. }
  11010. counters.wrapSymbol(defaultSymbols.length);
  11011. },
  11012. drawLegendSymbol: LegendSymbolMixin.drawLineMarker,
  11013. /**
  11014. * Replace the series data with a new set of data
  11015. * @param {Object} data
  11016. * @param {Object} redraw
  11017. */
  11018. setData: function (data, redraw, animation, updatePoints) {
  11019. var series = this,
  11020. oldData = series.points,
  11021. oldDataLength = (oldData && oldData.length) || 0,
  11022. dataLength,
  11023. options = series.options,
  11024. chart = series.chart,
  11025. firstPoint = null,
  11026. xAxis = series.xAxis,
  11027. hasCategories = xAxis && !!xAxis.categories,
  11028. tooltipPoints = series.tooltipPoints,
  11029. i,
  11030. turboThreshold = options.turboThreshold,
  11031. pt,
  11032. xData = this.xData,
  11033. yData = this.yData,
  11034. pointArrayMap = series.pointArrayMap,
  11035. valueCount = pointArrayMap && pointArrayMap.length;
  11036. data = data || [];
  11037. dataLength = data.length;
  11038. redraw = pick(redraw, true);
  11039. // If the point count is the same as is was, just run Point.update which is
  11040. // cheaper, allows animation, and keeps references to points.
  11041. if (updatePoints !== false && dataLength && oldDataLength === dataLength && !series.cropped && !series.hasGroupedData) {
  11042. each(data, function (point, i) {
  11043. oldData[i].update(point, false);
  11044. });
  11045. } else {
  11046. // Reset properties
  11047. series.xIncrement = null;
  11048. series.pointRange = hasCategories ? 1 : options.pointRange;
  11049. series.colorCounter = 0; // for series with colorByPoint (#1547)
  11050. // Update parallel arrays
  11051. each(this.parallelArrays, function (key) {
  11052. series[key + 'Data'].length = 0;
  11053. });
  11054. // In turbo mode, only one- or twodimensional arrays of numbers are allowed. The
  11055. // first value is tested, and we assume that all the rest are defined the same
  11056. // way. Although the 'for' loops are similar, they are repeated inside each
  11057. // if-else conditional for max performance.
  11058. if (turboThreshold && dataLength > turboThreshold) {
  11059. // find the first non-null point
  11060. i = 0;
  11061. while (firstPoint === null && i < dataLength) {
  11062. firstPoint = data[i];
  11063. i++;
  11064. }
  11065. if (isNumber(firstPoint)) { // assume all points are numbers
  11066. var x = pick(options.pointStart, 0),
  11067. pointInterval = pick(options.pointInterval, 1);
  11068. for (i = 0; i < dataLength; i++) {
  11069. xData[i] = x;
  11070. yData[i] = data[i];
  11071. x += pointInterval;
  11072. }
  11073. series.xIncrement = x;
  11074. } else if (isArray(firstPoint)) { // assume all points are arrays
  11075. if (valueCount) { // [x, low, high] or [x, o, h, l, c]
  11076. for (i = 0; i < dataLength; i++) {
  11077. pt = data[i];
  11078. xData[i] = pt[0];
  11079. yData[i] = pt.slice(1, valueCount + 1);
  11080. }
  11081. } else { // [x, y]
  11082. for (i = 0; i < dataLength; i++) {
  11083. pt = data[i];
  11084. xData[i] = pt[0];
  11085. yData[i] = pt[1];
  11086. }
  11087. }
  11088. } else {
  11089. error(12); // Highcharts expects configs to be numbers or arrays in turbo mode
  11090. }
  11091. } else {
  11092. for (i = 0; i < dataLength; i++) {
  11093. if (data[i] !== UNDEFINED) { // stray commas in oldIE
  11094. pt = { series: series };
  11095. series.pointClass.prototype.applyOptions.apply(pt, [data[i]]);
  11096. series.updateParallelArrays(pt, i);
  11097. if (hasCategories && pt.name) {
  11098. xAxis.names[pt.x] = pt.name; // #2046
  11099. }
  11100. }
  11101. }
  11102. }
  11103. // Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON
  11104. if (isString(yData[0])) {
  11105. error(14, true);
  11106. }
  11107. series.data = [];
  11108. series.options.data = data;
  11109. //series.zData = zData;
  11110. // destroy old points
  11111. i = oldDataLength;
  11112. while (i--) {
  11113. if (oldData[i] && oldData[i].destroy) {
  11114. oldData[i].destroy();
  11115. }
  11116. }
  11117. if (tooltipPoints) { // #2594
  11118. tooltipPoints.length = 0;
  11119. }
  11120. // reset minRange (#878)
  11121. if (xAxis) {
  11122. xAxis.minRange = xAxis.userMinRange;
  11123. }
  11124. // redraw
  11125. series.isDirty = series.isDirtyData = chart.isDirtyBox = true;
  11126. animation = false;
  11127. }
  11128. if (redraw) {
  11129. chart.redraw(animation);
  11130. }
  11131. },
  11132. /**
  11133. * Process the data by cropping away unused data points if the series is longer
  11134. * than the crop threshold. This saves computing time for lage series.
  11135. */
  11136. processData: function (force) {
  11137. var series = this,
  11138. processedXData = series.xData, // copied during slice operation below
  11139. processedYData = series.yData,
  11140. dataLength = processedXData.length,
  11141. croppedData,
  11142. cropStart = 0,
  11143. cropped,
  11144. distance,
  11145. closestPointRange,
  11146. xAxis = series.xAxis,
  11147. i, // loop variable
  11148. options = series.options,
  11149. cropThreshold = options.cropThreshold,
  11150. activePointCount = 0,
  11151. isCartesian = series.isCartesian,
  11152. min,
  11153. max;
  11154. // If the series data or axes haven't changed, don't go through this. Return false to pass
  11155. // the message on to override methods like in data grouping.
  11156. if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) {
  11157. return false;
  11158. }
  11159. // optionally filter out points outside the plot area
  11160. if (isCartesian && series.sorted && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) {
  11161. min = xAxis.min;
  11162. max = xAxis.max;
  11163. // it's outside current extremes
  11164. if (processedXData[dataLength - 1] < min || processedXData[0] > max) {
  11165. processedXData = [];
  11166. processedYData = [];
  11167. // only crop if it's actually spilling out
  11168. } else if (processedXData[0] < min || processedXData[dataLength - 1] > max) {
  11169. croppedData = this.cropData(series.xData, series.yData, min, max);
  11170. processedXData = croppedData.xData;
  11171. processedYData = croppedData.yData;
  11172. cropStart = croppedData.start;
  11173. cropped = true;
  11174. activePointCount = processedXData.length;
  11175. }
  11176. }
  11177. // Find the closest distance between processed points
  11178. for (i = processedXData.length - 1; i >= 0; i--) {
  11179. distance = processedXData[i] - processedXData[i - 1];
  11180. if (!cropped && processedXData[i] > min && processedXData[i] < max) {
  11181. activePointCount++;
  11182. }
  11183. if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) {
  11184. closestPointRange = distance;
  11185. // Unsorted data is not supported by the line tooltip, as well as data grouping and
  11186. // navigation in Stock charts (#725) and width calculation of columns (#1900)
  11187. } else if (distance < 0 && series.requireSorting) {
  11188. error(15);
  11189. }
  11190. }
  11191. // Record the properties
  11192. series.cropped = cropped; // undefined or true
  11193. series.cropStart = cropStart;
  11194. series.processedXData = processedXData;
  11195. series.processedYData = processedYData;
  11196. series.activePointCount = activePointCount;
  11197. if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC
  11198. series.pointRange = closestPointRange || 1;
  11199. }
  11200. series.closestPointRange = closestPointRange;
  11201. },
  11202. /**
  11203. * Iterate over xData and crop values between min and max. Returns object containing crop start/end
  11204. * cropped xData with corresponding part of yData, dataMin and dataMax within the cropped range
  11205. */
  11206. cropData: function (xData, yData, min, max) {
  11207. var dataLength = xData.length,
  11208. cropStart = 0,
  11209. cropEnd = dataLength,
  11210. cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside
  11211. i;
  11212. // iterate up to find slice start
  11213. for (i = 0; i < dataLength; i++) {
  11214. if (xData[i] >= min) {
  11215. cropStart = mathMax(0, i - cropShoulder);
  11216. break;
  11217. }
  11218. }
  11219. // proceed to find slice end
  11220. for (; i < dataLength; i++) {
  11221. if (xData[i] > max) {
  11222. cropEnd = i + cropShoulder;
  11223. break;
  11224. }
  11225. }
  11226. return {
  11227. xData: xData.slice(cropStart, cropEnd),
  11228. yData: yData.slice(cropStart, cropEnd),
  11229. start: cropStart,
  11230. end: cropEnd
  11231. };
  11232. },
  11233. /**
  11234. * Generate the data point after the data has been processed by cropping away
  11235. * unused points and optionally grouped in Highcharts Stock.
  11236. */
  11237. generatePoints: function () {
  11238. var series = this,
  11239. options = series.options,
  11240. dataOptions = options.data,
  11241. data = series.data,
  11242. dataLength,
  11243. processedXData = series.processedXData,
  11244. processedYData = series.processedYData,
  11245. pointClass = series.pointClass,
  11246. processedDataLength = processedXData.length,
  11247. cropStart = series.cropStart || 0,
  11248. cursor,
  11249. hasGroupedData = series.hasGroupedData,
  11250. point,
  11251. points = [],
  11252. i;
  11253. if (!data && !hasGroupedData) {
  11254. var arr = [];
  11255. arr.length = dataOptions.length;
  11256. data = series.data = arr;
  11257. }
  11258. for (i = 0; i < processedDataLength; i++) {
  11259. cursor = cropStart + i;
  11260. if (!hasGroupedData) {
  11261. if (data[cursor]) {
  11262. point = data[cursor];
  11263. } else if (dataOptions[cursor] !== UNDEFINED) { // #970
  11264. data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]);
  11265. }
  11266. points[i] = point;
  11267. } else {
  11268. // splat the y data in case of ohlc data array
  11269. points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i])));
  11270. }
  11271. }
  11272. // Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when
  11273. // swithching view from non-grouped data to grouped data (#637)
  11274. if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) {
  11275. for (i = 0; i < dataLength; i++) {
  11276. if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points
  11277. i += processedDataLength;
  11278. }
  11279. if (data[i]) {
  11280. data[i].destroyElements();
  11281. data[i].plotX = UNDEFINED; // #1003
  11282. }
  11283. }
  11284. }
  11285. series.data = data;
  11286. series.points = points;
  11287. },
  11288. /**
  11289. * Calculate Y extremes for visible data
  11290. */
  11291. getExtremes: function (yData) {
  11292. var xAxis = this.xAxis,
  11293. yAxis = this.yAxis,
  11294. xData = this.processedXData,
  11295. yDataLength,
  11296. activeYData = [],
  11297. activeCounter = 0,
  11298. xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis
  11299. xMin = xExtremes.min,
  11300. xMax = xExtremes.max,
  11301. validValue,
  11302. withinRange,
  11303. dataMin,
  11304. dataMax,
  11305. x,
  11306. y,
  11307. i,
  11308. j;
  11309. yData = yData || this.stackedYData || this.processedYData;
  11310. yDataLength = yData.length;
  11311. for (i = 0; i < yDataLength; i++) {
  11312. x = xData[i];
  11313. y = yData[i];
  11314. // For points within the visible range, including the first point outside the
  11315. // visible range, consider y extremes
  11316. validValue = y !== null && y !== UNDEFINED && (!yAxis.isLog || (y.length || y > 0));
  11317. withinRange = this.getExtremesFromAll || this.cropped || ((xData[i + 1] || x) >= xMin &&
  11318. (xData[i - 1] || x) <= xMax);
  11319. if (validValue && withinRange) {
  11320. j = y.length;
  11321. if (j) { // array, like ohlc or range data
  11322. while (j--) {
  11323. if (y[j] !== null) {
  11324. activeYData[activeCounter++] = y[j];
  11325. }
  11326. }
  11327. } else {
  11328. activeYData[activeCounter++] = y;
  11329. }
  11330. }
  11331. }
  11332. this.dataMin = pick(dataMin, arrayMin(activeYData));
  11333. this.dataMax = pick(dataMax, arrayMax(activeYData));
  11334. },
  11335. /**
  11336. * Translate data points from raw data values to chart specific positioning data
  11337. * needed later in drawPoints, drawGraph and drawTracker.
  11338. */
  11339. translate: function () {
  11340. if (!this.processedXData) { // hidden series
  11341. this.processData();
  11342. }
  11343. this.generatePoints();
  11344. var series = this,
  11345. options = series.options,
  11346. stacking = options.stacking,
  11347. xAxis = series.xAxis,
  11348. categories = xAxis.categories,
  11349. yAxis = series.yAxis,
  11350. points = series.points,
  11351. dataLength = points.length,
  11352. hasModifyValue = !!series.modifyValue,
  11353. i,
  11354. pointPlacement = options.pointPlacement,
  11355. dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement),
  11356. threshold = options.threshold;
  11357. // Translate each point
  11358. for (i = 0; i < dataLength; i++) {
  11359. var point = points[i],
  11360. xValue = point.x,
  11361. yValue = point.y,
  11362. yBottom = point.low,
  11363. stack = stacking && yAxis.stacks[(series.negStacks && yValue < threshold ? '-' : '') + series.stackKey],
  11364. pointStack,
  11365. stackValues;
  11366. // Discard disallowed y values for log axes
  11367. if (yAxis.isLog && yValue <= 0) {
  11368. point.y = yValue = null;
  11369. }
  11370. // Get the plotX translation
  11371. point.plotX = xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags'); // Math.round fixes #591
  11372. // Calculate the bottom y value for stacked series
  11373. if (stacking && series.visible && stack && stack[xValue]) {
  11374. pointStack = stack[xValue];
  11375. stackValues = pointStack.points[series.index + ',' + i];
  11376. yBottom = stackValues[0];
  11377. yValue = stackValues[1];
  11378. if (yBottom === 0) {
  11379. yBottom = pick(threshold, yAxis.min);
  11380. }
  11381. if (yAxis.isLog && yBottom <= 0) { // #1200, #1232
  11382. yBottom = null;
  11383. }
  11384. point.total = point.stackTotal = pointStack.total;
  11385. point.percentage = pointStack.total && (point.y / pointStack.total * 100);
  11386. point.stackY = yValue;
  11387. // Place the stack label
  11388. pointStack.setOffset(series.pointXOffset || 0, series.barW || 0);
  11389. }
  11390. // Set translated yBottom or remove it
  11391. point.yBottom = defined(yBottom) ?
  11392. yAxis.translate(yBottom, 0, 1, 0, 1) :
  11393. null;
  11394. // general hook, used for Highstock compare mode
  11395. if (hasModifyValue) {
  11396. yValue = series.modifyValue(yValue, point);
  11397. }
  11398. // Set the the plotY value, reset it for redraws
  11399. point.plotY = (typeof yValue === 'number' && yValue !== Infinity) ?
  11400. //mathRound(yAxis.translate(yValue, 0, 1, 0, 1) * 10) / 10 : // Math.round fixes #591
  11401. yAxis.translate(yValue, 0, 1, 0, 1) :
  11402. UNDEFINED;
  11403. // Set client related positions for mouse tracking
  11404. point.clientX = dynamicallyPlaced ? xAxis.translate(xValue, 0, 0, 0, 1) : point.plotX; // #1514
  11405. point.negative = point.y < (threshold || 0);
  11406. // some API data
  11407. point.category = categories && categories[point.x] !== UNDEFINED ?
  11408. categories[point.x] : point.x;
  11409. }
  11410. // now that we have the cropped data, build the segments
  11411. series.getSegments();
  11412. },
  11413. /**
  11414. * Animate in the series
  11415. */
  11416. animate: function (init) {
  11417. var series = this,
  11418. chart = series.chart,
  11419. renderer = chart.renderer,
  11420. clipRect,
  11421. markerClipRect,
  11422. animation = series.options.animation,
  11423. clipBox = series.clipBox || chart.clipBox,
  11424. inverted = chart.inverted,
  11425. sharedClipKey;
  11426. // Animation option is set to true
  11427. if (animation && !isObject(animation)) {
  11428. animation = defaultPlotOptions[series.type].animation;
  11429. }
  11430. sharedClipKey = ['_sharedClip', animation.duration, animation.easing, clipBox.height].join(',');
  11431. // Initialize the animation. Set up the clipping rectangle.
  11432. if (init) {
  11433. // If a clipping rectangle with the same properties is currently present in the chart, use that.
  11434. clipRect = chart[sharedClipKey];
  11435. markerClipRect = chart[sharedClipKey + 'm'];
  11436. if (!clipRect) {
  11437. chart[sharedClipKey] = clipRect = renderer.clipRect(
  11438. extend(clipBox, { width: 0 })
  11439. );
  11440. chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect(
  11441. -99, // include the width of the first marker
  11442. inverted ? -chart.plotLeft : -chart.plotTop,
  11443. 99,
  11444. inverted ? chart.chartWidth : chart.chartHeight
  11445. );
  11446. }
  11447. series.group.clip(clipRect);
  11448. series.markerGroup.clip(markerClipRect);
  11449. series.sharedClipKey = sharedClipKey;
  11450. // Run the animation
  11451. } else {
  11452. clipRect = chart[sharedClipKey];
  11453. if (clipRect) {
  11454. clipRect.animate({
  11455. width: chart.plotSizeX
  11456. }, animation);
  11457. }
  11458. if (chart[sharedClipKey + 'm']) {
  11459. chart[sharedClipKey + 'm'].animate({
  11460. width: chart.plotSizeX + 99
  11461. }, animation);
  11462. }
  11463. // Delete this function to allow it only once
  11464. series.animate = null;
  11465. }
  11466. },
  11467. /**
  11468. * This runs after animation to land on the final plot clipping
  11469. */
  11470. afterAnimate: function () {
  11471. var chart = this.chart,
  11472. sharedClipKey = this.sharedClipKey,
  11473. group = this.group,
  11474. clipBox = this.clipBox;
  11475. if (group && this.options.clip !== false) {
  11476. if (!sharedClipKey || !clipBox) {
  11477. group.clip(clipBox ? chart.renderer.clipRect(clipBox) : chart.clipRect);
  11478. }
  11479. this.markerGroup.clip(); // no clip
  11480. }
  11481. fireEvent(this, 'afterAnimate');
  11482. // Remove the shared clipping rectancgle when all series are shown
  11483. setTimeout(function () {
  11484. if (sharedClipKey && chart[sharedClipKey]) {
  11485. if (!clipBox) {
  11486. chart[sharedClipKey] = chart[sharedClipKey].destroy();
  11487. }
  11488. if (chart[sharedClipKey + 'm']) {
  11489. chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy();
  11490. }
  11491. }
  11492. }, 100);
  11493. },
  11494. /**
  11495. * Draw the markers
  11496. */
  11497. drawPoints: function () {
  11498. var series = this,
  11499. pointAttr,
  11500. points = series.points,
  11501. chart = series.chart,
  11502. plotX,
  11503. plotY,
  11504. i,
  11505. point,
  11506. radius,
  11507. symbol,
  11508. isImage,
  11509. graphic,
  11510. options = series.options,
  11511. seriesMarkerOptions = options.marker,
  11512. seriesPointAttr = series.pointAttr[''],
  11513. pointMarkerOptions,
  11514. enabled,
  11515. isInside,
  11516. markerGroup = series.markerGroup,
  11517. globallyEnabled = pick(
  11518. seriesMarkerOptions.enabled,
  11519. series.activePointCount < (0.5 * series.xAxis.len / seriesMarkerOptions.radius)
  11520. );
  11521. if (seriesMarkerOptions.enabled !== false || series._hasPointMarkers) {
  11522. i = points.length;
  11523. while (i--) {
  11524. point = points[i];
  11525. plotX = mathFloor(point.plotX); // #1843
  11526. plotY = point.plotY;
  11527. graphic = point.graphic;
  11528. pointMarkerOptions = point.marker || {};
  11529. enabled = (globallyEnabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled;
  11530. isInside = chart.isInsidePlot(mathRound(plotX), plotY, chart.inverted); // #1858
  11531. // only draw the point if y is defined
  11532. if (enabled && plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) {
  11533. // shortcuts
  11534. pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || seriesPointAttr;
  11535. radius = pointAttr.r;
  11536. symbol = pick(pointMarkerOptions.symbol, series.symbol);
  11537. isImage = symbol.indexOf('url') === 0;
  11538. if (graphic) { // update
  11539. graphic[isInside ? 'show' : 'hide'](true) // Since the marker group isn't clipped, each individual marker must be toggled
  11540. .animate(extend({
  11541. x: plotX - radius,
  11542. y: plotY - radius
  11543. }, graphic.symbolName ? { // don't apply to image symbols #507
  11544. width: 2 * radius,
  11545. height: 2 * radius
  11546. } : {}));
  11547. } else if (isInside && (radius > 0 || isImage)) {
  11548. point.graphic = graphic = chart.renderer.symbol(
  11549. symbol,
  11550. plotX - radius,
  11551. plotY - radius,
  11552. 2 * radius,
  11553. 2 * radius
  11554. )
  11555. .attr(pointAttr)
  11556. .add(markerGroup);
  11557. }
  11558. } else if (graphic) {
  11559. point.graphic = graphic.destroy(); // #1269
  11560. }
  11561. }
  11562. }
  11563. },
  11564. /**
  11565. * Convert state properties from API naming conventions to SVG attributes
  11566. *
  11567. * @param {Object} options API options object
  11568. * @param {Object} base1 SVG attribute object to inherit from
  11569. * @param {Object} base2 Second level SVG attribute object to inherit from
  11570. */
  11571. convertAttribs: function (options, base1, base2, base3) {
  11572. var conversion = this.pointAttrToOptions,
  11573. attr,
  11574. option,
  11575. obj = {};
  11576. options = options || {};
  11577. base1 = base1 || {};
  11578. base2 = base2 || {};
  11579. base3 = base3 || {};
  11580. for (attr in conversion) {
  11581. option = conversion[attr];
  11582. obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]);
  11583. }
  11584. return obj;
  11585. },
  11586. /**
  11587. * Get the state attributes. Each series type has its own set of attributes
  11588. * that are allowed to change on a point's state change. Series wide attributes are stored for
  11589. * all series, and additionally point specific attributes are stored for all
  11590. * points with individual marker options. If such options are not defined for the point,
  11591. * a reference to the series wide attributes is stored in point.pointAttr.
  11592. */
  11593. getAttribs: function () {
  11594. var series = this,
  11595. seriesOptions = series.options,
  11596. normalOptions = defaultPlotOptions[series.type].marker ? seriesOptions.marker : seriesOptions,
  11597. stateOptions = normalOptions.states,
  11598. stateOptionsHover = stateOptions[HOVER_STATE],
  11599. pointStateOptionsHover,
  11600. seriesColor = series.color,
  11601. normalDefaults = {
  11602. stroke: seriesColor,
  11603. fill: seriesColor
  11604. },
  11605. points = series.points || [], // #927
  11606. i,
  11607. point,
  11608. seriesPointAttr = [],
  11609. pointAttr,
  11610. pointAttrToOptions = series.pointAttrToOptions,
  11611. hasPointSpecificOptions = series.hasPointSpecificOptions,
  11612. negativeColor = seriesOptions.negativeColor,
  11613. defaultLineColor = normalOptions.lineColor,
  11614. defaultFillColor = normalOptions.fillColor,
  11615. turboThreshold = seriesOptions.turboThreshold,
  11616. attr,
  11617. key;
  11618. // series type specific modifications
  11619. if (seriesOptions.marker) { // line, spline, area, areaspline, scatter
  11620. // if no hover radius is given, default to normal radius + 2
  11621. stateOptionsHover.radius = stateOptionsHover.radius || normalOptions.radius + 2;
  11622. stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + 1;
  11623. } else { // column, bar, pie
  11624. // if no hover color is given, brighten the normal color
  11625. stateOptionsHover.color = stateOptionsHover.color ||
  11626. Color(stateOptionsHover.color || seriesColor)
  11627. .brighten(stateOptionsHover.brightness).get();
  11628. }
  11629. // general point attributes for the series normal state
  11630. seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults);
  11631. // HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius
  11632. each([HOVER_STATE, SELECT_STATE], function (state) {
  11633. seriesPointAttr[state] =
  11634. series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]);
  11635. });
  11636. // set it
  11637. series.pointAttr = seriesPointAttr;
  11638. // Generate the point-specific attribute collections if specific point
  11639. // options are given. If not, create a referance to the series wide point
  11640. // attributes
  11641. i = points.length;
  11642. if (!turboThreshold || i < turboThreshold || hasPointSpecificOptions) {
  11643. while (i--) {
  11644. point = points[i];
  11645. normalOptions = (point.options && point.options.marker) || point.options;
  11646. if (normalOptions && normalOptions.enabled === false) {
  11647. normalOptions.radius = 0;
  11648. }
  11649. if (point.negative && negativeColor) {
  11650. point.color = point.fillColor = negativeColor;
  11651. }
  11652. hasPointSpecificOptions = seriesOptions.colorByPoint || point.color; // #868
  11653. // check if the point has specific visual options
  11654. if (point.options) {
  11655. for (key in pointAttrToOptions) {
  11656. if (defined(normalOptions[pointAttrToOptions[key]])) {
  11657. hasPointSpecificOptions = true;
  11658. }
  11659. }
  11660. }
  11661. // a specific marker config object is defined for the individual point:
  11662. // create it's own attribute collection
  11663. if (hasPointSpecificOptions) {
  11664. normalOptions = normalOptions || {};
  11665. pointAttr = [];
  11666. stateOptions = normalOptions.states || {}; // reassign for individual point
  11667. pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {};
  11668. // Handle colors for column and pies
  11669. if (!seriesOptions.marker) { // column, bar, point
  11670. // If no hover color is given, brighten the normal color. #1619, #2579
  11671. pointStateOptionsHover.color = pointStateOptionsHover.color || (!point.options.color && stateOptionsHover.color) ||
  11672. Color(point.color)
  11673. .brighten(pointStateOptionsHover.brightness || stateOptionsHover.brightness)
  11674. .get();
  11675. }
  11676. // normal point state inherits series wide normal state
  11677. attr = { color: point.color }; // #868
  11678. if (!defaultFillColor) { // Individual point color or negative color markers (#2219)
  11679. attr.fillColor = point.color;
  11680. }
  11681. if (!defaultLineColor) {
  11682. attr.lineColor = point.color; // Bubbles take point color, line markers use white
  11683. }
  11684. pointAttr[NORMAL_STATE] = series.convertAttribs(extend(attr, normalOptions), seriesPointAttr[NORMAL_STATE]);
  11685. // inherit from point normal and series hover
  11686. pointAttr[HOVER_STATE] = series.convertAttribs(
  11687. stateOptions[HOVER_STATE],
  11688. seriesPointAttr[HOVER_STATE],
  11689. pointAttr[NORMAL_STATE]
  11690. );
  11691. // inherit from point normal and series hover
  11692. pointAttr[SELECT_STATE] = series.convertAttribs(
  11693. stateOptions[SELECT_STATE],
  11694. seriesPointAttr[SELECT_STATE],
  11695. pointAttr[NORMAL_STATE]
  11696. );
  11697. // no marker config object is created: copy a reference to the series-wide
  11698. // attribute collection
  11699. } else {
  11700. pointAttr = seriesPointAttr;
  11701. }
  11702. point.pointAttr = pointAttr;
  11703. }
  11704. }
  11705. },
  11706. /**
  11707. * Clear DOM objects and free up memory
  11708. */
  11709. destroy: function () {
  11710. var series = this,
  11711. chart = series.chart,
  11712. issue134 = /AppleWebKit\/533/.test(userAgent),
  11713. destroy,
  11714. i,
  11715. data = series.data || [],
  11716. point,
  11717. prop,
  11718. axis;
  11719. // add event hook
  11720. fireEvent(series, 'destroy');
  11721. // remove all events
  11722. removeEvent(series);
  11723. // erase from axes
  11724. each(series.axisTypes || [], function (AXIS) {
  11725. axis = series[AXIS];
  11726. if (axis) {
  11727. erase(axis.series, series);
  11728. axis.isDirty = axis.forceRedraw = true;
  11729. }
  11730. });
  11731. // remove legend items
  11732. if (series.legendItem) {
  11733. series.chart.legend.destroyItem(series);
  11734. }
  11735. // destroy all points with their elements
  11736. i = data.length;
  11737. while (i--) {
  11738. point = data[i];
  11739. if (point && point.destroy) {
  11740. point.destroy();
  11741. }
  11742. }
  11743. series.points = null;
  11744. // Clear the animation timeout if we are destroying the series during initial animation
  11745. clearTimeout(series.animationTimeout);
  11746. // destroy all SVGElements associated to the series
  11747. each(['area', 'graph', 'dataLabelsGroup', 'group', 'markerGroup', 'tracker',
  11748. 'graphNeg', 'areaNeg', 'posClip', 'negClip'], function (prop) {
  11749. if (series[prop]) {
  11750. // issue 134 workaround
  11751. destroy = issue134 && prop === 'group' ?
  11752. 'hide' :
  11753. 'destroy';
  11754. series[prop][destroy]();
  11755. }
  11756. });
  11757. // remove from hoverSeries
  11758. if (chart.hoverSeries === series) {
  11759. chart.hoverSeries = null;
  11760. }
  11761. erase(chart.series, series);
  11762. // clear all members
  11763. for (prop in series) {
  11764. delete series[prop];
  11765. }
  11766. },
  11767. /**
  11768. * Return the graph path of a segment
  11769. */
  11770. getSegmentPath: function (segment) {
  11771. var series = this,
  11772. segmentPath = [],
  11773. step = series.options.step;
  11774. // build the segment line
  11775. each(segment, function (point, i) {
  11776. var plotX = point.plotX,
  11777. plotY = point.plotY,
  11778. lastPoint;
  11779. if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object
  11780. segmentPath.push.apply(segmentPath, series.getPointSpline(segment, point, i));
  11781. } else {
  11782. // moveTo or lineTo
  11783. segmentPath.push(i ? L : M);
  11784. // step line?
  11785. if (step && i) {
  11786. lastPoint = segment[i - 1];
  11787. if (step === 'right') {
  11788. segmentPath.push(
  11789. lastPoint.plotX,
  11790. plotY
  11791. );
  11792. } else if (step === 'center') {
  11793. segmentPath.push(
  11794. (lastPoint.plotX + plotX) / 2,
  11795. lastPoint.plotY,
  11796. (lastPoint.plotX + plotX) / 2,
  11797. plotY
  11798. );
  11799. } else {
  11800. segmentPath.push(
  11801. plotX,
  11802. lastPoint.plotY
  11803. );
  11804. }
  11805. }
  11806. // normal line to next point
  11807. segmentPath.push(
  11808. point.plotX,
  11809. point.plotY
  11810. );
  11811. }
  11812. });
  11813. return segmentPath;
  11814. },
  11815. /**
  11816. * Get the graph path
  11817. */
  11818. getGraphPath: function () {
  11819. var series = this,
  11820. graphPath = [],
  11821. segmentPath,
  11822. singlePoints = []; // used in drawTracker
  11823. // Divide into segments and build graph and area paths
  11824. each(series.segments, function (segment) {
  11825. segmentPath = series.getSegmentPath(segment);
  11826. // add the segment to the graph, or a single point for tracking
  11827. if (segment.length > 1) {
  11828. graphPath = graphPath.concat(segmentPath);
  11829. } else {
  11830. singlePoints.push(segment[0]);
  11831. }
  11832. });
  11833. // Record it for use in drawGraph and drawTracker, and return graphPath
  11834. series.singlePoints = singlePoints;
  11835. series.graphPath = graphPath;
  11836. return graphPath;
  11837. },
  11838. /**
  11839. * Draw the actual graph
  11840. */
  11841. drawGraph: function () {
  11842. var series = this,
  11843. options = this.options,
  11844. props = [['graph', options.lineColor || this.color]],
  11845. lineWidth = options.lineWidth,
  11846. dashStyle = options.dashStyle,
  11847. roundCap = options.linecap !== 'square',
  11848. graphPath = this.getGraphPath(),
  11849. negativeColor = options.negativeColor;
  11850. if (negativeColor) {
  11851. props.push(['graphNeg', negativeColor]);
  11852. }
  11853. // draw the graph
  11854. each(props, function (prop, i) {
  11855. var graphKey = prop[0],
  11856. graph = series[graphKey],
  11857. attribs;
  11858. if (graph) {
  11859. stop(graph); // cancel running animations, #459
  11860. graph.animate({ d: graphPath });
  11861. } else if (lineWidth && graphPath.length) { // #1487
  11862. attribs = {
  11863. stroke: prop[1],
  11864. 'stroke-width': lineWidth,
  11865. fill: NONE,
  11866. zIndex: 1 // #1069
  11867. };
  11868. if (dashStyle) {
  11869. attribs.dashstyle = dashStyle;
  11870. } else if (roundCap) {
  11871. attribs['stroke-linecap'] = attribs['stroke-linejoin'] = 'round';
  11872. }
  11873. series[graphKey] = series.chart.renderer.path(graphPath)
  11874. .attr(attribs)
  11875. .add(series.group)
  11876. .shadow(!i && options.shadow);
  11877. }
  11878. });
  11879. },
  11880. /**
  11881. * Clip the graphs into the positive and negative coloured graphs
  11882. */
  11883. clipNeg: function () {
  11884. var options = this.options,
  11885. chart = this.chart,
  11886. renderer = chart.renderer,
  11887. negativeColor = options.negativeColor || options.negativeFillColor,
  11888. translatedThreshold,
  11889. posAttr,
  11890. negAttr,
  11891. graph = this.graph,
  11892. area = this.area,
  11893. posClip = this.posClip,
  11894. negClip = this.negClip,
  11895. chartWidth = chart.chartWidth,
  11896. chartHeight = chart.chartHeight,
  11897. chartSizeMax = mathMax(chartWidth, chartHeight),
  11898. yAxis = this.yAxis,
  11899. above,
  11900. below;
  11901. if (negativeColor && (graph || area)) {
  11902. translatedThreshold = mathRound(yAxis.toPixels(options.threshold || 0, true));
  11903. if (translatedThreshold < 0) {
  11904. chartSizeMax -= translatedThreshold; // #2534
  11905. }
  11906. above = {
  11907. x: 0,
  11908. y: 0,
  11909. width: chartSizeMax,
  11910. height: translatedThreshold
  11911. };
  11912. below = {
  11913. x: 0,
  11914. y: translatedThreshold,
  11915. width: chartSizeMax,
  11916. height: chartSizeMax
  11917. };
  11918. if (chart.inverted) {
  11919. above.height = below.y = chart.plotWidth - translatedThreshold;
  11920. if (renderer.isVML) {
  11921. above = {
  11922. x: chart.plotWidth - translatedThreshold - chart.plotLeft,
  11923. y: 0,
  11924. width: chartWidth,
  11925. height: chartHeight
  11926. };
  11927. below = {
  11928. x: translatedThreshold + chart.plotLeft - chartWidth,
  11929. y: 0,
  11930. width: chart.plotLeft + translatedThreshold,
  11931. height: chartWidth
  11932. };
  11933. }
  11934. }
  11935. if (yAxis.reversed) {
  11936. posAttr = below;
  11937. negAttr = above;
  11938. } else {
  11939. posAttr = above;
  11940. negAttr = below;
  11941. }
  11942. if (posClip) { // update
  11943. posClip.animate(posAttr);
  11944. negClip.animate(negAttr);
  11945. } else {
  11946. this.posClip = posClip = renderer.clipRect(posAttr);
  11947. this.negClip = negClip = renderer.clipRect(negAttr);
  11948. if (graph && this.graphNeg) {
  11949. graph.clip(posClip);
  11950. this.graphNeg.clip(negClip);
  11951. }
  11952. if (area) {
  11953. area.clip(posClip);
  11954. this.areaNeg.clip(negClip);
  11955. }
  11956. }
  11957. }
  11958. },
  11959. /**
  11960. * Initialize and perform group inversion on series.group and series.markerGroup
  11961. */
  11962. invertGroups: function () {
  11963. var series = this,
  11964. chart = series.chart;
  11965. // Pie, go away (#1736)
  11966. if (!series.xAxis) {
  11967. return;
  11968. }
  11969. // A fixed size is needed for inversion to work
  11970. function setInvert() {
  11971. var size = {
  11972. width: series.yAxis.len,
  11973. height: series.xAxis.len
  11974. };
  11975. each(['group', 'markerGroup'], function (groupName) {
  11976. if (series[groupName]) {
  11977. series[groupName].attr(size).invert();
  11978. }
  11979. });
  11980. }
  11981. addEvent(chart, 'resize', setInvert); // do it on resize
  11982. addEvent(series, 'destroy', function () {
  11983. removeEvent(chart, 'resize', setInvert);
  11984. });
  11985. // Do it now
  11986. setInvert(); // do it now
  11987. // On subsequent render and redraw, just do setInvert without setting up events again
  11988. series.invertGroups = setInvert;
  11989. },
  11990. /**
  11991. * General abstraction for creating plot groups like series.group, series.dataLabelsGroup and
  11992. * series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size.
  11993. */
  11994. plotGroup: function (prop, name, visibility, zIndex, parent) {
  11995. var group = this[prop],
  11996. isNew = !group;
  11997. // Generate it on first call
  11998. if (isNew) {
  11999. this[prop] = group = this.chart.renderer.g(name)
  12000. .attr({
  12001. visibility: visibility,
  12002. zIndex: zIndex || 0.1 // IE8 needs this
  12003. })
  12004. .add(parent);
  12005. }
  12006. // Place it on first and subsequent (redraw) calls
  12007. group[isNew ? 'attr' : 'animate'](this.getPlotBox());
  12008. return group;
  12009. },
  12010. /**
  12011. * Get the translation and scale for the plot area of this series
  12012. */
  12013. getPlotBox: function () {
  12014. var chart = this.chart,
  12015. xAxis = this.xAxis,
  12016. yAxis = this.yAxis;
  12017. // Swap axes for inverted (#2339)
  12018. if (chart.inverted) {
  12019. xAxis = yAxis;
  12020. yAxis = this.xAxis;
  12021. }
  12022. return {
  12023. translateX: xAxis ? xAxis.left : chart.plotLeft,
  12024. translateY: yAxis ? yAxis.top : chart.plotTop,
  12025. scaleX: 1, // #1623
  12026. scaleY: 1
  12027. };
  12028. },
  12029. /**
  12030. * Render the graph and markers
  12031. */
  12032. render: function () {
  12033. var series = this,
  12034. chart = series.chart,
  12035. group,
  12036. options = series.options,
  12037. animation = options.animation,
  12038. // Animation doesn't work in IE8 quirks when the group div is hidden,
  12039. // and looks bad in other oldIE
  12040. animDuration = (animation && !!series.animate && chart.renderer.isSVG && pick(animation.duration, 500)) || 0,
  12041. visibility = series.visible ? VISIBLE : HIDDEN,
  12042. zIndex = options.zIndex,
  12043. hasRendered = series.hasRendered,
  12044. chartSeriesGroup = chart.seriesGroup;
  12045. // the group
  12046. group = series.plotGroup(
  12047. 'group',
  12048. 'series',
  12049. visibility,
  12050. zIndex,
  12051. chartSeriesGroup
  12052. );
  12053. series.markerGroup = series.plotGroup(
  12054. 'markerGroup',
  12055. 'markers',
  12056. visibility,
  12057. zIndex,
  12058. chartSeriesGroup
  12059. );
  12060. // initiate the animation
  12061. if (animDuration) {
  12062. series.animate(true);
  12063. }
  12064. // cache attributes for shapes
  12065. series.getAttribs();
  12066. // SVGRenderer needs to know this before drawing elements (#1089, #1795)
  12067. group.inverted = series.isCartesian ? chart.inverted : false;
  12068. // draw the graph if any
  12069. if (series.drawGraph) {
  12070. series.drawGraph();
  12071. series.clipNeg();
  12072. }
  12073. // draw the data labels (inn pies they go before the points)
  12074. if (series.drawDataLabels) {
  12075. series.drawDataLabels();
  12076. }
  12077. // draw the points
  12078. if (series.visible) {
  12079. series.drawPoints();
  12080. }
  12081. // draw the mouse tracking area
  12082. if (series.drawTracker && series.options.enableMouseTracking !== false) {
  12083. series.drawTracker();
  12084. }
  12085. // Handle inverted series and tracker groups
  12086. if (chart.inverted) {
  12087. series.invertGroups();
  12088. }
  12089. // Initial clipping, must be defined after inverting groups for VML
  12090. if (options.clip !== false && !series.sharedClipKey && !hasRendered) {
  12091. group.clip(chart.clipRect);
  12092. }
  12093. // Run the animation
  12094. if (animDuration) {
  12095. series.animate();
  12096. }
  12097. // Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option
  12098. // which should be available to the user).
  12099. if (!hasRendered) {
  12100. if (animDuration) {
  12101. series.animationTimeout = setTimeout(function () {
  12102. series.afterAnimate();
  12103. }, animDuration);
  12104. } else {
  12105. series.afterAnimate();
  12106. }
  12107. }
  12108. series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
  12109. // (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
  12110. series.hasRendered = true;
  12111. },
  12112. /**
  12113. * Redraw the series after an update in the axes.
  12114. */
  12115. redraw: function () {
  12116. var series = this,
  12117. chart = series.chart,
  12118. wasDirtyData = series.isDirtyData, // cache it here as it is set to false in render, but used after
  12119. group = series.group,
  12120. xAxis = series.xAxis,
  12121. yAxis = series.yAxis;
  12122. // reposition on resize
  12123. if (group) {
  12124. if (chart.inverted) {
  12125. group.attr({
  12126. width: chart.plotWidth,
  12127. height: chart.plotHeight
  12128. });
  12129. }
  12130. group.animate({
  12131. translateX: pick(xAxis && xAxis.left, chart.plotLeft),
  12132. translateY: pick(yAxis && yAxis.top, chart.plotTop)
  12133. });
  12134. }
  12135. series.translate();
  12136. if (series.setTooltipPoints) {
  12137. series.setTooltipPoints(true);
  12138. }
  12139. series.render();
  12140. if (wasDirtyData) {
  12141. fireEvent(series, 'updatedData');
  12142. }
  12143. }
  12144. }; // end Series prototype
  12145. /**
  12146. * The class for stack items
  12147. */
  12148. function StackItem(axis, options, isNegative, x, stackOption) {
  12149. var inverted = axis.chart.inverted;
  12150. this.axis = axis;
  12151. // Tells if the stack is negative
  12152. this.isNegative = isNegative;
  12153. // Save the options to be able to style the label
  12154. this.options = options;
  12155. // Save the x value to be able to position the label later
  12156. this.x = x;
  12157. // Initialize total value
  12158. this.total = null;
  12159. // This will keep each points' extremes stored by series.index and point index
  12160. this.points = {};
  12161. // Save the stack option on the series configuration object, and whether to treat it as percent
  12162. this.stack = stackOption;
  12163. // The align options and text align varies on whether the stack is negative and
  12164. // if the chart is inverted or not.
  12165. // First test the user supplied value, then use the dynamic.
  12166. this.alignOptions = {
  12167. align: options.align || (inverted ? (isNegative ? 'left' : 'right') : 'center'),
  12168. verticalAlign: options.verticalAlign || (inverted ? 'middle' : (isNegative ? 'bottom' : 'top')),
  12169. y: pick(options.y, inverted ? 4 : (isNegative ? 14 : -6)),
  12170. x: pick(options.x, inverted ? (isNegative ? -6 : 6) : 0)
  12171. };
  12172. this.textAlign = options.textAlign || (inverted ? (isNegative ? 'right' : 'left') : 'center');
  12173. }
  12174. StackItem.prototype = {
  12175. destroy: function () {
  12176. destroyObjectProperties(this, this.axis);
  12177. },
  12178. /**
  12179. * Renders the stack total label and adds it to the stack label group.
  12180. */
  12181. render: function (group) {
  12182. var options = this.options,
  12183. formatOption = options.format,
  12184. str = formatOption ?
  12185. format(formatOption, this) :
  12186. options.formatter.call(this); // format the text in the label
  12187. // Change the text to reflect the new total and set visibility to hidden in case the serie is hidden
  12188. if (this.label) {
  12189. this.label.attr({text: str, visibility: HIDDEN});
  12190. // Create new label
  12191. } else {
  12192. this.label =
  12193. this.axis.chart.renderer.text(str, null, null, options.useHTML) // dummy positions, actual position updated with setOffset method in columnseries
  12194. .css(options.style) // apply style
  12195. .attr({
  12196. align: this.textAlign, // fix the text-anchor
  12197. rotation: options.rotation, // rotation
  12198. visibility: HIDDEN // hidden until setOffset is called
  12199. })
  12200. .add(group); // add to the labels-group
  12201. }
  12202. },
  12203. /**
  12204. * Sets the offset that the stack has from the x value and repositions the label.
  12205. */
  12206. setOffset: function (xOffset, xWidth) {
  12207. var stackItem = this,
  12208. axis = stackItem.axis,
  12209. chart = axis.chart,
  12210. inverted = chart.inverted,
  12211. neg = this.isNegative, // special treatment is needed for negative stacks
  12212. y = axis.translate(axis.usePercentage ? 100 : this.total, 0, 0, 0, 1), // stack value translated mapped to chart coordinates
  12213. yZero = axis.translate(0), // stack origin
  12214. h = mathAbs(y - yZero), // stack height
  12215. x = chart.xAxis[0].translate(this.x) + xOffset, // stack x position
  12216. plotHeight = chart.plotHeight,
  12217. stackBox = { // this is the box for the complete stack
  12218. x: inverted ? (neg ? y : y - h) : x,
  12219. y: inverted ? plotHeight - x - xWidth : (neg ? (plotHeight - y - h) : plotHeight - y),
  12220. width: inverted ? h : xWidth,
  12221. height: inverted ? xWidth : h
  12222. },
  12223. label = this.label,
  12224. alignAttr;
  12225. if (label) {
  12226. label.align(this.alignOptions, null, stackBox); // align the label to the box
  12227. // Set visibility (#678)
  12228. alignAttr = label.alignAttr;
  12229. label[this.options.crop === false || chart.isInsidePlot(alignAttr.x, alignAttr.y) ? 'show' : 'hide'](true);
  12230. }
  12231. }
  12232. };
  12233. // Stacking methods defined on the Axis prototype
  12234. /**
  12235. * Build the stacks from top down
  12236. */
  12237. Axis.prototype.buildStacks = function () {
  12238. var series = this.series,
  12239. reversedStacks = pick(this.options.reversedStacks, true),
  12240. i = series.length;
  12241. if (!this.isXAxis) {
  12242. this.usePercentage = false;
  12243. while (i--) {
  12244. series[reversedStacks ? i : series.length - i - 1].setStackedPoints();
  12245. }
  12246. // Loop up again to compute percent stack
  12247. if (this.usePercentage) {
  12248. for (i = 0; i < series.length; i++) {
  12249. series[i].setPercentStacks();
  12250. }
  12251. }
  12252. }
  12253. };
  12254. Axis.prototype.renderStackTotals = function () {
  12255. var axis = this,
  12256. chart = axis.chart,
  12257. renderer = chart.renderer,
  12258. stacks = axis.stacks,
  12259. stackKey,
  12260. oneStack,
  12261. stackCategory,
  12262. stackTotalGroup = axis.stackTotalGroup;
  12263. // Create a separate group for the stack total labels
  12264. if (!stackTotalGroup) {
  12265. axis.stackTotalGroup = stackTotalGroup =
  12266. renderer.g('stack-labels')
  12267. .attr({
  12268. visibility: VISIBLE,
  12269. zIndex: 6
  12270. })
  12271. .add();
  12272. }
  12273. // plotLeft/Top will change when y axis gets wider so we need to translate the
  12274. // stackTotalGroup at every render call. See bug #506 and #516
  12275. stackTotalGroup.translate(chart.plotLeft, chart.plotTop);
  12276. // Render each stack total
  12277. for (stackKey in stacks) {
  12278. oneStack = stacks[stackKey];
  12279. for (stackCategory in oneStack) {
  12280. oneStack[stackCategory].render(stackTotalGroup);
  12281. }
  12282. }
  12283. };
  12284. // Stacking methods defnied for Series prototype
  12285. /**
  12286. * Adds series' points value to corresponding stack
  12287. */
  12288. Series.prototype.setStackedPoints = function () {
  12289. if (!this.options.stacking || (this.visible !== true && this.chart.options.chart.ignoreHiddenSeries !== false)) {
  12290. return;
  12291. }
  12292. var series = this,
  12293. xData = series.processedXData,
  12294. yData = series.processedYData,
  12295. stackedYData = [],
  12296. yDataLength = yData.length,
  12297. seriesOptions = series.options,
  12298. threshold = seriesOptions.threshold,
  12299. stackOption = seriesOptions.stack,
  12300. stacking = seriesOptions.stacking,
  12301. stackKey = series.stackKey,
  12302. negKey = '-' + stackKey,
  12303. negStacks = series.negStacks,
  12304. yAxis = series.yAxis,
  12305. stacks = yAxis.stacks,
  12306. oldStacks = yAxis.oldStacks,
  12307. isNegative,
  12308. stack,
  12309. other,
  12310. key,
  12311. pointKey,
  12312. i,
  12313. x,
  12314. y;
  12315. // loop over the non-null y values and read them into a local array
  12316. for (i = 0; i < yDataLength; i++) {
  12317. x = xData[i];
  12318. y = yData[i];
  12319. pointKey = series.index + ',' + i;
  12320. // Read stacked values into a stack based on the x value,
  12321. // the sign of y and the stack key. Stacking is also handled for null values (#739)
  12322. isNegative = negStacks && y < threshold;
  12323. key = isNegative ? negKey : stackKey;
  12324. // Create empty object for this stack if it doesn't exist yet
  12325. if (!stacks[key]) {
  12326. stacks[key] = {};
  12327. }
  12328. // Initialize StackItem for this x
  12329. if (!stacks[key][x]) {
  12330. if (oldStacks[key] && oldStacks[key][x]) {
  12331. stacks[key][x] = oldStacks[key][x];
  12332. stacks[key][x].total = null;
  12333. } else {
  12334. stacks[key][x] = new StackItem(yAxis, yAxis.options.stackLabels, isNegative, x, stackOption);
  12335. }
  12336. }
  12337. // If the StackItem doesn't exist, create it first
  12338. stack = stacks[key][x];
  12339. stack.points[pointKey] = [stack.cum || 0];
  12340. // Add value to the stack total
  12341. if (stacking === 'percent') {
  12342. // Percent stacked column, totals are the same for the positive and negative stacks
  12343. other = isNegative ? stackKey : negKey;
  12344. if (negStacks && stacks[other] && stacks[other][x]) {
  12345. other = stacks[other][x];
  12346. stack.total = other.total = mathMax(other.total, stack.total) + mathAbs(y) || 0;
  12347. // Percent stacked areas
  12348. } else {
  12349. stack.total = correctFloat(stack.total + (mathAbs(y) || 0));
  12350. }
  12351. } else {
  12352. stack.total = correctFloat(stack.total + (y || 0));
  12353. }
  12354. stack.cum = (stack.cum || 0) + (y || 0);
  12355. stack.points[pointKey].push(stack.cum);
  12356. stackedYData[i] = stack.cum;
  12357. }
  12358. if (stacking === 'percent') {
  12359. yAxis.usePercentage = true;
  12360. }
  12361. this.stackedYData = stackedYData; // To be used in getExtremes
  12362. // Reset old stacks
  12363. yAxis.oldStacks = {};
  12364. };
  12365. /**
  12366. * Iterate over all stacks and compute the absolute values to percent
  12367. */
  12368. Series.prototype.setPercentStacks = function () {
  12369. var series = this,
  12370. stackKey = series.stackKey,
  12371. stacks = series.yAxis.stacks,
  12372. processedXData = series.processedXData;
  12373. each([stackKey, '-' + stackKey], function (key) {
  12374. var i = processedXData.length,
  12375. x,
  12376. stack,
  12377. pointExtremes,
  12378. totalFactor;
  12379. while (i--) {
  12380. x = processedXData[i];
  12381. stack = stacks[key] && stacks[key][x];
  12382. pointExtremes = stack && stack.points[series.index + ',' + i];
  12383. if (pointExtremes) {
  12384. totalFactor = stack.total ? 100 / stack.total : 0;
  12385. pointExtremes[0] = correctFloat(pointExtremes[0] * totalFactor); // Y bottom value
  12386. pointExtremes[1] = correctFloat(pointExtremes[1] * totalFactor); // Y value
  12387. series.stackedYData[i] = pointExtremes[1];
  12388. }
  12389. }
  12390. });
  12391. };
  12392. // Extend the Chart prototype for dynamic methods
  12393. extend(Chart.prototype, {
  12394. /**
  12395. * Add a series dynamically after time
  12396. *
  12397. * @param {Object} options The config options
  12398. * @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true.
  12399. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  12400. * configuration
  12401. *
  12402. * @return {Object} series The newly created series object
  12403. */
  12404. addSeries: function (options, redraw, animation) {
  12405. var series,
  12406. chart = this;
  12407. if (options) {
  12408. redraw = pick(redraw, true); // defaults to true
  12409. fireEvent(chart, 'addSeries', { options: options }, function () {
  12410. series = chart.initSeries(options);
  12411. chart.isDirtyLegend = true; // the series array is out of sync with the display
  12412. chart.linkSeries();
  12413. if (redraw) {
  12414. chart.redraw(animation);
  12415. }
  12416. });
  12417. }
  12418. return series;
  12419. },
  12420. /**
  12421. * Add an axis to the chart
  12422. * @param {Object} options The axis option
  12423. * @param {Boolean} isX Whether it is an X axis or a value axis
  12424. */
  12425. addAxis: function (options, isX, redraw, animation) {
  12426. var key = isX ? 'xAxis' : 'yAxis',
  12427. chartOptions = this.options,
  12428. axis;
  12429. /*jslint unused: false*/
  12430. axis = new Axis(this, merge(options, {
  12431. index: this[key].length,
  12432. isX: isX
  12433. }));
  12434. /*jslint unused: true*/
  12435. // Push the new axis options to the chart options
  12436. chartOptions[key] = splat(chartOptions[key] || {});
  12437. chartOptions[key].push(options);
  12438. if (pick(redraw, true)) {
  12439. this.redraw(animation);
  12440. }
  12441. },
  12442. /**
  12443. * Dim the chart and show a loading text or symbol
  12444. * @param {String} str An optional text to show in the loading label instead of the default one
  12445. */
  12446. showLoading: function (str) {
  12447. var chart = this,
  12448. options = chart.options,
  12449. loadingDiv = chart.loadingDiv;
  12450. var loadingOptions = options.loading;
  12451. // create the layer at the first call
  12452. if (!loadingDiv) {
  12453. chart.loadingDiv = loadingDiv = createElement(DIV, {
  12454. className: PREFIX + 'loading'
  12455. }, extend(loadingOptions.style, {
  12456. zIndex: 10,
  12457. display: NONE
  12458. }), chart.container);
  12459. chart.loadingSpan = createElement(
  12460. 'span',
  12461. null,
  12462. loadingOptions.labelStyle,
  12463. loadingDiv
  12464. );
  12465. }
  12466. // update text
  12467. chart.loadingSpan.innerHTML = str || options.lang.loading;
  12468. // show it
  12469. if (!chart.loadingShown) {
  12470. css(loadingDiv, {
  12471. opacity: 0,
  12472. display: '',
  12473. left: chart.plotLeft + PX,
  12474. top: chart.plotTop + PX,
  12475. width: chart.plotWidth + PX,
  12476. height: chart.plotHeight + PX
  12477. });
  12478. animate(loadingDiv, {
  12479. opacity: loadingOptions.style.opacity
  12480. }, {
  12481. duration: loadingOptions.showDuration || 0
  12482. });
  12483. chart.loadingShown = true;
  12484. }
  12485. },
  12486. /**
  12487. * Hide the loading layer
  12488. */
  12489. hideLoading: function () {
  12490. var options = this.options,
  12491. loadingDiv = this.loadingDiv;
  12492. if (loadingDiv) {
  12493. animate(loadingDiv, {
  12494. opacity: 0
  12495. }, {
  12496. duration: options.loading.hideDuration || 100,
  12497. complete: function () {
  12498. css(loadingDiv, { display: NONE });
  12499. }
  12500. });
  12501. }
  12502. this.loadingShown = false;
  12503. }
  12504. });
  12505. // extend the Point prototype for dynamic methods
  12506. extend(Point.prototype, {
  12507. /**
  12508. * Update the point with new options (typically x/y data) and optionally redraw the series.
  12509. *
  12510. * @param {Object} options Point options as defined in the series.data array
  12511. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  12512. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  12513. * configuration
  12514. *
  12515. */
  12516. update: function (options, redraw, animation) {
  12517. var point = this,
  12518. series = point.series,
  12519. graphic = point.graphic,
  12520. i,
  12521. data = series.data,
  12522. chart = series.chart,
  12523. seriesOptions = series.options;
  12524. redraw = pick(redraw, true);
  12525. // fire the event with a default handler of doing the update
  12526. point.firePointEvent('update', { options: options }, function () {
  12527. point.applyOptions(options);
  12528. // update visuals
  12529. if (isObject(options)) {
  12530. series.getAttribs();
  12531. if (graphic) {
  12532. if (options && options.marker && options.marker.symbol) {
  12533. point.graphic = graphic.destroy();
  12534. } else {
  12535. graphic.attr(point.pointAttr[point.state || '']);
  12536. }
  12537. }
  12538. if (options && options.dataLabels && point.dataLabel) { // #2468
  12539. point.dataLabel = point.dataLabel.destroy();
  12540. }
  12541. }
  12542. // record changes in the parallel arrays
  12543. i = inArray(point, data);
  12544. series.updateParallelArrays(point, i);
  12545. seriesOptions.data[i] = point.options;
  12546. // redraw
  12547. series.isDirty = series.isDirtyData = true;
  12548. if (!series.fixedBox && series.hasCartesianSeries) { // #1906, #2320
  12549. chart.isDirtyBox = true;
  12550. }
  12551. if (seriesOptions.legendType === 'point') { // #1831, #1885
  12552. chart.legend.destroyItem(point);
  12553. }
  12554. if (redraw) {
  12555. chart.redraw(animation);
  12556. }
  12557. });
  12558. },
  12559. /**
  12560. * Remove a point and optionally redraw the series and if necessary the axes
  12561. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  12562. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  12563. * configuration
  12564. */
  12565. remove: function (redraw, animation) {
  12566. var point = this,
  12567. series = point.series,
  12568. points = series.points,
  12569. chart = series.chart,
  12570. i,
  12571. data = series.data;
  12572. setAnimation(animation, chart);
  12573. redraw = pick(redraw, true);
  12574. // fire the event with a default handler of removing the point
  12575. point.firePointEvent('remove', null, function () {
  12576. // splice all the parallel arrays
  12577. i = inArray(point, data);
  12578. if (data.length === points.length) {
  12579. points.splice(i, 1);
  12580. }
  12581. data.splice(i, 1);
  12582. series.options.data.splice(i, 1);
  12583. series.updateParallelArrays(point, 'splice', i, 1);
  12584. point.destroy();
  12585. // redraw
  12586. series.isDirty = true;
  12587. series.isDirtyData = true;
  12588. if (redraw) {
  12589. chart.redraw();
  12590. }
  12591. });
  12592. }
  12593. });
  12594. // Extend the series prototype for dynamic methods
  12595. extend(Series.prototype, {
  12596. /**
  12597. * Add a point dynamically after chart load time
  12598. * @param {Object} options Point options as given in series.data
  12599. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  12600. * @param {Boolean} shift If shift is true, a point is shifted off the start
  12601. * of the series as one is appended to the end.
  12602. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  12603. * configuration
  12604. */
  12605. addPoint: function (options, redraw, shift, animation) {
  12606. var series = this,
  12607. seriesOptions = series.options,
  12608. data = series.data,
  12609. graph = series.graph,
  12610. area = series.area,
  12611. chart = series.chart,
  12612. names = series.xAxis && series.xAxis.names,
  12613. currentShift = (graph && graph.shift) || 0,
  12614. dataOptions = seriesOptions.data,
  12615. point,
  12616. isInTheMiddle,
  12617. xData = series.xData,
  12618. x,
  12619. i;
  12620. setAnimation(animation, chart);
  12621. // Make graph animate sideways
  12622. if (shift) {
  12623. each([graph, area, series.graphNeg, series.areaNeg], function (shape) {
  12624. if (shape) {
  12625. shape.shift = currentShift + 1;
  12626. }
  12627. });
  12628. }
  12629. if (area) {
  12630. area.isArea = true; // needed in animation, both with and without shift
  12631. }
  12632. // Optional redraw, defaults to true
  12633. redraw = pick(redraw, true);
  12634. // Get options and push the point to xData, yData and series.options. In series.generatePoints
  12635. // the Point instance will be created on demand and pushed to the series.data array.
  12636. point = { series: series };
  12637. series.pointClass.prototype.applyOptions.apply(point, [options]);
  12638. x = point.x;
  12639. // Get the insertion point
  12640. i = xData.length;
  12641. if (series.requireSorting && x < xData[i - 1]) {
  12642. isInTheMiddle = true;
  12643. while (i && xData[i - 1] > x) {
  12644. i--;
  12645. }
  12646. }
  12647. series.updateParallelArrays(point, 'splice', i, 0, 0); // insert undefined item
  12648. series.updateParallelArrays(point, i); // update it
  12649. if (names) {
  12650. names[x] = point.name;
  12651. }
  12652. dataOptions.splice(i, 0, options);
  12653. if (isInTheMiddle) {
  12654. series.data.splice(i, 0, null);
  12655. series.processData();
  12656. }
  12657. // Generate points to be added to the legend (#1329)
  12658. if (seriesOptions.legendType === 'point') {
  12659. series.generatePoints();
  12660. }
  12661. // Shift the first point off the parallel arrays
  12662. // todo: consider series.removePoint(i) method
  12663. if (shift) {
  12664. if (data[0] && data[0].remove) {
  12665. data[0].remove(false);
  12666. } else {
  12667. data.shift();
  12668. series.updateParallelArrays(point, 'shift');
  12669. dataOptions.shift();
  12670. }
  12671. }
  12672. // redraw
  12673. series.isDirty = true;
  12674. series.isDirtyData = true;
  12675. if (redraw) {
  12676. series.getAttribs(); // #1937
  12677. chart.redraw();
  12678. }
  12679. },
  12680. /**
  12681. * Remove a series and optionally redraw the chart
  12682. *
  12683. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  12684. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  12685. * configuration
  12686. */
  12687. remove: function (redraw, animation) {
  12688. var series = this,
  12689. chart = series.chart;
  12690. redraw = pick(redraw, true);
  12691. if (!series.isRemoving) { /* prevent triggering native event in jQuery
  12692. (calling the remove function from the remove event) */
  12693. series.isRemoving = true;
  12694. // fire the event with a default handler of removing the point
  12695. fireEvent(series, 'remove', null, function () {
  12696. // destroy elements
  12697. series.destroy();
  12698. // redraw
  12699. chart.isDirtyLegend = chart.isDirtyBox = true;
  12700. chart.linkSeries();
  12701. if (redraw) {
  12702. chart.redraw(animation);
  12703. }
  12704. });
  12705. }
  12706. series.isRemoving = false;
  12707. },
  12708. /**
  12709. * Update the series with a new set of options
  12710. */
  12711. update: function (newOptions, redraw) {
  12712. var chart = this.chart,
  12713. // must use user options when changing type because this.options is merged
  12714. // in with type specific plotOptions
  12715. oldOptions = this.userOptions,
  12716. oldType = this.type,
  12717. proto = seriesTypes[oldType].prototype,
  12718. n;
  12719. // Do the merge, with some forced options
  12720. newOptions = merge(oldOptions, {
  12721. animation: false,
  12722. index: this.index,
  12723. pointStart: this.xData[0] // when updating after addPoint
  12724. }, { data: this.options.data }, newOptions);
  12725. // Destroy the series and reinsert methods from the type prototype
  12726. this.remove(false);
  12727. for (n in proto) { // Overwrite series-type specific methods (#2270)
  12728. if (proto.hasOwnProperty(n)) {
  12729. this[n] = UNDEFINED;
  12730. }
  12731. }
  12732. extend(this, seriesTypes[newOptions.type || oldType].prototype);
  12733. this.init(chart, newOptions);
  12734. if (pick(redraw, true)) {
  12735. chart.redraw(false);
  12736. }
  12737. }
  12738. });
  12739. // Extend the Axis.prototype for dynamic methods
  12740. extend(Axis.prototype, {
  12741. /**
  12742. * Update the axis with a new options structure
  12743. */
  12744. update: function (newOptions, redraw) {
  12745. var chart = this.chart;
  12746. newOptions = chart.options[this.coll][this.options.index] = merge(this.userOptions, newOptions);
  12747. this.destroy(true);
  12748. this._addedPlotLB = UNDEFINED; // #1611, #2887
  12749. this.init(chart, extend(newOptions, { events: UNDEFINED }));
  12750. chart.isDirtyBox = true;
  12751. if (pick(redraw, true)) {
  12752. chart.redraw();
  12753. }
  12754. },
  12755. /**
  12756. * Remove the axis from the chart
  12757. */
  12758. remove: function (redraw) {
  12759. var chart = this.chart,
  12760. key = this.coll, // xAxis or yAxis
  12761. axisSeries = this.series,
  12762. i = axisSeries.length;
  12763. // Remove associated series (#2687)
  12764. while (i--) {
  12765. if (axisSeries[i]) {
  12766. axisSeries[i].remove(false);
  12767. }
  12768. }
  12769. // Remove the axis
  12770. erase(chart.axes, this);
  12771. erase(chart[key], this);
  12772. chart.options[key].splice(this.options.index, 1);
  12773. each(chart[key], function (axis, i) { // Re-index, #1706
  12774. axis.options.index = i;
  12775. });
  12776. this.destroy();
  12777. chart.isDirtyBox = true;
  12778. if (pick(redraw, true)) {
  12779. chart.redraw();
  12780. }
  12781. },
  12782. /**
  12783. * Update the axis title by options
  12784. */
  12785. setTitle: function (newTitleOptions, redraw) {
  12786. this.update({ title: newTitleOptions }, redraw);
  12787. },
  12788. /**
  12789. * Set new axis categories and optionally redraw
  12790. * @param {Array} categories
  12791. * @param {Boolean} redraw
  12792. */
  12793. setCategories: function (categories, redraw) {
  12794. this.update({ categories: categories }, redraw);
  12795. }
  12796. });
  12797. /**
  12798. * LineSeries object
  12799. */
  12800. var LineSeries = extendClass(Series);
  12801. seriesTypes.line = LineSeries;
  12802. /**
  12803. * Set the default options for area
  12804. */
  12805. defaultPlotOptions.area = merge(defaultSeriesOptions, {
  12806. threshold: 0
  12807. // trackByArea: false,
  12808. // lineColor: null, // overrides color, but lets fillColor be unaltered
  12809. // fillOpacity: 0.75,
  12810. // fillColor: null
  12811. });
  12812. /**
  12813. * AreaSeries object
  12814. */
  12815. var AreaSeries = extendClass(Series, {
  12816. type: 'area',
  12817. /**
  12818. * For stacks, don't split segments on null values. Instead, draw null values with
  12819. * no marker. Also insert dummy points for any X position that exists in other series
  12820. * in the stack.
  12821. */
  12822. getSegments: function () {
  12823. var segments = [],
  12824. segment = [],
  12825. keys = [],
  12826. xAxis = this.xAxis,
  12827. yAxis = this.yAxis,
  12828. stack = yAxis.stacks[this.stackKey],
  12829. pointMap = {},
  12830. plotX,
  12831. plotY,
  12832. points = this.points,
  12833. connectNulls = this.options.connectNulls,
  12834. val,
  12835. i,
  12836. x;
  12837. if (this.options.stacking && !this.cropped) { // cropped causes artefacts in Stock, and perf issue
  12838. // Create a map where we can quickly look up the points by their X value.
  12839. for (i = 0; i < points.length; i++) {
  12840. pointMap[points[i].x] = points[i];
  12841. }
  12842. // Sort the keys (#1651)
  12843. for (x in stack) {
  12844. if (stack[x].total !== null) { // nulled after switching between grouping and not (#1651, #2336)
  12845. keys.push(+x);
  12846. }
  12847. }
  12848. keys.sort(function (a, b) {
  12849. return a - b;
  12850. });
  12851. each(keys, function (x) {
  12852. if (connectNulls && (!pointMap[x] || pointMap[x].y === null)) { // #1836
  12853. return;
  12854. // The point exists, push it to the segment
  12855. } else if (pointMap[x]) {
  12856. segment.push(pointMap[x]);
  12857. // There is no point for this X value in this series, so we
  12858. // insert a dummy point in order for the areas to be drawn
  12859. // correctly.
  12860. } else {
  12861. plotX = xAxis.translate(x);
  12862. val = stack[x].percent ? (stack[x].total ? stack[x].cum * 100 / stack[x].total : 0) : stack[x].cum; // #1991
  12863. plotY = yAxis.toPixels(val, true);
  12864. segment.push({
  12865. y: null,
  12866. plotX: plotX,
  12867. clientX: plotX,
  12868. plotY: plotY,
  12869. yBottom: plotY,
  12870. onMouseOver: noop
  12871. });
  12872. }
  12873. });
  12874. if (segment.length) {
  12875. segments.push(segment);
  12876. }
  12877. } else {
  12878. Series.prototype.getSegments.call(this);
  12879. segments = this.segments;
  12880. }
  12881. this.segments = segments;
  12882. },
  12883. /**
  12884. * Extend the base Series getSegmentPath method by adding the path for the area.
  12885. * This path is pushed to the series.areaPath property.
  12886. */
  12887. getSegmentPath: function (segment) {
  12888. var segmentPath = Series.prototype.getSegmentPath.call(this, segment), // call base method
  12889. areaSegmentPath = [].concat(segmentPath), // work on a copy for the area path
  12890. i,
  12891. options = this.options,
  12892. segLength = segmentPath.length,
  12893. translatedThreshold = this.yAxis.getThreshold(options.threshold), // #2181
  12894. yBottom;
  12895. if (segLength === 3) { // for animation from 1 to two points
  12896. areaSegmentPath.push(L, segmentPath[1], segmentPath[2]);
  12897. }
  12898. if (options.stacking && !this.closedStacks) {
  12899. // Follow stack back. Todo: implement areaspline. A general solution could be to
  12900. // reverse the entire graphPath of the previous series, though may be hard with
  12901. // splines and with series with different extremes
  12902. for (i = segment.length - 1; i >= 0; i--) {
  12903. yBottom = pick(segment[i].yBottom, translatedThreshold);
  12904. // step line?
  12905. if (i < segment.length - 1 && options.step) {
  12906. areaSegmentPath.push(segment[i + 1].plotX, yBottom);
  12907. }
  12908. areaSegmentPath.push(segment[i].plotX, yBottom);
  12909. }
  12910. } else { // follow zero line back
  12911. this.closeSegment(areaSegmentPath, segment, translatedThreshold);
  12912. }
  12913. this.areaPath = this.areaPath.concat(areaSegmentPath);
  12914. return segmentPath;
  12915. },
  12916. /**
  12917. * Extendable method to close the segment path of an area. This is overridden in polar
  12918. * charts.
  12919. */
  12920. closeSegment: function (path, segment, translatedThreshold) {
  12921. path.push(
  12922. L,
  12923. segment[segment.length - 1].plotX,
  12924. translatedThreshold,
  12925. L,
  12926. segment[0].plotX,
  12927. translatedThreshold
  12928. );
  12929. },
  12930. /**
  12931. * Draw the graph and the underlying area. This method calls the Series base
  12932. * function and adds the area. The areaPath is calculated in the getSegmentPath
  12933. * method called from Series.prototype.drawGraph.
  12934. */
  12935. drawGraph: function () {
  12936. // Define or reset areaPath
  12937. this.areaPath = [];
  12938. // Call the base method
  12939. Series.prototype.drawGraph.apply(this);
  12940. // Define local variables
  12941. var series = this,
  12942. areaPath = this.areaPath,
  12943. options = this.options,
  12944. negativeColor = options.negativeColor,
  12945. negativeFillColor = options.negativeFillColor,
  12946. props = [['area', this.color, options.fillColor]]; // area name, main color, fill color
  12947. if (negativeColor || negativeFillColor) {
  12948. props.push(['areaNeg', negativeColor, negativeFillColor]);
  12949. }
  12950. each(props, function (prop) {
  12951. var areaKey = prop[0],
  12952. area = series[areaKey];
  12953. // Create or update the area
  12954. if (area) { // update
  12955. area.animate({ d: areaPath });
  12956. } else { // create
  12957. series[areaKey] = series.chart.renderer.path(areaPath)
  12958. .attr({
  12959. fill: pick(
  12960. prop[2],
  12961. Color(prop[1]).setOpacity(pick(options.fillOpacity, 0.75)).get()
  12962. ),
  12963. zIndex: 0 // #1069
  12964. }).add(series.group);
  12965. }
  12966. });
  12967. },
  12968. drawLegendSymbol: LegendSymbolMixin.drawRectangle
  12969. });
  12970. seriesTypes.area = AreaSeries;
  12971. /**
  12972. * Set the default options for spline
  12973. */
  12974. defaultPlotOptions.spline = merge(defaultSeriesOptions);
  12975. /**
  12976. * SplineSeries object
  12977. */
  12978. var SplineSeries = extendClass(Series, {
  12979. type: 'spline',
  12980. /**
  12981. * Get the spline segment from a given point's previous neighbour to the given point
  12982. */
  12983. getPointSpline: function (segment, point, i) {
  12984. var smoothing = 1.5, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc
  12985. denom = smoothing + 1,
  12986. plotX = point.plotX,
  12987. plotY = point.plotY,
  12988. lastPoint = segment[i - 1],
  12989. nextPoint = segment[i + 1],
  12990. leftContX,
  12991. leftContY,
  12992. rightContX,
  12993. rightContY,
  12994. ret;
  12995. // find control points
  12996. if (lastPoint && nextPoint) {
  12997. var lastX = lastPoint.plotX,
  12998. lastY = lastPoint.plotY,
  12999. nextX = nextPoint.plotX,
  13000. nextY = nextPoint.plotY,
  13001. correction;
  13002. leftContX = (smoothing * plotX + lastX) / denom;
  13003. leftContY = (smoothing * plotY + lastY) / denom;
  13004. rightContX = (smoothing * plotX + nextX) / denom;
  13005. rightContY = (smoothing * plotY + nextY) / denom;
  13006. // have the two control points make a straight line through main point
  13007. correction = ((rightContY - leftContY) * (rightContX - plotX)) /
  13008. (rightContX - leftContX) + plotY - rightContY;
  13009. leftContY += correction;
  13010. rightContY += correction;
  13011. // to prevent false extremes, check that control points are between
  13012. // neighbouring points' y values
  13013. if (leftContY > lastY && leftContY > plotY) {
  13014. leftContY = mathMax(lastY, plotY);
  13015. rightContY = 2 * plotY - leftContY; // mirror of left control point
  13016. } else if (leftContY < lastY && leftContY < plotY) {
  13017. leftContY = mathMin(lastY, plotY);
  13018. rightContY = 2 * plotY - leftContY;
  13019. }
  13020. if (rightContY > nextY && rightContY > plotY) {
  13021. rightContY = mathMax(nextY, plotY);
  13022. leftContY = 2 * plotY - rightContY;
  13023. } else if (rightContY < nextY && rightContY < plotY) {
  13024. rightContY = mathMin(nextY, plotY);
  13025. leftContY = 2 * plotY - rightContY;
  13026. }
  13027. // record for drawing in next point
  13028. point.rightContX = rightContX;
  13029. point.rightContY = rightContY;
  13030. }
  13031. // Visualize control points for debugging
  13032. /*
  13033. if (leftContX) {
  13034. this.chart.renderer.circle(leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 2)
  13035. .attr({
  13036. stroke: 'red',
  13037. 'stroke-width': 1,
  13038. fill: 'none'
  13039. })
  13040. .add();
  13041. this.chart.renderer.path(['M', leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop,
  13042. 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
  13043. .attr({
  13044. stroke: 'red',
  13045. 'stroke-width': 1
  13046. })
  13047. .add();
  13048. this.chart.renderer.circle(rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 2)
  13049. .attr({
  13050. stroke: 'green',
  13051. 'stroke-width': 1,
  13052. fill: 'none'
  13053. })
  13054. .add();
  13055. this.chart.renderer.path(['M', rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop,
  13056. 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
  13057. .attr({
  13058. stroke: 'green',
  13059. 'stroke-width': 1
  13060. })
  13061. .add();
  13062. }
  13063. */
  13064. // moveTo or lineTo
  13065. if (!i) {
  13066. ret = [M, plotX, plotY];
  13067. } else { // curve from last point to this
  13068. ret = [
  13069. 'C',
  13070. lastPoint.rightContX || lastPoint.plotX,
  13071. lastPoint.rightContY || lastPoint.plotY,
  13072. leftContX || plotX,
  13073. leftContY || plotY,
  13074. plotX,
  13075. plotY
  13076. ];
  13077. lastPoint.rightContX = lastPoint.rightContY = null; // reset for updating series later
  13078. }
  13079. return ret;
  13080. }
  13081. });
  13082. seriesTypes.spline = SplineSeries;
  13083. /**
  13084. * Set the default options for areaspline
  13085. */
  13086. defaultPlotOptions.areaspline = merge(defaultPlotOptions.area);
  13087. /**
  13088. * AreaSplineSeries object
  13089. */
  13090. var areaProto = AreaSeries.prototype,
  13091. AreaSplineSeries = extendClass(SplineSeries, {
  13092. type: 'areaspline',
  13093. closedStacks: true, // instead of following the previous graph back, follow the threshold back
  13094. // Mix in methods from the area series
  13095. getSegmentPath: areaProto.getSegmentPath,
  13096. closeSegment: areaProto.closeSegment,
  13097. drawGraph: areaProto.drawGraph,
  13098. drawLegendSymbol: LegendSymbolMixin.drawRectangle
  13099. });
  13100. seriesTypes.areaspline = AreaSplineSeries;
  13101. /**
  13102. * Set the default options for column
  13103. */
  13104. defaultPlotOptions.column = merge(defaultSeriesOptions, {
  13105. borderColor: '#FFFFFF',
  13106. //borderWidth: 1,
  13107. borderRadius: 0,
  13108. //colorByPoint: undefined,
  13109. groupPadding: 0.2,
  13110. //grouping: true,
  13111. marker: null, // point options are specified in the base options
  13112. pointPadding: 0.1,
  13113. //pointWidth: null,
  13114. minPointLength: 0,
  13115. cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes
  13116. pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories
  13117. states: {
  13118. hover: {
  13119. brightness: 0.1,
  13120. shadow: false,
  13121. halo: false
  13122. },
  13123. select: {
  13124. color: '#C0C0C0',
  13125. borderColor: '#000000',
  13126. shadow: false
  13127. }
  13128. },
  13129. dataLabels: {
  13130. align: null, // auto
  13131. verticalAlign: null, // auto
  13132. y: null
  13133. },
  13134. stickyTracking: false,
  13135. tooltip: {
  13136. distance: 6
  13137. },
  13138. threshold: 0
  13139. });
  13140. /**
  13141. * ColumnSeries object
  13142. */
  13143. var ColumnSeries = extendClass(Series, {
  13144. type: 'column',
  13145. pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
  13146. stroke: 'borderColor',
  13147. fill: 'color',
  13148. r: 'borderRadius'
  13149. },
  13150. cropShoulder: 0,
  13151. trackerGroups: ['group', 'dataLabelsGroup'],
  13152. negStacks: true, // use separate negative stacks, unlike area stacks where a negative
  13153. // point is substracted from previous (#1910)
  13154. /**
  13155. * Initialize the series
  13156. */
  13157. init: function () {
  13158. Series.prototype.init.apply(this, arguments);
  13159. var series = this,
  13160. chart = series.chart;
  13161. // if the series is added dynamically, force redraw of other
  13162. // series affected by a new column
  13163. if (chart.hasRendered) {
  13164. each(chart.series, function (otherSeries) {
  13165. if (otherSeries.type === series.type) {
  13166. otherSeries.isDirty = true;
  13167. }
  13168. });
  13169. }
  13170. },
  13171. /**
  13172. * Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding,
  13173. * pointWidth etc.
  13174. */
  13175. getColumnMetrics: function () {
  13176. var series = this,
  13177. options = series.options,
  13178. xAxis = series.xAxis,
  13179. yAxis = series.yAxis,
  13180. reversedXAxis = xAxis.reversed,
  13181. stackKey,
  13182. stackGroups = {},
  13183. columnIndex,
  13184. columnCount = 0;
  13185. // Get the total number of column type series.
  13186. // This is called on every series. Consider moving this logic to a
  13187. // chart.orderStacks() function and call it on init, addSeries and removeSeries
  13188. if (options.grouping === false) {
  13189. columnCount = 1;
  13190. } else {
  13191. each(series.chart.series, function (otherSeries) {
  13192. var otherOptions = otherSeries.options,
  13193. otherYAxis = otherSeries.yAxis;
  13194. if (otherSeries.type === series.type && otherSeries.visible &&
  13195. yAxis.len === otherYAxis.len && yAxis.pos === otherYAxis.pos) { // #642, #2086
  13196. if (otherOptions.stacking) {
  13197. stackKey = otherSeries.stackKey;
  13198. if (stackGroups[stackKey] === UNDEFINED) {
  13199. stackGroups[stackKey] = columnCount++;
  13200. }
  13201. columnIndex = stackGroups[stackKey];
  13202. } else if (otherOptions.grouping !== false) { // #1162
  13203. columnIndex = columnCount++;
  13204. }
  13205. otherSeries.columnIndex = columnIndex;
  13206. }
  13207. });
  13208. }
  13209. var categoryWidth = mathMin(
  13210. mathAbs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || xAxis.tickInterval || 1), // #2610
  13211. xAxis.len // #1535
  13212. ),
  13213. groupPadding = categoryWidth * options.groupPadding,
  13214. groupWidth = categoryWidth - 2 * groupPadding,
  13215. pointOffsetWidth = groupWidth / columnCount,
  13216. optionPointWidth = options.pointWidth,
  13217. pointPadding = defined(optionPointWidth) ? (pointOffsetWidth - optionPointWidth) / 2 :
  13218. pointOffsetWidth * options.pointPadding,
  13219. pointWidth = pick(optionPointWidth, pointOffsetWidth - 2 * pointPadding), // exact point width, used in polar charts
  13220. colIndex = (reversedXAxis ?
  13221. columnCount - (series.columnIndex || 0) : // #1251
  13222. series.columnIndex) || 0,
  13223. pointXOffset = pointPadding + (groupPadding + colIndex *
  13224. pointOffsetWidth - (categoryWidth / 2)) *
  13225. (reversedXAxis ? -1 : 1);
  13226. // Save it for reading in linked series (Error bars particularly)
  13227. return (series.columnMetrics = {
  13228. width: pointWidth,
  13229. offset: pointXOffset
  13230. });
  13231. },
  13232. /**
  13233. * Translate each point to the plot area coordinate system and find shape positions
  13234. */
  13235. translate: function () {
  13236. var series = this,
  13237. chart = series.chart,
  13238. options = series.options,
  13239. borderWidth = series.borderWidth = pick(
  13240. options.borderWidth,
  13241. series.activePointCount > 0.5 * series.xAxis.len ? 0 : 1
  13242. ),
  13243. yAxis = series.yAxis,
  13244. threshold = options.threshold,
  13245. translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold),
  13246. minPointLength = pick(options.minPointLength, 5),
  13247. metrics = series.getColumnMetrics(),
  13248. pointWidth = metrics.width,
  13249. seriesBarW = series.barW = mathCeil(mathMax(pointWidth, 1 + 2 * borderWidth)), // rounded and postprocessed for border width
  13250. pointXOffset = series.pointXOffset = metrics.offset,
  13251. xCrisp = -(borderWidth % 2 ? 0.5 : 0),
  13252. yCrisp = borderWidth % 2 ? 0.5 : 1;
  13253. if (chart.renderer.isVML && chart.inverted) {
  13254. yCrisp += 1;
  13255. }
  13256. Series.prototype.translate.apply(series);
  13257. // record the new values
  13258. each(series.points, function (point) {
  13259. var yBottom = pick(point.yBottom, translatedThreshold),
  13260. plotY = mathMin(mathMax(-999 - yBottom, point.plotY), yAxis.len + 999 + yBottom), // Don't draw too far outside plot area (#1303, #2241)
  13261. barX = point.plotX + pointXOffset,
  13262. barW = seriesBarW,
  13263. barY = mathMin(plotY, yBottom),
  13264. right,
  13265. bottom,
  13266. fromTop,
  13267. fromLeft,
  13268. barH = mathMax(plotY, yBottom) - barY;
  13269. // Handle options.minPointLength
  13270. if (mathAbs(barH) < minPointLength) {
  13271. if (minPointLength) {
  13272. barH = minPointLength;
  13273. barY =
  13274. mathRound(mathAbs(barY - translatedThreshold) > minPointLength ? // stacked
  13275. yBottom - minPointLength : // keep position
  13276. translatedThreshold - (yAxis.translate(point.y, 0, 1, 0, 1) <= translatedThreshold ? minPointLength : 0)); // use exact yAxis.translation (#1485)
  13277. }
  13278. }
  13279. // Cache for access in polar
  13280. point.barX = barX;
  13281. point.pointWidth = pointWidth;
  13282. // Fix the tooltip on center of grouped columns (#1216)
  13283. point.tooltipPos = chart.inverted ? [yAxis.len - plotY, series.xAxis.len - barX - barW / 2] : [barX + barW / 2, plotY];
  13284. // Round off to obtain crisp edges
  13285. fromLeft = mathAbs(barX) < 0.5;
  13286. right = mathRound(barX + barW) + xCrisp;
  13287. barX = mathRound(barX) + xCrisp;
  13288. barW = right - barX;
  13289. fromTop = mathAbs(barY) < 0.5;
  13290. bottom = mathRound(barY + barH) + yCrisp;
  13291. barY = mathRound(barY) + yCrisp;
  13292. barH = bottom - barY;
  13293. // Top and left edges are exceptions
  13294. if (fromLeft) {
  13295. barX += 1;
  13296. barW -= 1;
  13297. }
  13298. if (fromTop) {
  13299. barY -= 1;
  13300. barH += 1;
  13301. }
  13302. // Register shape type and arguments to be used in drawPoints
  13303. point.shapeType = 'rect';
  13304. point.shapeArgs = {
  13305. x: barX,
  13306. y: barY,
  13307. width: barW,
  13308. height: barH
  13309. };
  13310. });
  13311. },
  13312. getSymbol: noop,
  13313. /**
  13314. * Use a solid rectangle like the area series types
  13315. */
  13316. drawLegendSymbol: LegendSymbolMixin.drawRectangle,
  13317. /**
  13318. * Columns have no graph
  13319. */
  13320. drawGraph: noop,
  13321. /**
  13322. * Draw the columns. For bars, the series.group is rotated, so the same coordinates
  13323. * apply for columns and bars. This method is inherited by scatter series.
  13324. *
  13325. */
  13326. drawPoints: function () {
  13327. var series = this,
  13328. chart = this.chart,
  13329. options = series.options,
  13330. renderer = chart.renderer,
  13331. animationLimit = options.animationLimit || 250,
  13332. shapeArgs,
  13333. pointAttr,
  13334. borderAttr;
  13335. // draw the columns
  13336. each(series.points, function (point) {
  13337. var plotY = point.plotY,
  13338. graphic = point.graphic;
  13339. if (plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) {
  13340. shapeArgs = point.shapeArgs;
  13341. borderAttr = defined(series.borderWidth) ? {
  13342. 'stroke-width': series.borderWidth
  13343. } : {};
  13344. pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || series.pointAttr[NORMAL_STATE];
  13345. if (graphic) { // update
  13346. stop(graphic);
  13347. graphic.attr(borderAttr)[chart.pointCount < animationLimit ? 'animate' : 'attr'](merge(shapeArgs));
  13348. } else {
  13349. point.graphic = graphic = renderer[point.shapeType](shapeArgs)
  13350. .attr(pointAttr)
  13351. .attr(borderAttr)
  13352. .add(series.group)
  13353. .shadow(options.shadow, null, options.stacking && !options.borderRadius);
  13354. }
  13355. } else if (graphic) {
  13356. point.graphic = graphic.destroy(); // #1269
  13357. }
  13358. });
  13359. },
  13360. /**
  13361. * Animate the column heights one by one from zero
  13362. * @param {Boolean} init Whether to initialize the animation or run it
  13363. */
  13364. animate: function (init) {
  13365. var series = this,
  13366. yAxis = this.yAxis,
  13367. options = series.options,
  13368. inverted = this.chart.inverted,
  13369. attr = {},
  13370. translatedThreshold;
  13371. if (hasSVG) { // VML is too slow anyway
  13372. if (init) {
  13373. attr.scaleY = 0.001;
  13374. translatedThreshold = mathMin(yAxis.pos + yAxis.len, mathMax(yAxis.pos, yAxis.toPixels(options.threshold)));
  13375. if (inverted) {
  13376. attr.translateX = translatedThreshold - yAxis.len;
  13377. } else {
  13378. attr.translateY = translatedThreshold;
  13379. }
  13380. series.group.attr(attr);
  13381. } else { // run the animation
  13382. attr.scaleY = 1;
  13383. attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos;
  13384. series.group.animate(attr, series.options.animation);
  13385. // delete this function to allow it only once
  13386. series.animate = null;
  13387. }
  13388. }
  13389. },
  13390. /**
  13391. * Remove this series from the chart
  13392. */
  13393. remove: function () {
  13394. var series = this,
  13395. chart = series.chart;
  13396. // column and bar series affects other series of the same type
  13397. // as they are either stacked or grouped
  13398. if (chart.hasRendered) {
  13399. each(chart.series, function (otherSeries) {
  13400. if (otherSeries.type === series.type) {
  13401. otherSeries.isDirty = true;
  13402. }
  13403. });
  13404. }
  13405. Series.prototype.remove.apply(series, arguments);
  13406. }
  13407. });
  13408. seriesTypes.column = ColumnSeries;
  13409. /**
  13410. * Set the default options for bar
  13411. */
  13412. defaultPlotOptions.bar = merge(defaultPlotOptions.column);
  13413. /**
  13414. * The Bar series class
  13415. */
  13416. var BarSeries = extendClass(ColumnSeries, {
  13417. type: 'bar',
  13418. inverted: true
  13419. });
  13420. seriesTypes.bar = BarSeries;
  13421. /**
  13422. * Set the default options for scatter
  13423. */
  13424. defaultPlotOptions.scatter = merge(defaultSeriesOptions, {
  13425. lineWidth: 0,
  13426. tooltip: {
  13427. headerFormat: '<span style="color:{series.color}">\u25CF</span> <span style="font-size: 10px;"> {series.name}</span><br/>', // docs
  13428. pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>'
  13429. },
  13430. stickyTracking: false
  13431. });
  13432. /**
  13433. * The scatter series class
  13434. */
  13435. var ScatterSeries = extendClass(Series, {
  13436. type: 'scatter',
  13437. sorted: false,
  13438. requireSorting: false,
  13439. noSharedTooltip: true,
  13440. trackerGroups: ['markerGroup'],
  13441. takeOrdinalPosition: false, // #2342
  13442. singularTooltips: true,
  13443. drawGraph: function () {
  13444. if (this.options.lineWidth) {
  13445. Series.prototype.drawGraph.call(this);
  13446. }
  13447. }
  13448. });
  13449. seriesTypes.scatter = ScatterSeries;
  13450. /**
  13451. * Set the default options for pie
  13452. */
  13453. defaultPlotOptions.pie = merge(defaultSeriesOptions, {
  13454. borderColor: '#FFFFFF',
  13455. borderWidth: 1,
  13456. center: [null, null],
  13457. clip: false,
  13458. colorByPoint: true, // always true for pies
  13459. dataLabels: {
  13460. // align: null,
  13461. // connectorWidth: 1,
  13462. // connectorColor: point.color,
  13463. // connectorPadding: 5,
  13464. distance: 30,
  13465. enabled: true,
  13466. formatter: function () {
  13467. return this.point.name;
  13468. }
  13469. // softConnector: true,
  13470. //y: 0
  13471. },
  13472. ignoreHiddenPoint: true,
  13473. //innerSize: 0,
  13474. legendType: 'point',
  13475. marker: null, // point options are specified in the base options
  13476. size: null,
  13477. showInLegend: false,
  13478. slicedOffset: 10,
  13479. states: {
  13480. hover: {
  13481. brightness: 0.1,
  13482. shadow: false
  13483. }
  13484. },
  13485. stickyTracking: false,
  13486. tooltip: {
  13487. followPointer: true
  13488. }
  13489. });
  13490. /**
  13491. * Extended point object for pies
  13492. */
  13493. var PiePoint = extendClass(Point, {
  13494. /**
  13495. * Initiate the pie slice
  13496. */
  13497. init: function () {
  13498. Point.prototype.init.apply(this, arguments);
  13499. var point = this,
  13500. toggleSlice;
  13501. // Disallow negative values (#1530)
  13502. if (point.y < 0) {
  13503. point.y = null;
  13504. }
  13505. //visible: options.visible !== false,
  13506. extend(point, {
  13507. visible: point.visible !== false,
  13508. name: pick(point.name, 'Slice')
  13509. });
  13510. // add event listener for select
  13511. toggleSlice = function (e) {
  13512. point.slice(e.type === 'select');
  13513. };
  13514. addEvent(point, 'select', toggleSlice);
  13515. addEvent(point, 'unselect', toggleSlice);
  13516. return point;
  13517. },
  13518. /**
  13519. * Toggle the visibility of the pie slice
  13520. * @param {Boolean} vis Whether to show the slice or not. If undefined, the
  13521. * visibility is toggled
  13522. */
  13523. setVisible: function (vis) {
  13524. var point = this,
  13525. series = point.series,
  13526. chart = series.chart;
  13527. // if called without an argument, toggle visibility
  13528. point.visible = point.options.visible = vis = vis === UNDEFINED ? !point.visible : vis;
  13529. series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data
  13530. // Show and hide associated elements
  13531. each(['graphic', 'dataLabel', 'connector', 'shadowGroup'], function (key) {
  13532. if (point[key]) {
  13533. point[key][vis ? 'show' : 'hide'](true);
  13534. }
  13535. });
  13536. if (point.legendItem) {
  13537. chart.legend.colorizeItem(point, vis);
  13538. }
  13539. // Handle ignore hidden slices
  13540. if (!series.isDirty && series.options.ignoreHiddenPoint) {
  13541. series.isDirty = true;
  13542. chart.redraw();
  13543. }
  13544. },
  13545. /**
  13546. * Set or toggle whether the slice is cut out from the pie
  13547. * @param {Boolean} sliced When undefined, the slice state is toggled
  13548. * @param {Boolean} redraw Whether to redraw the chart. True by default.
  13549. */
  13550. slice: function (sliced, redraw, animation) {
  13551. var point = this,
  13552. series = point.series,
  13553. chart = series.chart,
  13554. translation;
  13555. setAnimation(animation, chart);
  13556. // redraw is true by default
  13557. redraw = pick(redraw, true);
  13558. // if called without an argument, toggle
  13559. point.sliced = point.options.sliced = sliced = defined(sliced) ? sliced : !point.sliced;
  13560. series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data
  13561. translation = sliced ? point.slicedTranslation : {
  13562. translateX: 0,
  13563. translateY: 0
  13564. };
  13565. point.graphic.animate(translation);
  13566. if (point.shadowGroup) {
  13567. point.shadowGroup.animate(translation);
  13568. }
  13569. },
  13570. haloPath: function (size) {
  13571. var shapeArgs = this.shapeArgs,
  13572. chart = this.series.chart;
  13573. return this.series.chart.renderer.symbols.arc(chart.plotLeft + shapeArgs.x, chart.plotTop + shapeArgs.y, shapeArgs.r + size, shapeArgs.r + size, {
  13574. innerR: this.shapeArgs.r,
  13575. start: shapeArgs.start,
  13576. end: shapeArgs.end
  13577. });
  13578. }
  13579. });
  13580. /**
  13581. * The Pie series class
  13582. */
  13583. var PieSeries = {
  13584. type: 'pie',
  13585. isCartesian: false,
  13586. pointClass: PiePoint,
  13587. requireSorting: false,
  13588. noSharedTooltip: true,
  13589. trackerGroups: ['group', 'dataLabelsGroup'],
  13590. axisTypes: [],
  13591. pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
  13592. stroke: 'borderColor',
  13593. 'stroke-width': 'borderWidth',
  13594. fill: 'color'
  13595. },
  13596. singularTooltips: true,
  13597. /**
  13598. * Pies have one color each point
  13599. */
  13600. getColor: noop,
  13601. /**
  13602. * Animate the pies in
  13603. */
  13604. animate: function (init) {
  13605. var series = this,
  13606. points = series.points,
  13607. startAngleRad = series.startAngleRad;
  13608. if (!init) {
  13609. each(points, function (point) {
  13610. var graphic = point.graphic,
  13611. args = point.shapeArgs;
  13612. if (graphic) {
  13613. // start values
  13614. graphic.attr({
  13615. r: series.center[3] / 2, // animate from inner radius (#779)
  13616. start: startAngleRad,
  13617. end: startAngleRad
  13618. });
  13619. // animate
  13620. graphic.animate({
  13621. r: args.r,
  13622. start: args.start,
  13623. end: args.end
  13624. }, series.options.animation);
  13625. }
  13626. });
  13627. // delete this function to allow it only once
  13628. series.animate = null;
  13629. }
  13630. },
  13631. /**
  13632. * Extend the basic setData method by running processData and generatePoints immediately,
  13633. * in order to access the points from the legend.
  13634. */
  13635. setData: function (data, redraw, animation, updatePoints) {
  13636. Series.prototype.setData.call(this, data, false, animation, updatePoints);
  13637. this.processData();
  13638. this.generatePoints();
  13639. if (pick(redraw, true)) {
  13640. this.chart.redraw(animation);
  13641. }
  13642. },
  13643. /**
  13644. * Extend the generatePoints method by adding total and percentage properties to each point
  13645. */
  13646. generatePoints: function () {
  13647. var i,
  13648. total = 0,
  13649. points,
  13650. len,
  13651. point,
  13652. ignoreHiddenPoint = this.options.ignoreHiddenPoint;
  13653. Series.prototype.generatePoints.call(this);
  13654. // Populate local vars
  13655. points = this.points;
  13656. len = points.length;
  13657. // Get the total sum
  13658. for (i = 0; i < len; i++) {
  13659. point = points[i];
  13660. total += (ignoreHiddenPoint && !point.visible) ? 0 : point.y;
  13661. }
  13662. this.total = total;
  13663. // Set each point's properties
  13664. for (i = 0; i < len; i++) {
  13665. point = points[i];
  13666. point.percentage = total > 0 ? (point.y / total) * 100 : 0;
  13667. point.total = total;
  13668. }
  13669. },
  13670. /**
  13671. * Do translation for pie slices
  13672. */
  13673. translate: function (positions) {
  13674. this.generatePoints();
  13675. var series = this,
  13676. cumulative = 0,
  13677. precision = 1000, // issue #172
  13678. options = series.options,
  13679. slicedOffset = options.slicedOffset,
  13680. connectorOffset = slicedOffset + options.borderWidth,
  13681. start,
  13682. end,
  13683. angle,
  13684. startAngle = options.startAngle || 0,
  13685. startAngleRad = series.startAngleRad = mathPI / 180 * (startAngle - 90),
  13686. endAngleRad = series.endAngleRad = mathPI / 180 * ((pick(options.endAngle, startAngle + 360)) - 90),
  13687. circ = endAngleRad - startAngleRad, //2 * mathPI,
  13688. points = series.points,
  13689. radiusX, // the x component of the radius vector for a given point
  13690. radiusY,
  13691. labelDistance = options.dataLabels.distance,
  13692. ignoreHiddenPoint = options.ignoreHiddenPoint,
  13693. i,
  13694. len = points.length,
  13695. point;
  13696. // Get positions - either an integer or a percentage string must be given.
  13697. // If positions are passed as a parameter, we're in a recursive loop for adjusting
  13698. // space for data labels.
  13699. if (!positions) {
  13700. series.center = positions = series.getCenter();
  13701. }
  13702. // utility for getting the x value from a given y, used for anticollision logic in data labels
  13703. series.getX = function (y, left) {
  13704. angle = math.asin(mathMin((y - positions[1]) / (positions[2] / 2 + labelDistance), 1));
  13705. return positions[0] +
  13706. (left ? -1 : 1) *
  13707. (mathCos(angle) * (positions[2] / 2 + labelDistance));
  13708. };
  13709. // Calculate the geometry for each point
  13710. for (i = 0; i < len; i++) {
  13711. point = points[i];
  13712. // set start and end angle
  13713. start = startAngleRad + (cumulative * circ);
  13714. if (!ignoreHiddenPoint || point.visible) {
  13715. cumulative += point.percentage / 100;
  13716. }
  13717. end = startAngleRad + (cumulative * circ);
  13718. // set the shape
  13719. point.shapeType = 'arc';
  13720. point.shapeArgs = {
  13721. x: positions[0],
  13722. y: positions[1],
  13723. r: positions[2] / 2,
  13724. innerR: positions[3] / 2,
  13725. start: mathRound(start * precision) / precision,
  13726. end: mathRound(end * precision) / precision
  13727. };
  13728. // The angle must stay within -90 and 270 (#2645)
  13729. angle = (end + start) / 2;
  13730. if (angle > 1.5 * mathPI) {
  13731. angle -= 2 * mathPI;
  13732. } else if (angle < -mathPI / 2) {
  13733. angle += 2 * mathPI;
  13734. }
  13735. // Center for the sliced out slice
  13736. point.slicedTranslation = {
  13737. translateX: mathRound(mathCos(angle) * slicedOffset),
  13738. translateY: mathRound(mathSin(angle) * slicedOffset)
  13739. };
  13740. // set the anchor point for tooltips
  13741. radiusX = mathCos(angle) * positions[2] / 2;
  13742. radiusY = mathSin(angle) * positions[2] / 2;
  13743. point.tooltipPos = [
  13744. positions[0] + radiusX * 0.7,
  13745. positions[1] + radiusY * 0.7
  13746. ];
  13747. point.half = angle < -mathPI / 2 || angle > mathPI / 2 ? 1 : 0;
  13748. point.angle = angle;
  13749. // set the anchor point for data labels
  13750. connectorOffset = mathMin(connectorOffset, labelDistance / 2); // #1678
  13751. point.labelPos = [
  13752. positions[0] + radiusX + mathCos(angle) * labelDistance, // first break of connector
  13753. positions[1] + radiusY + mathSin(angle) * labelDistance, // a/a
  13754. positions[0] + radiusX + mathCos(angle) * connectorOffset, // second break, right outside pie
  13755. positions[1] + radiusY + mathSin(angle) * connectorOffset, // a/a
  13756. positions[0] + radiusX, // landing point for connector
  13757. positions[1] + radiusY, // a/a
  13758. labelDistance < 0 ? // alignment
  13759. 'center' :
  13760. point.half ? 'right' : 'left', // alignment
  13761. angle // center angle
  13762. ];
  13763. }
  13764. },
  13765. drawGraph: null,
  13766. /**
  13767. * Draw the data points
  13768. */
  13769. drawPoints: function () {
  13770. var series = this,
  13771. chart = series.chart,
  13772. renderer = chart.renderer,
  13773. groupTranslation,
  13774. //center,
  13775. graphic,
  13776. //group,
  13777. shadow = series.options.shadow,
  13778. shadowGroup,
  13779. shapeArgs;
  13780. if (shadow && !series.shadowGroup) {
  13781. series.shadowGroup = renderer.g('shadow')
  13782. .add(series.group);
  13783. }
  13784. // draw the slices
  13785. each(series.points, function (point) {
  13786. graphic = point.graphic;
  13787. shapeArgs = point.shapeArgs;
  13788. shadowGroup = point.shadowGroup;
  13789. // put the shadow behind all points
  13790. if (shadow && !shadowGroup) {
  13791. shadowGroup = point.shadowGroup = renderer.g('shadow')
  13792. .add(series.shadowGroup);
  13793. }
  13794. // if the point is sliced, use special translation, else use plot area traslation
  13795. groupTranslation = point.sliced ? point.slicedTranslation : {
  13796. translateX: 0,
  13797. translateY: 0
  13798. };
  13799. //group.translate(groupTranslation[0], groupTranslation[1]);
  13800. if (shadowGroup) {
  13801. shadowGroup.attr(groupTranslation);
  13802. }
  13803. // draw the slice
  13804. if (graphic) {
  13805. graphic.animate(extend(shapeArgs, groupTranslation));
  13806. } else {
  13807. point.graphic = graphic = renderer[point.shapeType](shapeArgs)
  13808. .setRadialReference(series.center)
  13809. .attr(
  13810. point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE]
  13811. )
  13812. .attr({
  13813. 'stroke-linejoin': 'round'
  13814. //zIndex: 1 // #2722 (reversed)
  13815. })
  13816. .attr(groupTranslation)
  13817. .add(series.group)
  13818. .shadow(shadow, shadowGroup);
  13819. }
  13820. // detect point specific visibility (#2430)
  13821. if (point.visible !== undefined) {
  13822. point.setVisible(point.visible);
  13823. }
  13824. });
  13825. },
  13826. /**
  13827. * Utility for sorting data labels
  13828. */
  13829. sortByAngle: function (points, sign) {
  13830. points.sort(function (a, b) {
  13831. return a.angle !== undefined && (b.angle - a.angle) * sign;
  13832. });
  13833. },
  13834. /**
  13835. * Use a simple symbol from LegendSymbolMixin
  13836. */
  13837. drawLegendSymbol: LegendSymbolMixin.drawRectangle,
  13838. /**
  13839. * Use the getCenter method from drawLegendSymbol
  13840. */
  13841. getCenter: CenteredSeriesMixin.getCenter,
  13842. /**
  13843. * Pies don't have point marker symbols
  13844. */
  13845. getSymbol: noop
  13846. };
  13847. PieSeries = extendClass(Series, PieSeries);
  13848. seriesTypes.pie = PieSeries;
  13849. /**
  13850. * Draw the data labels
  13851. */
  13852. Series.prototype.drawDataLabels = function () {
  13853. var series = this,
  13854. seriesOptions = series.options,
  13855. cursor = seriesOptions.cursor,
  13856. options = seriesOptions.dataLabels,
  13857. points = series.points,
  13858. pointOptions,
  13859. generalOptions,
  13860. str,
  13861. dataLabelsGroup;
  13862. if (options.enabled || series._hasPointLabels) {
  13863. // Process default alignment of data labels for columns
  13864. if (series.dlProcessOptions) {
  13865. series.dlProcessOptions(options);
  13866. }
  13867. // Create a separate group for the data labels to avoid rotation
  13868. dataLabelsGroup = series.plotGroup(
  13869. 'dataLabelsGroup',
  13870. 'data-labels',
  13871. HIDDEN,
  13872. options.zIndex || 6
  13873. );
  13874. if (!series.hasRendered && pick(options.defer, true)) {
  13875. dataLabelsGroup.attr({ opacity: 0 });
  13876. addEvent(series, 'afterAnimate', function () {
  13877. series.dataLabelsGroup.show()[seriesOptions.animation ? 'animate' : 'attr']({ opacity: 1 }, { duration: 200 });
  13878. });
  13879. }
  13880. // Make the labels for each point
  13881. generalOptions = options;
  13882. each(points, function (point) {
  13883. var enabled,
  13884. dataLabel = point.dataLabel,
  13885. labelConfig,
  13886. attr,
  13887. name,
  13888. rotation,
  13889. connector = point.connector,
  13890. isNew = true;
  13891. // Determine if each data label is enabled
  13892. pointOptions = point.options && point.options.dataLabels;
  13893. enabled = pick(pointOptions && pointOptions.enabled, generalOptions.enabled); // #2282
  13894. // If the point is outside the plot area, destroy it. #678, #820
  13895. if (dataLabel && !enabled) {
  13896. point.dataLabel = dataLabel.destroy();
  13897. // Individual labels are disabled if the are explicitly disabled
  13898. // in the point options, or if they fall outside the plot area.
  13899. } else if (enabled) {
  13900. // Create individual options structure that can be extended without
  13901. // affecting others
  13902. options = merge(generalOptions, pointOptions);
  13903. rotation = options.rotation;
  13904. // Get the string
  13905. labelConfig = point.getLabelConfig();
  13906. str = options.format ?
  13907. format(options.format, labelConfig) :
  13908. options.formatter.call(labelConfig, options);
  13909. // Determine the color
  13910. options.style.color = pick(options.color, options.style.color, series.color, 'black');
  13911. // update existing label
  13912. if (dataLabel) {
  13913. if (defined(str)) {
  13914. dataLabel
  13915. .attr({
  13916. text: str
  13917. });
  13918. isNew = false;
  13919. } else { // #1437 - the label is shown conditionally
  13920. point.dataLabel = dataLabel = dataLabel.destroy();
  13921. if (connector) {
  13922. point.connector = connector.destroy();
  13923. }
  13924. }
  13925. // create new label
  13926. } else if (defined(str)) {
  13927. attr = {
  13928. //align: align,
  13929. fill: options.backgroundColor,
  13930. stroke: options.borderColor,
  13931. 'stroke-width': options.borderWidth,
  13932. r: options.borderRadius || 0,
  13933. rotation: rotation,
  13934. padding: options.padding,
  13935. zIndex: 1
  13936. };
  13937. // Remove unused attributes (#947)
  13938. for (name in attr) {
  13939. if (attr[name] === UNDEFINED) {
  13940. delete attr[name];
  13941. }
  13942. }
  13943. dataLabel = point.dataLabel = series.chart.renderer[rotation ? 'text' : 'label']( // labels don't support rotation
  13944. str,
  13945. 0,
  13946. -999,
  13947. null,
  13948. null,
  13949. null,
  13950. options.useHTML
  13951. )
  13952. .attr(attr)
  13953. .css(extend(options.style, cursor && { cursor: cursor }))
  13954. .add(dataLabelsGroup)
  13955. .shadow(options.shadow);
  13956. }
  13957. if (dataLabel) {
  13958. // Now the data label is created and placed at 0,0, so we need to align it
  13959. series.alignDataLabel(point, dataLabel, options, null, isNew);
  13960. }
  13961. }
  13962. });
  13963. }
  13964. };
  13965. /**
  13966. * Align each individual data label
  13967. */
  13968. Series.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) {
  13969. var chart = this.chart,
  13970. inverted = chart.inverted,
  13971. plotX = pick(point.plotX, -999),
  13972. plotY = pick(point.plotY, -999),
  13973. bBox = dataLabel.getBBox(),
  13974. // Math.round for rounding errors (#2683), alignTo to allow column labels (#2700)
  13975. visible = this.visible && (point.series.forceDL || chart.isInsidePlot(plotX, mathRound(plotY), inverted) ||
  13976. (alignTo && chart.isInsidePlot(plotX, inverted ? alignTo.x + 1 : alignTo.y + alignTo.height - 1, inverted))),
  13977. alignAttr; // the final position;
  13978. if (visible) {
  13979. // The alignment box is a singular point
  13980. alignTo = extend({
  13981. x: inverted ? chart.plotWidth - plotY : plotX,
  13982. y: mathRound(inverted ? chart.plotHeight - plotX : plotY),
  13983. width: 0,
  13984. height: 0
  13985. }, alignTo);
  13986. // Add the text size for alignment calculation
  13987. extend(options, {
  13988. width: bBox.width,
  13989. height: bBox.height
  13990. });
  13991. // Allow a hook for changing alignment in the last moment, then do the alignment
  13992. if (options.rotation) { // Fancy box alignment isn't supported for rotated text
  13993. alignAttr = {
  13994. align: options.align,
  13995. x: alignTo.x + options.x + alignTo.width / 2,
  13996. y: alignTo.y + options.y + alignTo.height / 2
  13997. };
  13998. dataLabel[isNew ? 'attr' : 'animate'](alignAttr);
  13999. } else {
  14000. dataLabel.align(options, null, alignTo);
  14001. alignAttr = dataLabel.alignAttr;
  14002. // Handle justify or crop
  14003. if (pick(options.overflow, 'justify') === 'justify') {
  14004. this.justifyDataLabel(dataLabel, options, alignAttr, bBox, alignTo, isNew);
  14005. } else if (pick(options.crop, true)) {
  14006. // Now check that the data label is within the plot area
  14007. visible = chart.isInsidePlot(alignAttr.x, alignAttr.y) && chart.isInsidePlot(alignAttr.x + bBox.width, alignAttr.y + bBox.height);
  14008. }
  14009. }
  14010. }
  14011. // Show or hide based on the final aligned position
  14012. if (!visible) {
  14013. dataLabel.attr({ y: -999 });
  14014. dataLabel.placed = false; // don't animate back in
  14015. }
  14016. };
  14017. /**
  14018. * If data labels fall partly outside the plot area, align them back in, in a way that
  14019. * doesn't hide the point.
  14020. */
  14021. Series.prototype.justifyDataLabel = function (dataLabel, options, alignAttr, bBox, alignTo, isNew) {
  14022. var chart = this.chart,
  14023. align = options.align,
  14024. verticalAlign = options.verticalAlign,
  14025. off,
  14026. justified;
  14027. // Off left
  14028. off = alignAttr.x;
  14029. if (off < 0) {
  14030. if (align === 'right') {
  14031. options.align = 'left';
  14032. } else {
  14033. options.x = -off;
  14034. }
  14035. justified = true;
  14036. }
  14037. // Off right
  14038. off = alignAttr.x + bBox.width;
  14039. if (off > chart.plotWidth) {
  14040. if (align === 'left') {
  14041. options.align = 'right';
  14042. } else {
  14043. options.x = chart.plotWidth - off;
  14044. }
  14045. justified = true;
  14046. }
  14047. // Off top
  14048. off = alignAttr.y;
  14049. if (off < 0) {
  14050. if (verticalAlign === 'bottom') {
  14051. options.verticalAlign = 'top';
  14052. } else {
  14053. options.y = -off;
  14054. }
  14055. justified = true;
  14056. }
  14057. // Off bottom
  14058. off = alignAttr.y + bBox.height;
  14059. if (off > chart.plotHeight) {
  14060. if (verticalAlign === 'top') {
  14061. options.verticalAlign = 'bottom';
  14062. } else {
  14063. options.y = chart.plotHeight - off;
  14064. }
  14065. justified = true;
  14066. }
  14067. if (justified) {
  14068. dataLabel.placed = !isNew;
  14069. dataLabel.align(options, null, alignTo);
  14070. }
  14071. };
  14072. /**
  14073. * Override the base drawDataLabels method by pie specific functionality
  14074. */
  14075. if (seriesTypes.pie) {
  14076. seriesTypes.pie.prototype.drawDataLabels = function () {
  14077. var series = this,
  14078. data = series.data,
  14079. point,
  14080. chart = series.chart,
  14081. options = series.options.dataLabels,
  14082. connectorPadding = pick(options.connectorPadding, 10),
  14083. connectorWidth = pick(options.connectorWidth, 1),
  14084. plotWidth = chart.plotWidth,
  14085. plotHeight = chart.plotHeight,
  14086. connector,
  14087. connectorPath,
  14088. softConnector = pick(options.softConnector, true),
  14089. distanceOption = options.distance,
  14090. seriesCenter = series.center,
  14091. radius = seriesCenter[2] / 2,
  14092. centerY = seriesCenter[1],
  14093. outside = distanceOption > 0,
  14094. dataLabel,
  14095. dataLabelWidth,
  14096. labelPos,
  14097. labelHeight,
  14098. halves = [// divide the points into right and left halves for anti collision
  14099. [], // right
  14100. [] // left
  14101. ],
  14102. x,
  14103. y,
  14104. visibility,
  14105. rankArr,
  14106. i,
  14107. j,
  14108. overflow = [0, 0, 0, 0], // top, right, bottom, left
  14109. sort = function (a, b) {
  14110. return b.y - a.y;
  14111. };
  14112. // get out if not enabled
  14113. if (!series.visible || (!options.enabled && !series._hasPointLabels)) {
  14114. return;
  14115. }
  14116. // run parent method
  14117. Series.prototype.drawDataLabels.apply(series);
  14118. // arrange points for detection collision
  14119. each(data, function (point) {
  14120. if (point.dataLabel && point.visible) { // #407, #2510
  14121. halves[point.half].push(point);
  14122. }
  14123. });
  14124. // assume equal label heights
  14125. i = 0;
  14126. while (!labelHeight && data[i]) { // #1569
  14127. labelHeight = data[i] && data[i].dataLabel && (data[i].dataLabel.getBBox().height || 21); // 21 is for #968
  14128. i++;
  14129. }
  14130. /* Loop over the points in each half, starting from the top and bottom
  14131. * of the pie to detect overlapping labels.
  14132. */
  14133. i = 2;
  14134. while (i--) {
  14135. var slots = [],
  14136. slotsLength,
  14137. usedSlots = [],
  14138. points = halves[i],
  14139. pos,
  14140. length = points.length,
  14141. slotIndex;
  14142. // Sort by angle
  14143. series.sortByAngle(points, i - 0.5);
  14144. // Only do anti-collision when we are outside the pie and have connectors (#856)
  14145. if (distanceOption > 0) {
  14146. // build the slots
  14147. for (pos = centerY - radius - distanceOption; pos <= centerY + radius + distanceOption; pos += labelHeight) {
  14148. slots.push(pos);
  14149. // visualize the slot
  14150. /*
  14151. var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0),
  14152. slotY = pos + chart.plotTop;
  14153. if (!isNaN(slotX)) {
  14154. chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1)
  14155. .attr({
  14156. 'stroke-width': 1,
  14157. stroke: 'silver'
  14158. })
  14159. .add();
  14160. chart.renderer.text('Slot '+ (slots.length - 1), slotX, slotY + 4)
  14161. .attr({
  14162. fill: 'silver'
  14163. }).add();
  14164. }
  14165. */
  14166. }
  14167. slotsLength = slots.length;
  14168. // if there are more values than available slots, remove lowest values
  14169. if (length > slotsLength) {
  14170. // create an array for sorting and ranking the points within each quarter
  14171. rankArr = [].concat(points);
  14172. rankArr.sort(sort);
  14173. j = length;
  14174. while (j--) {
  14175. rankArr[j].rank = j;
  14176. }
  14177. j = length;
  14178. while (j--) {
  14179. if (points[j].rank >= slotsLength) {
  14180. points.splice(j, 1);
  14181. }
  14182. }
  14183. length = points.length;
  14184. }
  14185. // The label goes to the nearest open slot, but not closer to the edge than
  14186. // the label's index.
  14187. for (j = 0; j < length; j++) {
  14188. point = points[j];
  14189. labelPos = point.labelPos;
  14190. var closest = 9999,
  14191. distance,
  14192. slotI;
  14193. // find the closest slot index
  14194. for (slotI = 0; slotI < slotsLength; slotI++) {
  14195. distance = mathAbs(slots[slotI] - labelPos[1]);
  14196. if (distance < closest) {
  14197. closest = distance;
  14198. slotIndex = slotI;
  14199. }
  14200. }
  14201. // if that slot index is closer to the edges of the slots, move it
  14202. // to the closest appropriate slot
  14203. if (slotIndex < j && slots[j] !== null) { // cluster at the top
  14204. slotIndex = j;
  14205. } else if (slotsLength < length - j + slotIndex && slots[j] !== null) { // cluster at the bottom
  14206. slotIndex = slotsLength - length + j;
  14207. while (slots[slotIndex] === null) { // make sure it is not taken
  14208. slotIndex++;
  14209. }
  14210. } else {
  14211. // Slot is taken, find next free slot below. In the next run, the next slice will find the
  14212. // slot above these, because it is the closest one
  14213. while (slots[slotIndex] === null) { // make sure it is not taken
  14214. slotIndex++;
  14215. }
  14216. }
  14217. usedSlots.push({ i: slotIndex, y: slots[slotIndex] });
  14218. slots[slotIndex] = null; // mark as taken
  14219. }
  14220. // sort them in order to fill in from the top
  14221. usedSlots.sort(sort);
  14222. }
  14223. // now the used slots are sorted, fill them up sequentially
  14224. for (j = 0; j < length; j++) {
  14225. var slot, naturalY;
  14226. point = points[j];
  14227. labelPos = point.labelPos;
  14228. dataLabel = point.dataLabel;
  14229. visibility = point.visible === false ? HIDDEN : VISIBLE;
  14230. naturalY = labelPos[1];
  14231. if (distanceOption > 0) {
  14232. slot = usedSlots.pop();
  14233. slotIndex = slot.i;
  14234. // if the slot next to currrent slot is free, the y value is allowed
  14235. // to fall back to the natural position
  14236. y = slot.y;
  14237. if ((naturalY > y && slots[slotIndex + 1] !== null) ||
  14238. (naturalY < y && slots[slotIndex - 1] !== null)) {
  14239. y = naturalY;
  14240. }
  14241. } else {
  14242. y = naturalY;
  14243. }
  14244. // get the x - use the natural x position for first and last slot, to prevent the top
  14245. // and botton slice connectors from touching each other on either side
  14246. x = options.justify ?
  14247. seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption) :
  14248. series.getX(slotIndex === 0 || slotIndex === slots.length - 1 ? naturalY : y, i);
  14249. // Record the placement and visibility
  14250. dataLabel._attr = {
  14251. visibility: visibility,
  14252. align: labelPos[6]
  14253. };
  14254. dataLabel._pos = {
  14255. x: x + options.x +
  14256. ({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0),
  14257. y: y + options.y - 10 // 10 is for the baseline (label vs text)
  14258. };
  14259. dataLabel.connX = x;
  14260. dataLabel.connY = y;
  14261. // Detect overflowing data labels
  14262. if (this.options.size === null) {
  14263. dataLabelWidth = dataLabel.width;
  14264. // Overflow left
  14265. if (x - dataLabelWidth < connectorPadding) {
  14266. overflow[3] = mathMax(mathRound(dataLabelWidth - x + connectorPadding), overflow[3]);
  14267. // Overflow right
  14268. } else if (x + dataLabelWidth > plotWidth - connectorPadding) {
  14269. overflow[1] = mathMax(mathRound(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]);
  14270. }
  14271. // Overflow top
  14272. if (y - labelHeight / 2 < 0) {
  14273. overflow[0] = mathMax(mathRound(-y + labelHeight / 2), overflow[0]);
  14274. // Overflow left
  14275. } else if (y + labelHeight / 2 > plotHeight) {
  14276. overflow[2] = mathMax(mathRound(y + labelHeight / 2 - plotHeight), overflow[2]);
  14277. }
  14278. }
  14279. } // for each point
  14280. } // for each half
  14281. // Do not apply the final placement and draw the connectors until we have verified
  14282. // that labels are not spilling over.
  14283. if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) {
  14284. // Place the labels in the final position
  14285. this.placeDataLabels();
  14286. // Draw the connectors
  14287. if (outside && connectorWidth) {
  14288. each(this.points, function (point) {
  14289. connector = point.connector;
  14290. labelPos = point.labelPos;
  14291. dataLabel = point.dataLabel;
  14292. if (dataLabel && dataLabel._pos) {
  14293. visibility = dataLabel._attr.visibility;
  14294. x = dataLabel.connX;
  14295. y = dataLabel.connY;
  14296. connectorPath = softConnector ? [
  14297. M,
  14298. x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
  14299. 'C',
  14300. x, y, // first break, next to the label
  14301. 2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5],
  14302. labelPos[2], labelPos[3], // second break
  14303. L,
  14304. labelPos[4], labelPos[5] // base
  14305. ] : [
  14306. M,
  14307. x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
  14308. L,
  14309. labelPos[2], labelPos[3], // second break
  14310. L,
  14311. labelPos[4], labelPos[5] // base
  14312. ];
  14313. if (connector) {
  14314. connector.animate({ d: connectorPath });
  14315. connector.attr('visibility', visibility);
  14316. } else {
  14317. point.connector = connector = series.chart.renderer.path(connectorPath).attr({
  14318. 'stroke-width': connectorWidth,
  14319. stroke: options.connectorColor || point.color || '#606060',
  14320. visibility: visibility
  14321. //zIndex: 0 // #2722 (reversed)
  14322. })
  14323. .add(series.dataLabelsGroup);
  14324. }
  14325. } else if (connector) {
  14326. point.connector = connector.destroy();
  14327. }
  14328. });
  14329. }
  14330. }
  14331. };
  14332. /**
  14333. * Perform the final placement of the data labels after we have verified that they
  14334. * fall within the plot area.
  14335. */
  14336. seriesTypes.pie.prototype.placeDataLabels = function () {
  14337. each(this.points, function (point) {
  14338. var dataLabel = point.dataLabel,
  14339. _pos;
  14340. if (dataLabel) {
  14341. _pos = dataLabel._pos;
  14342. if (_pos) {
  14343. dataLabel.attr(dataLabel._attr);
  14344. dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos);
  14345. dataLabel.moved = true;
  14346. } else if (dataLabel) {
  14347. dataLabel.attr({ y: -999 });
  14348. }
  14349. }
  14350. });
  14351. };
  14352. seriesTypes.pie.prototype.alignDataLabel = noop;
  14353. /**
  14354. * Verify whether the data labels are allowed to draw, or we should run more translation and data
  14355. * label positioning to keep them inside the plot area. Returns true when data labels are ready
  14356. * to draw.
  14357. */
  14358. seriesTypes.pie.prototype.verifyDataLabelOverflow = function (overflow) {
  14359. var center = this.center,
  14360. options = this.options,
  14361. centerOption = options.center,
  14362. minSize = options.minSize || 80,
  14363. newSize = minSize,
  14364. ret;
  14365. // Handle horizontal size and center
  14366. if (centerOption[0] !== null) { // Fixed center
  14367. newSize = mathMax(center[2] - mathMax(overflow[1], overflow[3]), minSize);
  14368. } else { // Auto center
  14369. newSize = mathMax(
  14370. center[2] - overflow[1] - overflow[3], // horizontal overflow
  14371. minSize
  14372. );
  14373. center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center
  14374. }
  14375. // Handle vertical size and center
  14376. if (centerOption[1] !== null) { // Fixed center
  14377. newSize = mathMax(mathMin(newSize, center[2] - mathMax(overflow[0], overflow[2])), minSize);
  14378. } else { // Auto center
  14379. newSize = mathMax(
  14380. mathMin(
  14381. newSize,
  14382. center[2] - overflow[0] - overflow[2] // vertical overflow
  14383. ),
  14384. minSize
  14385. );
  14386. center[1] += (overflow[0] - overflow[2]) / 2; // vertical center
  14387. }
  14388. // If the size must be decreased, we need to run translate and drawDataLabels again
  14389. if (newSize < center[2]) {
  14390. center[2] = newSize;
  14391. this.translate(center);
  14392. each(this.points, function (point) {
  14393. if (point.dataLabel) {
  14394. point.dataLabel._pos = null; // reset
  14395. }
  14396. });
  14397. if (this.drawDataLabels) {
  14398. this.drawDataLabels();
  14399. }
  14400. // Else, return true to indicate that the pie and its labels is within the plot area
  14401. } else {
  14402. ret = true;
  14403. }
  14404. return ret;
  14405. };
  14406. }
  14407. if (seriesTypes.column) {
  14408. /**
  14409. * Override the basic data label alignment by adjusting for the position of the column
  14410. */
  14411. seriesTypes.column.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) {
  14412. var chart = this.chart,
  14413. inverted = chart.inverted,
  14414. dlBox = point.dlBox || point.shapeArgs, // data label box for alignment
  14415. below = point.below || (point.plotY > pick(this.translatedThreshold, chart.plotSizeY)),
  14416. inside = pick(options.inside, !!this.options.stacking); // draw it inside the box?
  14417. // Align to the column itself, or the top of it
  14418. if (dlBox) { // Area range uses this method but not alignTo
  14419. alignTo = merge(dlBox);
  14420. if (inverted) {
  14421. alignTo = {
  14422. x: chart.plotWidth - alignTo.y - alignTo.height,
  14423. y: chart.plotHeight - alignTo.x - alignTo.width,
  14424. width: alignTo.height,
  14425. height: alignTo.width
  14426. };
  14427. }
  14428. // Compute the alignment box
  14429. if (!inside) {
  14430. if (inverted) {
  14431. alignTo.x += below ? 0 : alignTo.width;
  14432. alignTo.width = 0;
  14433. } else {
  14434. alignTo.y += below ? alignTo.height : 0;
  14435. alignTo.height = 0;
  14436. }
  14437. }
  14438. }
  14439. // When alignment is undefined (typically columns and bars), display the individual
  14440. // point below or above the point depending on the threshold
  14441. options.align = pick(
  14442. options.align,
  14443. !inverted || inside ? 'center' : below ? 'right' : 'left'
  14444. );
  14445. options.verticalAlign = pick(
  14446. options.verticalAlign,
  14447. inverted || inside ? 'middle' : below ? 'top' : 'bottom'
  14448. );
  14449. // Call the parent method
  14450. Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew);
  14451. };
  14452. }
  14453. /**
  14454. * TrackerMixin for points and graphs
  14455. */
  14456. var TrackerMixin = Highcharts.TrackerMixin = {
  14457. drawTrackerPoint: function () {
  14458. var series = this,
  14459. chart = series.chart,
  14460. pointer = chart.pointer,
  14461. cursor = series.options.cursor,
  14462. css = cursor && { cursor: cursor },
  14463. onMouseOver = function (e) {
  14464. var target = e.target,
  14465. point;
  14466. if (chart.hoverSeries !== series) {
  14467. series.onMouseOver();
  14468. }
  14469. while (target && !point) {
  14470. point = target.point;
  14471. target = target.parentNode;
  14472. }
  14473. if (point !== UNDEFINED && point !== chart.hoverPoint) { // undefined on graph in scatterchart
  14474. point.onMouseOver(e);
  14475. }
  14476. };
  14477. // Add reference to the point
  14478. each(series.points, function (point) {
  14479. if (point.graphic) {
  14480. point.graphic.element.point = point;
  14481. }
  14482. if (point.dataLabel) {
  14483. point.dataLabel.element.point = point;
  14484. }
  14485. });
  14486. // Add the event listeners, we need to do this only once
  14487. if (!series._hasTracking) {
  14488. each(series.trackerGroups, function (key) {
  14489. if (series[key]) { // we don't always have dataLabelsGroup
  14490. series[key]
  14491. .addClass(PREFIX + 'tracker')
  14492. .on('mouseover', onMouseOver)
  14493. .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); })
  14494. .css(css);
  14495. if (hasTouch) {
  14496. series[key].on('touchstart', onMouseOver);
  14497. }
  14498. }
  14499. });
  14500. series._hasTracking = true;
  14501. }
  14502. },
  14503. /**
  14504. * Draw the tracker object that sits above all data labels and markers to
  14505. * track mouse events on the graph or points. For the line type charts
  14506. * the tracker uses the same graphPath, but with a greater stroke width
  14507. * for better control.
  14508. */
  14509. drawTrackerGraph: function () {
  14510. var series = this,
  14511. options = series.options,
  14512. trackByArea = options.trackByArea,
  14513. trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath),
  14514. trackerPathLength = trackerPath.length,
  14515. chart = series.chart,
  14516. pointer = chart.pointer,
  14517. renderer = chart.renderer,
  14518. snap = chart.options.tooltip.snap,
  14519. tracker = series.tracker,
  14520. cursor = options.cursor,
  14521. css = cursor && { cursor: cursor },
  14522. singlePoints = series.singlePoints,
  14523. singlePoint,
  14524. i,
  14525. onMouseOver = function () {
  14526. if (chart.hoverSeries !== series) {
  14527. series.onMouseOver();
  14528. }
  14529. },
  14530. /*
  14531. * Empirical lowest possible opacities for TRACKER_FILL for an element to stay invisible but clickable
  14532. * IE6: 0.002
  14533. * IE7: 0.002
  14534. * IE8: 0.002
  14535. * IE9: 0.00000000001 (unlimited)
  14536. * IE10: 0.0001 (exporting only)
  14537. * FF: 0.00000000001 (unlimited)
  14538. * Chrome: 0.000001
  14539. * Safari: 0.000001
  14540. * Opera: 0.00000000001 (unlimited)
  14541. */
  14542. TRACKER_FILL = 'rgba(192,192,192,' + (hasSVG ? 0.0001 : 0.002) + ')';
  14543. // Extend end points. A better way would be to use round linecaps,
  14544. // but those are not clickable in VML.
  14545. if (trackerPathLength && !trackByArea) {
  14546. i = trackerPathLength + 1;
  14547. while (i--) {
  14548. if (trackerPath[i] === M) { // extend left side
  14549. trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L);
  14550. }
  14551. if ((i && trackerPath[i] === M) || i === trackerPathLength) { // extend right side
  14552. trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]);
  14553. }
  14554. }
  14555. }
  14556. // handle single points
  14557. for (i = 0; i < singlePoints.length; i++) {
  14558. singlePoint = singlePoints[i];
  14559. trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY,
  14560. L, singlePoint.plotX + snap, singlePoint.plotY);
  14561. }
  14562. // draw the tracker
  14563. if (tracker) {
  14564. tracker.attr({ d: trackerPath });
  14565. } else { // create
  14566. series.tracker = renderer.path(trackerPath)
  14567. .attr({
  14568. 'stroke-linejoin': 'round', // #1225
  14569. visibility: series.visible ? VISIBLE : HIDDEN,
  14570. stroke: TRACKER_FILL,
  14571. fill: trackByArea ? TRACKER_FILL : NONE,
  14572. 'stroke-width' : options.lineWidth + (trackByArea ? 0 : 2 * snap),
  14573. zIndex: 2
  14574. })
  14575. .add(series.group);
  14576. // The tracker is added to the series group, which is clipped, but is covered
  14577. // by the marker group. So the marker group also needs to capture events.
  14578. each([series.tracker, series.markerGroup], function (tracker) {
  14579. tracker.addClass(PREFIX + 'tracker')
  14580. .on('mouseover', onMouseOver)
  14581. .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); })
  14582. .css(css);
  14583. if (hasTouch) {
  14584. tracker.on('touchstart', onMouseOver);
  14585. }
  14586. });
  14587. }
  14588. }
  14589. };
  14590. /* End TrackerMixin */
  14591. /**
  14592. * Add tracking event listener to the series group, so the point graphics
  14593. * themselves act as trackers
  14594. */
  14595. if (seriesTypes.column) {
  14596. ColumnSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
  14597. }
  14598. if (seriesTypes.pie) {
  14599. seriesTypes.pie.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
  14600. }
  14601. if (seriesTypes.scatter) {
  14602. ScatterSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
  14603. }
  14604. /*
  14605. * Extend Legend for item events
  14606. */
  14607. extend(Legend.prototype, {
  14608. setItemEvents: function (item, legendItem, useHTML, itemStyle, itemHiddenStyle) {
  14609. var legend = this;
  14610. // Set the events on the item group, or in case of useHTML, the item itself (#1249)
  14611. (useHTML ? legendItem : item.legendGroup).on('mouseover', function () {
  14612. item.setState(HOVER_STATE);
  14613. legendItem.css(legend.options.itemHoverStyle);
  14614. })
  14615. .on('mouseout', function () {
  14616. legendItem.css(item.visible ? itemStyle : itemHiddenStyle);
  14617. item.setState();
  14618. })
  14619. .on('click', function (event) {
  14620. var strLegendItemClick = 'legendItemClick',
  14621. fnLegendItemClick = function () {
  14622. item.setVisible();
  14623. };
  14624. // Pass over the click/touch event. #4.
  14625. event = {
  14626. browserEvent: event
  14627. };
  14628. // click the name or symbol
  14629. if (item.firePointEvent) { // point
  14630. item.firePointEvent(strLegendItemClick, event, fnLegendItemClick);
  14631. } else {
  14632. fireEvent(item, strLegendItemClick, event, fnLegendItemClick);
  14633. }
  14634. });
  14635. },
  14636. createCheckboxForItem: function (item) {
  14637. var legend = this;
  14638. item.checkbox = createElement('input', {
  14639. type: 'checkbox',
  14640. checked: item.selected,
  14641. defaultChecked: item.selected // required by IE7
  14642. }, legend.options.itemCheckboxStyle, legend.chart.container);
  14643. addEvent(item.checkbox, 'click', function (event) {
  14644. var target = event.target;
  14645. fireEvent(item, 'checkboxClick', {
  14646. checked: target.checked
  14647. },
  14648. function () {
  14649. item.select();
  14650. }
  14651. );
  14652. });
  14653. }
  14654. });
  14655. /*
  14656. * Add pointer cursor to legend itemstyle in defaultOptions
  14657. */
  14658. defaultOptions.legend.itemStyle.cursor = 'pointer';
  14659. /*
  14660. * Extend the Chart object with interaction
  14661. */
  14662. extend(Chart.prototype, {
  14663. /**
  14664. * Display the zoom button
  14665. */
  14666. showResetZoom: function () {
  14667. var chart = this,
  14668. lang = defaultOptions.lang,
  14669. btnOptions = chart.options.chart.resetZoomButton,
  14670. theme = btnOptions.theme,
  14671. states = theme.states,
  14672. alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox';
  14673. this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, function () { chart.zoomOut(); }, theme, states && states.hover)
  14674. .attr({
  14675. align: btnOptions.position.align,
  14676. title: lang.resetZoomTitle
  14677. })
  14678. .add()
  14679. .align(btnOptions.position, false, alignTo);
  14680. },
  14681. /**
  14682. * Zoom out to 1:1
  14683. */
  14684. zoomOut: function () {
  14685. var chart = this;
  14686. fireEvent(chart, 'selection', { resetSelection: true }, function () {
  14687. chart.zoom();
  14688. });
  14689. },
  14690. /**
  14691. * Zoom into a given portion of the chart given by axis coordinates
  14692. * @param {Object} event
  14693. */
  14694. zoom: function (event) {
  14695. var chart = this,
  14696. hasZoomed,
  14697. pointer = chart.pointer,
  14698. displayButton = false,
  14699. resetZoomButton;
  14700. // If zoom is called with no arguments, reset the axes
  14701. if (!event || event.resetSelection) {
  14702. each(chart.axes, function (axis) {
  14703. hasZoomed = axis.zoom();
  14704. });
  14705. } else { // else, zoom in on all axes
  14706. each(event.xAxis.concat(event.yAxis), function (axisData) {
  14707. var axis = axisData.axis,
  14708. isXAxis = axis.isXAxis;
  14709. // don't zoom more than minRange
  14710. if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) {
  14711. hasZoomed = axis.zoom(axisData.min, axisData.max);
  14712. if (axis.displayBtn) {
  14713. displayButton = true;
  14714. }
  14715. }
  14716. });
  14717. }
  14718. // Show or hide the Reset zoom button
  14719. resetZoomButton = chart.resetZoomButton;
  14720. if (displayButton && !resetZoomButton) {
  14721. chart.showResetZoom();
  14722. } else if (!displayButton && isObject(resetZoomButton)) {
  14723. chart.resetZoomButton = resetZoomButton.destroy();
  14724. }
  14725. // Redraw
  14726. if (hasZoomed) {
  14727. chart.redraw(
  14728. pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation
  14729. );
  14730. }
  14731. },
  14732. /**
  14733. * Pan the chart by dragging the mouse across the pane. This function is called
  14734. * on mouse move, and the distance to pan is computed from chartX compared to
  14735. * the first chartX position in the dragging operation.
  14736. */
  14737. pan: function (e, panning) {
  14738. var chart = this,
  14739. hoverPoints = chart.hoverPoints,
  14740. doRedraw;
  14741. // remove active points for shared tooltip
  14742. if (hoverPoints) {
  14743. each(hoverPoints, function (point) {
  14744. point.setState();
  14745. });
  14746. }
  14747. each(panning === 'xy' ? [1, 0] : [1], function (isX) { // xy is used in maps
  14748. var mousePos = e[isX ? 'chartX' : 'chartY'],
  14749. axis = chart[isX ? 'xAxis' : 'yAxis'][0],
  14750. startPos = chart[isX ? 'mouseDownX' : 'mouseDownY'],
  14751. halfPointRange = (axis.pointRange || 0) / 2,
  14752. extremes = axis.getExtremes(),
  14753. newMin = axis.toValue(startPos - mousePos, true) + halfPointRange,
  14754. newMax = axis.toValue(startPos + chart[isX ? 'plotWidth' : 'plotHeight'] - mousePos, true) - halfPointRange;
  14755. if (axis.series.length && newMin > mathMin(extremes.dataMin, extremes.min) && newMax < mathMax(extremes.dataMax, extremes.max)) {
  14756. axis.setExtremes(newMin, newMax, false, false, { trigger: 'pan' });
  14757. doRedraw = true;
  14758. }
  14759. chart[isX ? 'mouseDownX' : 'mouseDownY'] = mousePos; // set new reference for next run
  14760. });
  14761. if (doRedraw) {
  14762. chart.redraw(false);
  14763. }
  14764. css(chart.container, { cursor: 'move' });
  14765. }
  14766. });
  14767. /*
  14768. * Extend the Point object with interaction
  14769. */
  14770. extend(Point.prototype, {
  14771. /**
  14772. * Toggle the selection status of a point
  14773. * @param {Boolean} selected Whether to select or unselect the point.
  14774. * @param {Boolean} accumulate Whether to add to the previous selection. By default,
  14775. * this happens if the control key (Cmd on Mac) was pressed during clicking.
  14776. */
  14777. select: function (selected, accumulate) {
  14778. var point = this,
  14779. series = point.series,
  14780. chart = series.chart;
  14781. selected = pick(selected, !point.selected);
  14782. // fire the event with the defalut handler
  14783. point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () {
  14784. point.selected = point.options.selected = selected;
  14785. series.options.data[inArray(point, series.data)] = point.options;
  14786. point.setState(selected && SELECT_STATE);
  14787. // unselect all other points unless Ctrl or Cmd + click
  14788. if (!accumulate) {
  14789. each(chart.getSelectedPoints(), function (loopPoint) {
  14790. if (loopPoint.selected && loopPoint !== point) {
  14791. loopPoint.selected = loopPoint.options.selected = false;
  14792. series.options.data[inArray(loopPoint, series.data)] = loopPoint.options;
  14793. loopPoint.setState(NORMAL_STATE);
  14794. loopPoint.firePointEvent('unselect');
  14795. }
  14796. });
  14797. }
  14798. });
  14799. },
  14800. /**
  14801. * Runs on mouse over the point
  14802. */
  14803. onMouseOver: function (e) {
  14804. var point = this,
  14805. series = point.series,
  14806. chart = series.chart,
  14807. tooltip = chart.tooltip,
  14808. hoverPoint = chart.hoverPoint;
  14809. // set normal state to previous series
  14810. if (hoverPoint && hoverPoint !== point) {
  14811. hoverPoint.onMouseOut();
  14812. }
  14813. // trigger the event
  14814. point.firePointEvent('mouseOver');
  14815. // update the tooltip
  14816. if (tooltip && (!tooltip.shared || series.noSharedTooltip)) {
  14817. tooltip.refresh(point, e);
  14818. }
  14819. // hover this
  14820. point.setState(HOVER_STATE);
  14821. chart.hoverPoint = point;
  14822. },
  14823. /**
  14824. * Runs on mouse out from the point
  14825. */
  14826. onMouseOut: function () {
  14827. var chart = this.series.chart,
  14828. hoverPoints = chart.hoverPoints;
  14829. if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887
  14830. this.firePointEvent('mouseOut');
  14831. this.setState();
  14832. chart.hoverPoint = null;
  14833. }
  14834. },
  14835. /**
  14836. * Import events from the series' and point's options. Only do it on
  14837. * demand, to save processing time on hovering.
  14838. */
  14839. importEvents: function () {
  14840. if (!this.hasImportedEvents) {
  14841. var point = this,
  14842. options = merge(point.series.options.point, point.options),
  14843. events = options.events,
  14844. eventType;
  14845. point.events = events;
  14846. for (eventType in events) {
  14847. addEvent(point, eventType, events[eventType]);
  14848. }
  14849. this.hasImportedEvents = true;
  14850. }
  14851. },
  14852. /**
  14853. * Set the point's state
  14854. * @param {String} state
  14855. */
  14856. setState: function (state, move) {
  14857. var point = this,
  14858. plotX = point.plotX,
  14859. plotY = point.plotY,
  14860. series = point.series,
  14861. stateOptions = series.options.states,
  14862. markerOptions = defaultPlotOptions[series.type].marker && series.options.marker,
  14863. normalDisabled = markerOptions && !markerOptions.enabled,
  14864. markerStateOptions = markerOptions && markerOptions.states[state],
  14865. stateDisabled = markerStateOptions && markerStateOptions.enabled === false,
  14866. stateMarkerGraphic = series.stateMarkerGraphic,
  14867. pointMarker = point.marker || {},
  14868. chart = series.chart,
  14869. radius,
  14870. halo = series.halo,
  14871. haloOptions,
  14872. newSymbol,
  14873. pointAttr;
  14874. state = state || NORMAL_STATE; // empty string
  14875. pointAttr = point.pointAttr[state] || series.pointAttr[state];
  14876. if (
  14877. // already has this state
  14878. (state === point.state && !move) ||
  14879. // selected points don't respond to hover
  14880. (point.selected && state !== SELECT_STATE) ||
  14881. // series' state options is disabled
  14882. (stateOptions[state] && stateOptions[state].enabled === false) ||
  14883. // general point marker's state options is disabled
  14884. (state && (stateDisabled || (normalDisabled && markerStateOptions.enabled === false))) ||
  14885. // individual point marker's state options is disabled
  14886. (state && pointMarker.states && pointMarker.states[state] && pointMarker.states[state].enabled === false) // #1610
  14887. ) {
  14888. return;
  14889. }
  14890. // apply hover styles to the existing point
  14891. if (point.graphic) {
  14892. radius = markerOptions && point.graphic.symbolName && pointAttr.r;
  14893. point.graphic.attr(merge(
  14894. pointAttr,
  14895. radius ? { // new symbol attributes (#507, #612)
  14896. x: plotX - radius,
  14897. y: plotY - radius,
  14898. width: 2 * radius,
  14899. height: 2 * radius
  14900. } : {}
  14901. ));
  14902. // Zooming in from a range with no markers to a range with markers
  14903. if (stateMarkerGraphic) {
  14904. stateMarkerGraphic.hide();
  14905. }
  14906. } else {
  14907. // if a graphic is not applied to each point in the normal state, create a shared
  14908. // graphic for the hover state
  14909. if (state && markerStateOptions) {
  14910. radius = markerStateOptions.radius;
  14911. newSymbol = pointMarker.symbol || series.symbol;
  14912. // If the point has another symbol than the previous one, throw away the
  14913. // state marker graphic and force a new one (#1459)
  14914. if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) {
  14915. stateMarkerGraphic = stateMarkerGraphic.destroy();
  14916. }
  14917. // Add a new state marker graphic
  14918. if (!stateMarkerGraphic) {
  14919. if (newSymbol) {
  14920. series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol(
  14921. newSymbol,
  14922. plotX - radius,
  14923. plotY - radius,
  14924. 2 * radius,
  14925. 2 * radius
  14926. )
  14927. .attr(pointAttr)
  14928. .add(series.markerGroup);
  14929. stateMarkerGraphic.currentSymbol = newSymbol;
  14930. }
  14931. // Move the existing graphic
  14932. } else {
  14933. stateMarkerGraphic[move ? 'animate' : 'attr']({ // #1054
  14934. x: plotX - radius,
  14935. y: plotY - radius
  14936. });
  14937. }
  14938. }
  14939. if (stateMarkerGraphic) {
  14940. stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY, chart.inverted) ? 'show' : 'hide'](); // #2450
  14941. }
  14942. }
  14943. // Show me your halo
  14944. haloOptions = stateOptions[state] && stateOptions[state].halo;
  14945. if (haloOptions && haloOptions.size) {
  14946. if (!halo) {
  14947. series.halo = halo = chart.renderer.path()
  14948. .add(series.seriesGroup);
  14949. }
  14950. halo.attr(extend({
  14951. fill: Color(point.color || series.color).setOpacity(haloOptions.opacity).get()
  14952. }, haloOptions.attributes))[move ? 'animate' : 'attr']({
  14953. d: point.haloPath(haloOptions.size)
  14954. });
  14955. } else if (halo) {
  14956. halo.attr({ d: [] });
  14957. }
  14958. point.state = state;
  14959. },
  14960. haloPath: function (size) {
  14961. var series = this.series,
  14962. chart = series.chart,
  14963. plotBox = series.getPlotBox(),
  14964. inverted = chart.inverted;
  14965. return chart.renderer.symbols.circle(
  14966. plotBox.translateX + (inverted ? series.yAxis.len - this.plotY : this.plotX) - size,
  14967. plotBox.translateY + (inverted ? series.xAxis.len - this.plotX : this.plotY) - size,
  14968. size * 2,
  14969. size * 2
  14970. );
  14971. }
  14972. });
  14973. /*
  14974. * Extend the Series object with interaction
  14975. */
  14976. extend(Series.prototype, {
  14977. /**
  14978. * Series mouse over handler
  14979. */
  14980. onMouseOver: function () {
  14981. var series = this,
  14982. chart = series.chart,
  14983. hoverSeries = chart.hoverSeries;
  14984. // set normal state to previous series
  14985. if (hoverSeries && hoverSeries !== series) {
  14986. hoverSeries.onMouseOut();
  14987. }
  14988. // trigger the event, but to save processing time,
  14989. // only if defined
  14990. if (series.options.events.mouseOver) {
  14991. fireEvent(series, 'mouseOver');
  14992. }
  14993. // hover this
  14994. series.setState(HOVER_STATE);
  14995. chart.hoverSeries = series;
  14996. },
  14997. /**
  14998. * Series mouse out handler
  14999. */
  15000. onMouseOut: function () {
  15001. // trigger the event only if listeners exist
  15002. var series = this,
  15003. options = series.options,
  15004. chart = series.chart,
  15005. tooltip = chart.tooltip,
  15006. hoverPoint = chart.hoverPoint;
  15007. // trigger mouse out on the point, which must be in this series
  15008. if (hoverPoint) {
  15009. hoverPoint.onMouseOut();
  15010. }
  15011. // fire the mouse out event
  15012. if (series && options.events.mouseOut) {
  15013. fireEvent(series, 'mouseOut');
  15014. }
  15015. // hide the tooltip
  15016. if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) {
  15017. tooltip.hide();
  15018. }
  15019. // set normal state
  15020. series.setState();
  15021. chart.hoverSeries = null;
  15022. },
  15023. /**
  15024. * Set the state of the graph
  15025. */
  15026. setState: function (state) {
  15027. var series = this,
  15028. options = series.options,
  15029. graph = series.graph,
  15030. graphNeg = series.graphNeg,
  15031. stateOptions = options.states,
  15032. lineWidth = options.lineWidth,
  15033. attribs;
  15034. state = state || NORMAL_STATE;
  15035. if (series.state !== state) {
  15036. series.state = state;
  15037. if (stateOptions[state] && stateOptions[state].enabled === false) {
  15038. return;
  15039. }
  15040. if (state) {
  15041. lineWidth = stateOptions[state].lineWidth || lineWidth + 1;
  15042. }
  15043. if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML
  15044. attribs = {
  15045. 'stroke-width': lineWidth
  15046. };
  15047. // use attr because animate will cause any other animation on the graph to stop
  15048. graph.attr(attribs);
  15049. if (graphNeg) {
  15050. graphNeg.attr(attribs);
  15051. }
  15052. }
  15053. }
  15054. },
  15055. /**
  15056. * Set the visibility of the graph
  15057. *
  15058. * @param vis {Boolean} True to show the series, false to hide. If UNDEFINED,
  15059. * the visibility is toggled.
  15060. */
  15061. setVisible: function (vis, redraw) {
  15062. var series = this,
  15063. chart = series.chart,
  15064. legendItem = series.legendItem,
  15065. showOrHide,
  15066. ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries,
  15067. oldVisibility = series.visible;
  15068. // if called without an argument, toggle visibility
  15069. series.visible = vis = series.userOptions.visible = vis === UNDEFINED ? !oldVisibility : vis;
  15070. showOrHide = vis ? 'show' : 'hide';
  15071. // show or hide elements
  15072. each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) {
  15073. if (series[key]) {
  15074. series[key][showOrHide]();
  15075. }
  15076. });
  15077. // hide tooltip (#1361)
  15078. if (chart.hoverSeries === series) {
  15079. series.onMouseOut();
  15080. }
  15081. if (legendItem) {
  15082. chart.legend.colorizeItem(series, vis);
  15083. }
  15084. // rescale or adapt to resized chart
  15085. series.isDirty = true;
  15086. // in a stack, all other series are affected
  15087. if (series.options.stacking) {
  15088. each(chart.series, function (otherSeries) {
  15089. if (otherSeries.options.stacking && otherSeries.visible) {
  15090. otherSeries.isDirty = true;
  15091. }
  15092. });
  15093. }
  15094. // show or hide linked series
  15095. each(series.linkedSeries, function (otherSeries) {
  15096. otherSeries.setVisible(vis, false);
  15097. });
  15098. if (ignoreHiddenSeries) {
  15099. chart.isDirtyBox = true;
  15100. }
  15101. if (redraw !== false) {
  15102. chart.redraw();
  15103. }
  15104. fireEvent(series, showOrHide);
  15105. },
  15106. /**
  15107. * Memorize tooltip texts and positions
  15108. */
  15109. setTooltipPoints: function (renew) {
  15110. var series = this,
  15111. points = [],
  15112. pointsLength,
  15113. low,
  15114. high,
  15115. xAxis = series.xAxis,
  15116. xExtremes = xAxis && xAxis.getExtremes(),
  15117. axisLength = xAxis ? (xAxis.tooltipLen || xAxis.len) : series.chart.plotSizeX, // tooltipLen and tooltipPosName used in polar
  15118. point,
  15119. pointX,
  15120. nextPoint,
  15121. i,
  15122. tooltipPoints = []; // a lookup array for each pixel in the x dimension
  15123. // don't waste resources if tracker is disabled
  15124. if (series.options.enableMouseTracking === false || series.singularTooltips) {
  15125. return;
  15126. }
  15127. // renew
  15128. if (renew) {
  15129. series.tooltipPoints = null;
  15130. }
  15131. // concat segments to overcome null values
  15132. each(series.segments || series.points, function (segment) {
  15133. points = points.concat(segment);
  15134. });
  15135. // Reverse the points in case the X axis is reversed
  15136. if (xAxis && xAxis.reversed) {
  15137. points = points.reverse();
  15138. }
  15139. // Polar needs additional shaping
  15140. if (series.orderTooltipPoints) {
  15141. series.orderTooltipPoints(points);
  15142. }
  15143. // Assign each pixel position to the nearest point
  15144. pointsLength = points.length;
  15145. for (i = 0; i < pointsLength; i++) {
  15146. point = points[i];
  15147. pointX = point.x;
  15148. if (pointX >= xExtremes.min && pointX <= xExtremes.max) { // #1149
  15149. nextPoint = points[i + 1];
  15150. // Set this range's low to the last range's high plus one
  15151. low = high === UNDEFINED ? 0 : high + 1;
  15152. // Now find the new high
  15153. high = points[i + 1] ?
  15154. mathMin(mathMax(0, mathFloor( // #2070
  15155. (point.clientX + (nextPoint ? (nextPoint.wrappedClientX || nextPoint.clientX) : axisLength)) / 2
  15156. )), axisLength) :
  15157. axisLength;
  15158. while (low >= 0 && low <= high) {
  15159. tooltipPoints[low++] = point;
  15160. }
  15161. }
  15162. }
  15163. series.tooltipPoints = tooltipPoints;
  15164. },
  15165. /**
  15166. * Show the graph
  15167. */
  15168. show: function () {
  15169. this.setVisible(true);
  15170. },
  15171. /**
  15172. * Hide the graph
  15173. */
  15174. hide: function () {
  15175. this.setVisible(false);
  15176. },
  15177. /**
  15178. * Set the selected state of the graph
  15179. *
  15180. * @param selected {Boolean} True to select the series, false to unselect. If
  15181. * UNDEFINED, the selection state is toggled.
  15182. */
  15183. select: function (selected) {
  15184. var series = this;
  15185. // if called without an argument, toggle
  15186. series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected;
  15187. if (series.checkbox) {
  15188. series.checkbox.checked = selected;
  15189. }
  15190. fireEvent(series, selected ? 'select' : 'unselect');
  15191. },
  15192. drawTracker: TrackerMixin.drawTrackerGraph
  15193. });
  15194. // global variables
  15195. extend(Highcharts, {
  15196. // Constructors
  15197. Axis: Axis,
  15198. Chart: Chart,
  15199. Color: Color,
  15200. Point: Point,
  15201. Tick: Tick,
  15202. Renderer: Renderer,
  15203. Series: Series,
  15204. SVGElement: SVGElement,
  15205. SVGRenderer: SVGRenderer,
  15206. // Various
  15207. arrayMin: arrayMin,
  15208. arrayMax: arrayMax,
  15209. charts: charts,
  15210. dateFormat: dateFormat,
  15211. format: format,
  15212. pathAnim: pathAnim,
  15213. getOptions: getOptions,
  15214. hasBidiBug: hasBidiBug,
  15215. isTouchDevice: isTouchDevice,
  15216. numberFormat: numberFormat,
  15217. seriesTypes: seriesTypes,
  15218. setOptions: setOptions,
  15219. addEvent: addEvent,
  15220. removeEvent: removeEvent,
  15221. createElement: createElement,
  15222. discardElement: discardElement,
  15223. css: css,
  15224. each: each,
  15225. extend: extend,
  15226. map: map,
  15227. merge: merge,
  15228. pick: pick,
  15229. splat: splat,
  15230. extendClass: extendClass,
  15231. pInt: pInt,
  15232. wrap: wrap,
  15233. svg: hasSVG,
  15234. canvas: useCanVG,
  15235. vml: !hasSVG && !useCanVG,
  15236. product: PRODUCT,
  15237. version: VERSION
  15238. });
  15239. }());