highcharts.src.js 416 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274
  1. // ==ClosureCompiler==
  2. // @compilation_level SIMPLE_OPTIMIZATIONS
  3. /**
  4. * @license Highcharts JS v3.0.1 (2013-04-09)
  5. *
  6. * (c) 2009-2013 Torstein Hønsi
  7. *
  8. * License: www.highcharts.com/license
  9. */
  10. // JSLint options:
  11. /*global Highcharts, document, window, navigator, setInterval, clearInterval, clearTimeout, setTimeout, location, jQuery, $, console */
  12. (function () {
  13. // encapsulated variables
  14. var UNDEFINED,
  15. doc = document,
  16. win = window,
  17. math = Math,
  18. mathRound = math.round,
  19. mathFloor = math.floor,
  20. mathCeil = math.ceil,
  21. mathMax = math.max,
  22. mathMin = math.min,
  23. mathAbs = math.abs,
  24. mathCos = math.cos,
  25. mathSin = math.sin,
  26. mathPI = math.PI,
  27. deg2rad = mathPI * 2 / 360,
  28. // some variables
  29. userAgent = navigator.userAgent,
  30. isOpera = win.opera,
  31. isIE = /msie/i.test(userAgent) && !isOpera,
  32. docMode8 = doc.documentMode === 8,
  33. isWebKit = /AppleWebKit/.test(userAgent),
  34. isFirefox = /Firefox/.test(userAgent),
  35. isTouchDevice = /(Mobile|Android|Windows Phone)/.test(userAgent),
  36. SVG_NS = 'http://www.w3.org/2000/svg',
  37. hasSVG = !!doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect,
  38. hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4, // issue #38
  39. useCanVG = !hasSVG && !isIE && !!doc.createElement('canvas').getContext,
  40. Renderer,
  41. hasTouch = doc.documentElement.ontouchstart !== UNDEFINED,
  42. symbolSizes = {},
  43. idCounter = 0,
  44. garbageBin,
  45. defaultOptions,
  46. dateFormat, // function
  47. globalAnimation,
  48. pathAnim,
  49. timeUnits,
  50. noop = function () {},
  51. charts = [],
  52. PRODUCT = 'Highcharts',
  53. VERSION = '3.0.1',
  54. // some constants for frequently used strings
  55. DIV = 'div',
  56. ABSOLUTE = 'absolute',
  57. RELATIVE = 'relative',
  58. HIDDEN = 'hidden',
  59. PREFIX = 'highcharts-',
  60. VISIBLE = 'visible',
  61. PX = 'px',
  62. NONE = 'none',
  63. M = 'M',
  64. L = 'L',
  65. /*
  66. * Empirical lowest possible opacities for TRACKER_FILL
  67. * IE6: 0.002
  68. * IE7: 0.002
  69. * IE8: 0.002
  70. * IE9: 0.00000000001 (unlimited)
  71. * IE10: 0.0001 (exporting only)
  72. * FF: 0.00000000001 (unlimited)
  73. * Chrome: 0.000001
  74. * Safari: 0.000001
  75. * Opera: 0.00000000001 (unlimited)
  76. */
  77. TRACKER_FILL = 'rgba(192,192,192,' + (hasSVG ? 0.0001 : 0.002) + ')', // invisible but clickable
  78. //TRACKER_FILL = 'rgba(192,192,192,0.5)',
  79. NORMAL_STATE = '',
  80. HOVER_STATE = 'hover',
  81. SELECT_STATE = 'select',
  82. MILLISECOND = 'millisecond',
  83. SECOND = 'second',
  84. MINUTE = 'minute',
  85. HOUR = 'hour',
  86. DAY = 'day',
  87. WEEK = 'week',
  88. MONTH = 'month',
  89. YEAR = 'year',
  90. // constants for attributes
  91. LINEAR_GRADIENT = 'linearGradient',
  92. STOPS = 'stops',
  93. STROKE_WIDTH = 'stroke-width',
  94. // time methods, changed based on whether or not UTC is used
  95. makeTime,
  96. getMinutes,
  97. getHours,
  98. getDay,
  99. getDate,
  100. getMonth,
  101. getFullYear,
  102. setMinutes,
  103. setHours,
  104. setDate,
  105. setMonth,
  106. setFullYear,
  107. // lookup over the types and the associated classes
  108. seriesTypes = {};
  109. // The Highcharts namespace
  110. win.Highcharts = win.Highcharts ? error(16, true) : {};
  111. /**
  112. * Extend an object with the members of another
  113. * @param {Object} a The object to be extended
  114. * @param {Object} b The object to add to the first one
  115. */
  116. function extend(a, b) {
  117. var n;
  118. if (!a) {
  119. a = {};
  120. }
  121. for (n in b) {
  122. a[n] = b[n];
  123. }
  124. return a;
  125. }
  126. /**
  127. * Deep merge two or more objects and return a third object.
  128. * Previously this function redirected to jQuery.extend(true), but this had two limitations.
  129. * First, it deep merged arrays, which lead to workarounds in Highcharts. Second,
  130. * it copied properties from extended prototypes.
  131. */
  132. function merge() {
  133. var i,
  134. len = arguments.length,
  135. ret = {},
  136. doCopy = function (copy, original) {
  137. var value, key;
  138. for (key in original) {
  139. if (original.hasOwnProperty(key)) {
  140. value = original[key];
  141. // An object is replacing a primitive
  142. if (typeof copy !== 'object') {
  143. copy = {};
  144. }
  145. // Copy the contents of objects, but not arrays or DOM nodes
  146. if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]'
  147. && typeof value.nodeType !== 'number') {
  148. copy[key] = doCopy(copy[key] || {}, value);
  149. // Primitives and arrays are copied over directly
  150. } else {
  151. copy[key] = original[key];
  152. }
  153. }
  154. }
  155. return copy;
  156. };
  157. // For each argument, extend the return
  158. for (i = 0; i < len; i++) {
  159. ret = doCopy(ret, arguments[i]);
  160. }
  161. return ret;
  162. }
  163. /**
  164. * Take an array and turn into a hash with even number arguments as keys and odd numbers as
  165. * values. Allows creating constants for commonly used style properties, attributes etc.
  166. * Avoid it in performance critical situations like looping
  167. */
  168. function hash() {
  169. var i = 0,
  170. args = arguments,
  171. length = args.length,
  172. obj = {};
  173. for (; i < length; i++) {
  174. obj[args[i++]] = args[i];
  175. }
  176. return obj;
  177. }
  178. /**
  179. * Shortcut for parseInt
  180. * @param {Object} s
  181. * @param {Number} mag Magnitude
  182. */
  183. function pInt(s, mag) {
  184. return parseInt(s, mag || 10);
  185. }
  186. /**
  187. * Check for string
  188. * @param {Object} s
  189. */
  190. function isString(s) {
  191. return typeof s === 'string';
  192. }
  193. /**
  194. * Check for object
  195. * @param {Object} obj
  196. */
  197. function isObject(obj) {
  198. return typeof obj === 'object';
  199. }
  200. /**
  201. * Check for array
  202. * @param {Object} obj
  203. */
  204. function isArray(obj) {
  205. return Object.prototype.toString.call(obj) === '[object Array]';
  206. }
  207. /**
  208. * Check for number
  209. * @param {Object} n
  210. */
  211. function isNumber(n) {
  212. return typeof n === 'number';
  213. }
  214. function log2lin(num) {
  215. return math.log(num) / math.LN10;
  216. }
  217. function lin2log(num) {
  218. return math.pow(10, num);
  219. }
  220. /**
  221. * Remove last occurence of an item from an array
  222. * @param {Array} arr
  223. * @param {Mixed} item
  224. */
  225. function erase(arr, item) {
  226. var i = arr.length;
  227. while (i--) {
  228. if (arr[i] === item) {
  229. arr.splice(i, 1);
  230. break;
  231. }
  232. }
  233. //return arr;
  234. }
  235. /**
  236. * Returns true if the object is not null or undefined. Like MooTools' $.defined.
  237. * @param {Object} obj
  238. */
  239. function defined(obj) {
  240. return obj !== UNDEFINED && obj !== null;
  241. }
  242. /**
  243. * Set or get an attribute or an object of attributes. Can't use jQuery attr because
  244. * it attempts to set expando properties on the SVG element, which is not allowed.
  245. *
  246. * @param {Object} elem The DOM element to receive the attribute(s)
  247. * @param {String|Object} prop The property or an abject of key-value pairs
  248. * @param {String} value The value if a single property is set
  249. */
  250. function attr(elem, prop, value) {
  251. var key,
  252. setAttribute = 'setAttribute',
  253. ret;
  254. // if the prop is a string
  255. if (isString(prop)) {
  256. // set the value
  257. if (defined(value)) {
  258. elem[setAttribute](prop, value);
  259. // get the value
  260. } else if (elem && elem.getAttribute) { // elem not defined when printing pie demo...
  261. ret = elem.getAttribute(prop);
  262. }
  263. // else if prop is defined, it is a hash of key/value pairs
  264. } else if (defined(prop) && isObject(prop)) {
  265. for (key in prop) {
  266. elem[setAttribute](key, prop[key]);
  267. }
  268. }
  269. return ret;
  270. }
  271. /**
  272. * Check if an element is an array, and if not, make it into an array. Like
  273. * MooTools' $.splat.
  274. */
  275. function splat(obj) {
  276. return isArray(obj) ? obj : [obj];
  277. }
  278. /**
  279. * Return the first value that is defined. Like MooTools' $.pick.
  280. */
  281. function pick() {
  282. var args = arguments,
  283. i,
  284. arg,
  285. length = args.length;
  286. for (i = 0; i < length; i++) {
  287. arg = args[i];
  288. if (typeof arg !== 'undefined' && arg !== null) {
  289. return arg;
  290. }
  291. }
  292. }
  293. /**
  294. * Set CSS on a given element
  295. * @param {Object} el
  296. * @param {Object} styles Style object with camel case property names
  297. */
  298. function css(el, styles) {
  299. if (isIE) {
  300. if (styles && styles.opacity !== UNDEFINED) {
  301. styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')';
  302. }
  303. }
  304. extend(el.style, styles);
  305. }
  306. /**
  307. * Utility function to create element with attributes and styles
  308. * @param {Object} tag
  309. * @param {Object} attribs
  310. * @param {Object} styles
  311. * @param {Object} parent
  312. * @param {Object} nopad
  313. */
  314. function createElement(tag, attribs, styles, parent, nopad) {
  315. var el = doc.createElement(tag);
  316. if (attribs) {
  317. extend(el, attribs);
  318. }
  319. if (nopad) {
  320. css(el, {padding: 0, border: NONE, margin: 0});
  321. }
  322. if (styles) {
  323. css(el, styles);
  324. }
  325. if (parent) {
  326. parent.appendChild(el);
  327. }
  328. return el;
  329. }
  330. /**
  331. * Extend a prototyped class by new members
  332. * @param {Object} parent
  333. * @param {Object} members
  334. */
  335. function extendClass(parent, members) {
  336. var object = function () {};
  337. object.prototype = new parent();
  338. extend(object.prototype, members);
  339. return object;
  340. }
  341. /**
  342. * Format a number and return a string based on input settings
  343. * @param {Number} number The input number to format
  344. * @param {Number} decimals The amount of decimals
  345. * @param {String} decPoint The decimal point, defaults to the one given in the lang options
  346. * @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options
  347. */
  348. function numberFormat(number, decimals, decPoint, thousandsSep) {
  349. var lang = defaultOptions.lang,
  350. // http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/
  351. n = number,
  352. c = decimals === -1 ?
  353. ((n || 0).toString().split('.')[1] || '').length : // preserve decimals
  354. (isNaN(decimals = mathAbs(decimals)) ? 2 : decimals),
  355. d = decPoint === undefined ? lang.decimalPoint : decPoint,
  356. t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep,
  357. s = n < 0 ? "-" : "",
  358. i = String(pInt(n = mathAbs(+n || 0).toFixed(c))),
  359. j = i.length > 3 ? i.length % 3 : 0;
  360. return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) +
  361. (c ? d + mathAbs(n - i).toFixed(c).slice(2) : "");
  362. }
  363. /**
  364. * Pad a string to a given length by adding 0 to the beginning
  365. * @param {Number} number
  366. * @param {Number} length
  367. */
  368. function pad(number, length) {
  369. // Create an array of the remaining length +1 and join it with 0's
  370. return new Array((length || 2) + 1 - String(number).length).join(0) + number;
  371. }
  372. /**
  373. * Wrap a method with extended functionality, preserving the original function
  374. * @param {Object} obj The context object that the method belongs to
  375. * @param {String} method The name of the method to extend
  376. * @param {Function} func A wrapper function callback. This function is called with the same arguments
  377. * as the original function, except that the original function is unshifted and passed as the first
  378. * argument.
  379. */
  380. function wrap(obj, method, func) {
  381. var proceed = obj[method];
  382. obj[method] = function () {
  383. var args = Array.prototype.slice.call(arguments);
  384. args.unshift(proceed);
  385. return func.apply(this, args);
  386. };
  387. }
  388. /**
  389. * Based on http://www.php.net/manual/en/function.strftime.php
  390. * @param {String} format
  391. * @param {Number} timestamp
  392. * @param {Boolean} capitalize
  393. */
  394. dateFormat = function (format, timestamp, capitalize) {
  395. if (!defined(timestamp) || isNaN(timestamp)) {
  396. return 'Invalid date';
  397. }
  398. format = pick(format, '%Y-%m-%d %H:%M:%S');
  399. var date = new Date(timestamp),
  400. key, // used in for constuct below
  401. // get the basic time values
  402. hours = date[getHours](),
  403. day = date[getDay](),
  404. dayOfMonth = date[getDate](),
  405. month = date[getMonth](),
  406. fullYear = date[getFullYear](),
  407. lang = defaultOptions.lang,
  408. langWeekdays = lang.weekdays,
  409. // List all format keys. Custom formats can be added from the outside.
  410. replacements = extend({
  411. // Day
  412. 'a': langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon'
  413. 'A': langWeekdays[day], // Long weekday, like 'Monday'
  414. 'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31
  415. 'e': dayOfMonth, // Day of the month, 1 through 31
  416. // Week (none implemented)
  417. //'W': weekNumber(),
  418. // Month
  419. 'b': lang.shortMonths[month], // Short month, like 'Jan'
  420. 'B': lang.months[month], // Long month, like 'January'
  421. 'm': pad(month + 1), // Two digit month number, 01 through 12
  422. // Year
  423. 'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009
  424. 'Y': fullYear, // Four digits year, like 2009
  425. // Time
  426. 'H': pad(hours), // Two digits hours in 24h format, 00 through 23
  427. 'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11
  428. 'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12
  429. 'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59
  430. 'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM
  431. 'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM
  432. 'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59
  433. 'L': pad(mathRound(timestamp % 1000), 3) // Milliseconds (naming from Ruby)
  434. }, Highcharts.dateFormats);
  435. // do the replaces
  436. for (key in replacements) {
  437. while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster
  438. format = format.replace('%' + key, typeof replacements[key] === 'function' ? replacements[key](timestamp) : replacements[key]);
  439. }
  440. }
  441. // Optionally capitalize the string and return
  442. return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format;
  443. };
  444. /**
  445. * Format a single variable. Similar to sprintf, without the % prefix.
  446. */
  447. function formatSingle(format, val) {
  448. var floatRegex = /f$/,
  449. decRegex = /\.([0-9])/,
  450. lang = defaultOptions.lang,
  451. decimals;
  452. if (floatRegex.test(format)) { // float
  453. decimals = format.match(decRegex);
  454. decimals = decimals ? decimals[1] : -1;
  455. val = numberFormat(
  456. val,
  457. decimals,
  458. lang.decimalPoint,
  459. format.indexOf(',') > -1 ? lang.thousandsSep : ''
  460. );
  461. } else {
  462. val = dateFormat(format, val);
  463. }
  464. return val;
  465. }
  466. /**
  467. * Format a string according to a subset of the rules of Python's String.format method.
  468. */
  469. function format(str, ctx) {
  470. var splitter = '{',
  471. isInside = false,
  472. segment,
  473. valueAndFormat,
  474. path,
  475. i,
  476. len,
  477. ret = [],
  478. val,
  479. index;
  480. while ((index = str.indexOf(splitter)) !== -1) {
  481. segment = str.slice(0, index);
  482. if (isInside) { // we're on the closing bracket looking back
  483. valueAndFormat = segment.split(':');
  484. path = valueAndFormat.shift().split('.'); // get first and leave format
  485. len = path.length;
  486. val = ctx;
  487. // Assign deeper paths
  488. for (i = 0; i < len; i++) {
  489. val = val[path[i]];
  490. }
  491. // Format the replacement
  492. if (valueAndFormat.length) {
  493. val = formatSingle(valueAndFormat.join(':'), val);
  494. }
  495. // Push the result and advance the cursor
  496. ret.push(val);
  497. } else {
  498. ret.push(segment);
  499. }
  500. str = str.slice(index + 1); // the rest
  501. isInside = !isInside; // toggle
  502. splitter = isInside ? '}' : '{'; // now look for next matching bracket
  503. }
  504. ret.push(str);
  505. return ret.join('');
  506. }
  507. /**
  508. * Take an interval and normalize it to multiples of 1, 2, 2.5 and 5
  509. * @param {Number} interval
  510. * @param {Array} multiples
  511. * @param {Number} magnitude
  512. * @param {Object} options
  513. */
  514. function normalizeTickInterval(interval, multiples, magnitude, options) {
  515. var normalized, i;
  516. // round to a tenfold of 1, 2, 2.5 or 5
  517. magnitude = pick(magnitude, 1);
  518. normalized = interval / magnitude;
  519. // multiples for a linear scale
  520. if (!multiples) {
  521. multiples = [1, 2, 2.5, 5, 10];
  522. // the allowDecimals option
  523. if (options && options.allowDecimals === false) {
  524. if (magnitude === 1) {
  525. multiples = [1, 2, 5, 10];
  526. } else if (magnitude <= 0.1) {
  527. multiples = [1 / magnitude];
  528. }
  529. }
  530. }
  531. // normalize the interval to the nearest multiple
  532. for (i = 0; i < multiples.length; i++) {
  533. interval = multiples[i];
  534. if (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2) {
  535. break;
  536. }
  537. }
  538. // multiply back to the correct magnitude
  539. interval *= magnitude;
  540. return interval;
  541. }
  542. /**
  543. * Get a normalized tick interval for dates. Returns a configuration object with
  544. * unit range (interval), count and name. Used to prepare data for getTimeTicks.
  545. * Previously this logic was part of getTimeTicks, but as getTimeTicks now runs
  546. * of segments in stock charts, the normalizing logic was extracted in order to
  547. * prevent it for running over again for each segment having the same interval.
  548. * #662, #697.
  549. */
  550. function normalizeTimeTickInterval(tickInterval, unitsOption) {
  551. var units = unitsOption || [[
  552. MILLISECOND, // unit name
  553. [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples
  554. ], [
  555. SECOND,
  556. [1, 2, 5, 10, 15, 30]
  557. ], [
  558. MINUTE,
  559. [1, 2, 5, 10, 15, 30]
  560. ], [
  561. HOUR,
  562. [1, 2, 3, 4, 6, 8, 12]
  563. ], [
  564. DAY,
  565. [1, 2]
  566. ], [
  567. WEEK,
  568. [1, 2]
  569. ], [
  570. MONTH,
  571. [1, 2, 3, 4, 6]
  572. ], [
  573. YEAR,
  574. null
  575. ]],
  576. unit = units[units.length - 1], // default unit is years
  577. interval = timeUnits[unit[0]],
  578. multiples = unit[1],
  579. count,
  580. i;
  581. // loop through the units to find the one that best fits the tickInterval
  582. for (i = 0; i < units.length; i++) {
  583. unit = units[i];
  584. interval = timeUnits[unit[0]];
  585. multiples = unit[1];
  586. if (units[i + 1]) {
  587. // lessThan is in the middle between the highest multiple and the next unit.
  588. var lessThan = (interval * multiples[multiples.length - 1] +
  589. timeUnits[units[i + 1][0]]) / 2;
  590. // break and keep the current unit
  591. if (tickInterval <= lessThan) {
  592. break;
  593. }
  594. }
  595. }
  596. // prevent 2.5 years intervals, though 25, 250 etc. are allowed
  597. if (interval === timeUnits[YEAR] && tickInterval < 5 * interval) {
  598. multiples = [1, 2, 5];
  599. }
  600. // prevent 2.5 years intervals, though 25, 250 etc. are allowed
  601. if (interval === timeUnits[YEAR] && tickInterval < 5 * interval) {
  602. multiples = [1, 2, 5];
  603. }
  604. // get the count
  605. count = normalizeTickInterval(tickInterval / interval, multiples);
  606. return {
  607. unitRange: interval,
  608. count: count,
  609. unitName: unit[0]
  610. };
  611. }
  612. /**
  613. * Set the tick positions to a time unit that makes sense, for example
  614. * on the first of each month or on every Monday. Return an array
  615. * with the time positions. Used in datetime axes as well as for grouping
  616. * data on a datetime axis.
  617. *
  618. * @param {Object} normalizedInterval The interval in axis values (ms) and the count
  619. * @param {Number} min The minimum in axis values
  620. * @param {Number} max The maximum in axis values
  621. * @param {Number} startOfWeek
  622. */
  623. function getTimeTicks(normalizedInterval, min, max, startOfWeek) {
  624. var tickPositions = [],
  625. i,
  626. higherRanks = {},
  627. useUTC = defaultOptions.global.useUTC,
  628. minYear, // used in months and years as a basis for Date.UTC()
  629. minDate = new Date(min),
  630. interval = normalizedInterval.unitRange,
  631. count = normalizedInterval.count;
  632. if (defined(min)) { // #1300
  633. if (interval >= timeUnits[SECOND]) { // second
  634. minDate.setMilliseconds(0);
  635. minDate.setSeconds(interval >= timeUnits[MINUTE] ? 0 :
  636. count * mathFloor(minDate.getSeconds() / count));
  637. }
  638. if (interval >= timeUnits[MINUTE]) { // minute
  639. minDate[setMinutes](interval >= timeUnits[HOUR] ? 0 :
  640. count * mathFloor(minDate[getMinutes]() / count));
  641. }
  642. if (interval >= timeUnits[HOUR]) { // hour
  643. minDate[setHours](interval >= timeUnits[DAY] ? 0 :
  644. count * mathFloor(minDate[getHours]() / count));
  645. }
  646. if (interval >= timeUnits[DAY]) { // day
  647. minDate[setDate](interval >= timeUnits[MONTH] ? 1 :
  648. count * mathFloor(minDate[getDate]() / count));
  649. }
  650. if (interval >= timeUnits[MONTH]) { // month
  651. minDate[setMonth](interval >= timeUnits[YEAR] ? 0 :
  652. count * mathFloor(minDate[getMonth]() / count));
  653. minYear = minDate[getFullYear]();
  654. }
  655. if (interval >= timeUnits[YEAR]) { // year
  656. minYear -= minYear % count;
  657. minDate[setFullYear](minYear);
  658. }
  659. // week is a special case that runs outside the hierarchy
  660. if (interval === timeUnits[WEEK]) {
  661. // get start of current week, independent of count
  662. minDate[setDate](minDate[getDate]() - minDate[getDay]() +
  663. pick(startOfWeek, 1));
  664. }
  665. // get tick positions
  666. i = 1;
  667. minYear = minDate[getFullYear]();
  668. var time = minDate.getTime(),
  669. minMonth = minDate[getMonth](),
  670. minDateDate = minDate[getDate](),
  671. timezoneOffset = useUTC ?
  672. 0 :
  673. (24 * 3600 * 1000 + minDate.getTimezoneOffset() * 60 * 1000) % (24 * 3600 * 1000); // #950
  674. // iterate and add tick positions at appropriate values
  675. while (time < max) {
  676. tickPositions.push(time);
  677. // if the interval is years, use Date.UTC to increase years
  678. if (interval === timeUnits[YEAR]) {
  679. time = makeTime(minYear + i * count, 0);
  680. // if the interval is months, use Date.UTC to increase months
  681. } else if (interval === timeUnits[MONTH]) {
  682. time = makeTime(minYear, minMonth + i * count);
  683. // if we're using global time, the interval is not fixed as it jumps
  684. // one hour at the DST crossover
  685. } else if (!useUTC && (interval === timeUnits[DAY] || interval === timeUnits[WEEK])) {
  686. time = makeTime(minYear, minMonth, minDateDate +
  687. i * count * (interval === timeUnits[DAY] ? 1 : 7));
  688. // else, the interval is fixed and we use simple addition
  689. } else {
  690. // mark new days if the time is dividable by day
  691. if (interval <= timeUnits[HOUR] && time % timeUnits[DAY] === timezoneOffset) {
  692. higherRanks[time] = DAY;
  693. }
  694. time += interval * count;
  695. }
  696. i++;
  697. }
  698. // push the last time
  699. tickPositions.push(time);
  700. }
  701. // record information on the chosen unit - for dynamic label formatter
  702. tickPositions.info = extend(normalizedInterval, {
  703. higherRanks: higherRanks,
  704. totalRange: interval * count
  705. });
  706. return tickPositions;
  707. }
  708. /**
  709. * Helper class that contains variuos counters that are local to the chart.
  710. */
  711. function ChartCounters() {
  712. this.color = 0;
  713. this.symbol = 0;
  714. }
  715. ChartCounters.prototype = {
  716. /**
  717. * Wraps the color counter if it reaches the specified length.
  718. */
  719. wrapColor: function (length) {
  720. if (this.color >= length) {
  721. this.color = 0;
  722. }
  723. },
  724. /**
  725. * Wraps the symbol counter if it reaches the specified length.
  726. */
  727. wrapSymbol: function (length) {
  728. if (this.symbol >= length) {
  729. this.symbol = 0;
  730. }
  731. }
  732. };
  733. /**
  734. * Utility method that sorts an object array and keeping the order of equal items.
  735. * ECMA script standard does not specify the behaviour when items are equal.
  736. */
  737. function stableSort(arr, sortFunction) {
  738. var length = arr.length,
  739. sortValue,
  740. i;
  741. // Add index to each item
  742. for (i = 0; i < length; i++) {
  743. arr[i].ss_i = i; // stable sort index
  744. }
  745. arr.sort(function (a, b) {
  746. sortValue = sortFunction(a, b);
  747. return sortValue === 0 ? a.ss_i - b.ss_i : sortValue;
  748. });
  749. // Remove index from items
  750. for (i = 0; i < length; i++) {
  751. delete arr[i].ss_i; // stable sort index
  752. }
  753. }
  754. /**
  755. * Non-recursive method to find the lowest member of an array. Math.min raises a maximum
  756. * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
  757. * method is slightly slower, but safe.
  758. */
  759. function arrayMin(data) {
  760. var i = data.length,
  761. min = data[0];
  762. while (i--) {
  763. if (data[i] < min) {
  764. min = data[i];
  765. }
  766. }
  767. return min;
  768. }
  769. /**
  770. * Non-recursive method to find the lowest member of an array. Math.min raises a maximum
  771. * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
  772. * method is slightly slower, but safe.
  773. */
  774. function arrayMax(data) {
  775. var i = data.length,
  776. max = data[0];
  777. while (i--) {
  778. if (data[i] > max) {
  779. max = data[i];
  780. }
  781. }
  782. return max;
  783. }
  784. /**
  785. * Utility method that destroys any SVGElement or VMLElement that are properties on the given object.
  786. * It loops all properties and invokes destroy if there is a destroy method. The property is
  787. * then delete'ed.
  788. * @param {Object} The object to destroy properties on
  789. * @param {Object} Exception, do not destroy this property, only delete it.
  790. */
  791. function destroyObjectProperties(obj, except) {
  792. var n;
  793. for (n in obj) {
  794. // If the object is non-null and destroy is defined
  795. if (obj[n] && obj[n] !== except && obj[n].destroy) {
  796. // Invoke the destroy
  797. obj[n].destroy();
  798. }
  799. // Delete the property from the object.
  800. delete obj[n];
  801. }
  802. }
  803. /**
  804. * Discard an element by moving it to the bin and delete
  805. * @param {Object} The HTML node to discard
  806. */
  807. function discardElement(element) {
  808. // create a garbage bin element, not part of the DOM
  809. if (!garbageBin) {
  810. garbageBin = createElement(DIV);
  811. }
  812. // move the node and empty bin
  813. if (element) {
  814. garbageBin.appendChild(element);
  815. }
  816. garbageBin.innerHTML = '';
  817. }
  818. /**
  819. * Provide error messages for debugging, with links to online explanation
  820. */
  821. function error(code, stop) {
  822. var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code;
  823. if (stop) {
  824. throw msg;
  825. } else if (win.console) {
  826. console.log(msg);
  827. }
  828. }
  829. /**
  830. * Fix JS round off float errors
  831. * @param {Number} num
  832. */
  833. function correctFloat(num) {
  834. return parseFloat(
  835. num.toPrecision(14)
  836. );
  837. }
  838. /**
  839. * Set the global animation to either a given value, or fall back to the
  840. * given chart's animation option
  841. * @param {Object} animation
  842. * @param {Object} chart
  843. */
  844. function setAnimation(animation, chart) {
  845. globalAnimation = pick(animation, chart.animation);
  846. }
  847. /**
  848. * The time unit lookup
  849. */
  850. /*jslint white: true*/
  851. timeUnits = hash(
  852. MILLISECOND, 1,
  853. SECOND, 1000,
  854. MINUTE, 60000,
  855. HOUR, 3600000,
  856. DAY, 24 * 3600000,
  857. WEEK, 7 * 24 * 3600000,
  858. MONTH, 31 * 24 * 3600000,
  859. YEAR, 31556952000
  860. );
  861. /*jslint white: false*/
  862. /**
  863. * Path interpolation algorithm used across adapters
  864. */
  865. pathAnim = {
  866. /**
  867. * Prepare start and end values so that the path can be animated one to one
  868. */
  869. init: function (elem, fromD, toD) {
  870. fromD = fromD || '';
  871. var shift = elem.shift,
  872. bezier = fromD.indexOf('C') > -1,
  873. numParams = bezier ? 7 : 3,
  874. endLength,
  875. slice,
  876. i,
  877. start = fromD.split(' '),
  878. end = [].concat(toD), // copy
  879. startBaseLine,
  880. endBaseLine,
  881. sixify = function (arr) { // in splines make move points have six parameters like bezier curves
  882. i = arr.length;
  883. while (i--) {
  884. if (arr[i] === M) {
  885. arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]);
  886. }
  887. }
  888. };
  889. if (bezier) {
  890. sixify(start);
  891. sixify(end);
  892. }
  893. // pull out the base lines before padding
  894. if (elem.isArea) {
  895. startBaseLine = start.splice(start.length - 6, 6);
  896. endBaseLine = end.splice(end.length - 6, 6);
  897. }
  898. // if shifting points, prepend a dummy point to the end path
  899. if (shift <= end.length / numParams) {
  900. while (shift--) {
  901. end = [].concat(end).splice(0, numParams).concat(end);
  902. }
  903. }
  904. elem.shift = 0; // reset for following animations
  905. // copy and append last point until the length matches the end length
  906. if (start.length) {
  907. endLength = end.length;
  908. while (start.length < endLength) {
  909. //bezier && sixify(start);
  910. slice = [].concat(start).splice(start.length - numParams, numParams);
  911. if (bezier) { // disable first control point
  912. slice[numParams - 6] = slice[numParams - 2];
  913. slice[numParams - 5] = slice[numParams - 1];
  914. }
  915. start = start.concat(slice);
  916. }
  917. }
  918. if (startBaseLine) { // append the base lines for areas
  919. start = start.concat(startBaseLine);
  920. end = end.concat(endBaseLine);
  921. }
  922. return [start, end];
  923. },
  924. /**
  925. * Interpolate each value of the path and return the array
  926. */
  927. step: function (start, end, pos, complete) {
  928. var ret = [],
  929. i = start.length,
  930. startVal;
  931. if (pos === 1) { // land on the final path without adjustment points appended in the ends
  932. ret = complete;
  933. } else if (i === end.length && pos < 1) {
  934. while (i--) {
  935. startVal = parseFloat(start[i]);
  936. ret[i] =
  937. isNaN(startVal) ? // a letter instruction like M or L
  938. start[i] :
  939. pos * (parseFloat(end[i] - startVal)) + startVal;
  940. }
  941. } else { // if animation is finished or length not matching, land on right value
  942. ret = end;
  943. }
  944. return ret;
  945. }
  946. };
  947. (function ($) {
  948. /**
  949. * The default HighchartsAdapter for jQuery
  950. */
  951. win.HighchartsAdapter = win.HighchartsAdapter || ($ && {
  952. /**
  953. * Initialize the adapter by applying some extensions to jQuery
  954. */
  955. init: function (pathAnim) {
  956. // extend the animate function to allow SVG animations
  957. var Fx = $.fx,
  958. Step = Fx.step,
  959. dSetter,
  960. Tween = $.Tween,
  961. propHooks = Tween && Tween.propHooks;
  962. /*jslint unparam: true*//* allow unused param x in this function */
  963. $.extend($.easing, {
  964. easeOutQuad: function (x, t, b, c, d) {
  965. return -c * (t /= d) * (t - 2) + b;
  966. }
  967. });
  968. /*jslint unparam: false*/
  969. // extend some methods to check for elem.attr, which means it is a Highcharts SVG object
  970. $.each(['cur', '_default', 'width', 'height', 'opacity'], function (i, fn) {
  971. var obj = Step,
  972. base,
  973. elem;
  974. // Handle different parent objects
  975. if (fn === 'cur') {
  976. obj = Fx.prototype; // 'cur', the getter, relates to Fx.prototype
  977. } else if (fn === '_default' && Tween) { // jQuery 1.8 model
  978. obj = propHooks[fn];
  979. fn = 'set';
  980. }
  981. // Overwrite the method
  982. base = obj[fn];
  983. if (base) { // step.width and step.height don't exist in jQuery < 1.7
  984. // create the extended function replacement
  985. obj[fn] = function (fx) {
  986. // Fx.prototype.cur does not use fx argument
  987. fx = i ? fx : this;
  988. // shortcut
  989. elem = fx.elem;
  990. // Fx.prototype.cur returns the current value. The other ones are setters
  991. // and returning a value has no effect.
  992. return elem.attr ? // is SVG element wrapper
  993. elem.attr(fx.prop, fn === 'cur' ? UNDEFINED : fx.now) : // apply the SVG wrapper's method
  994. base.apply(this, arguments); // use jQuery's built-in method
  995. };
  996. }
  997. });
  998. // Define the setter function for d (path definitions)
  999. dSetter = function (fx) {
  1000. var elem = fx.elem,
  1001. ends;
  1002. // Normally start and end should be set in state == 0, but sometimes,
  1003. // for reasons unknown, this doesn't happen. Perhaps state == 0 is skipped
  1004. // in these cases
  1005. if (!fx.started) {
  1006. ends = pathAnim.init(elem, elem.d, elem.toD);
  1007. fx.start = ends[0];
  1008. fx.end = ends[1];
  1009. fx.started = true;
  1010. }
  1011. // interpolate each value of the path
  1012. elem.attr('d', pathAnim.step(fx.start, fx.end, fx.pos, elem.toD));
  1013. };
  1014. // jQuery 1.8 style
  1015. if (Tween) {
  1016. propHooks.d = {
  1017. set: dSetter
  1018. };
  1019. // pre 1.8
  1020. } else {
  1021. // animate paths
  1022. Step.d = dSetter;
  1023. }
  1024. /**
  1025. * Utility for iterating over an array. Parameters are reversed compared to jQuery.
  1026. * @param {Array} arr
  1027. * @param {Function} fn
  1028. */
  1029. this.each = Array.prototype.forEach ?
  1030. function (arr, fn) { // modern browsers
  1031. return Array.prototype.forEach.call(arr, fn);
  1032. } :
  1033. function (arr, fn) { // legacy
  1034. var i = 0,
  1035. len = arr.length;
  1036. for (; i < len; i++) {
  1037. if (fn.call(arr[i], arr[i], i, arr) === false) {
  1038. return i;
  1039. }
  1040. }
  1041. };
  1042. /**
  1043. * Register Highcharts as a plugin in the respective framework
  1044. */
  1045. $.fn.highcharts = function () {
  1046. var constr = 'Chart', // default constructor
  1047. args = arguments,
  1048. options,
  1049. ret,
  1050. chart;
  1051. if (isString(args[0])) {
  1052. constr = args[0];
  1053. args = Array.prototype.slice.call(args, 1);
  1054. }
  1055. options = args[0];
  1056. // Create the chart
  1057. if (options !== UNDEFINED) {
  1058. /*jslint unused:false*/
  1059. options.chart = options.chart || {};
  1060. options.chart.renderTo = this[0];
  1061. chart = new Highcharts[constr](options, args[1]);
  1062. ret = this;
  1063. /*jslint unused:true*/
  1064. }
  1065. // When called without parameters or with the return argument, get a predefined chart
  1066. if (options === UNDEFINED) {
  1067. ret = charts[attr(this[0], 'data-highcharts-chart')];
  1068. }
  1069. return ret;
  1070. };
  1071. },
  1072. /**
  1073. * Downloads a script and executes a callback when done.
  1074. * @param {String} scriptLocation
  1075. * @param {Function} callback
  1076. */
  1077. getScript: $.getScript,
  1078. /**
  1079. * Return the index of an item in an array, or -1 if not found
  1080. */
  1081. inArray: $.inArray,
  1082. /**
  1083. * A direct link to jQuery methods. MooTools and Prototype adapters must be implemented for each case of method.
  1084. * @param {Object} elem The HTML element
  1085. * @param {String} method Which method to run on the wrapped element
  1086. */
  1087. adapterRun: function (elem, method) {
  1088. return $(elem)[method]();
  1089. },
  1090. /**
  1091. * Filter an array
  1092. */
  1093. grep: $.grep,
  1094. /**
  1095. * Map an array
  1096. * @param {Array} arr
  1097. * @param {Function} fn
  1098. */
  1099. map: function (arr, fn) {
  1100. //return jQuery.map(arr, fn);
  1101. var results = [],
  1102. i = 0,
  1103. len = arr.length;
  1104. for (; i < len; i++) {
  1105. results[i] = fn.call(arr[i], arr[i], i, arr);
  1106. }
  1107. return results;
  1108. },
  1109. /**
  1110. * Get the position of an element relative to the top left of the page
  1111. */
  1112. offset: function (el) {
  1113. return $(el).offset();
  1114. },
  1115. /**
  1116. * Add an event listener
  1117. * @param {Object} el A HTML element or custom object
  1118. * @param {String} event The event type
  1119. * @param {Function} fn The event handler
  1120. */
  1121. addEvent: function (el, event, fn) {
  1122. $(el).bind(event, fn);
  1123. },
  1124. /**
  1125. * Remove event added with addEvent
  1126. * @param {Object} el The object
  1127. * @param {String} eventType The event type. Leave blank to remove all events.
  1128. * @param {Function} handler The function to remove
  1129. */
  1130. removeEvent: function (el, eventType, handler) {
  1131. // workaround for jQuery issue with unbinding custom events:
  1132. // http://forum.jQuery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jQuery-1-4-2
  1133. var func = doc.removeEventListener ? 'removeEventListener' : 'detachEvent';
  1134. if (doc[func] && el && !el[func]) {
  1135. el[func] = function () {};
  1136. }
  1137. $(el).unbind(eventType, handler);
  1138. },
  1139. /**
  1140. * Fire an event on a custom object
  1141. * @param {Object} el
  1142. * @param {String} type
  1143. * @param {Object} eventArguments
  1144. * @param {Function} defaultFunction
  1145. */
  1146. fireEvent: function (el, type, eventArguments, defaultFunction) {
  1147. var event = $.Event(type),
  1148. detachedType = 'detached' + type,
  1149. defaultPrevented;
  1150. // Remove warnings in Chrome when accessing layerX and layerY. Although Highcharts
  1151. // never uses these properties, Chrome includes them in the default click event and
  1152. // raises the warning when they are copied over in the extend statement below.
  1153. //
  1154. // To avoid problems in IE (see #1010) where we cannot delete the properties and avoid
  1155. // testing if they are there (warning in chrome) the only option is to test if running IE.
  1156. if (!isIE && eventArguments) {
  1157. delete eventArguments.layerX;
  1158. delete eventArguments.layerY;
  1159. }
  1160. extend(event, eventArguments);
  1161. // Prevent jQuery from triggering the object method that is named the
  1162. // same as the event. For example, if the event is 'select', jQuery
  1163. // attempts calling el.select and it goes into a loop.
  1164. if (el[type]) {
  1165. el[detachedType] = el[type];
  1166. el[type] = null;
  1167. }
  1168. // Wrap preventDefault and stopPropagation in try/catch blocks in
  1169. // order to prevent JS errors when cancelling events on non-DOM
  1170. // objects. #615.
  1171. /*jslint unparam: true*/
  1172. $.each(['preventDefault', 'stopPropagation'], function (i, fn) {
  1173. var base = event[fn];
  1174. event[fn] = function () {
  1175. try {
  1176. base.call(event);
  1177. } catch (e) {
  1178. if (fn === 'preventDefault') {
  1179. defaultPrevented = true;
  1180. }
  1181. }
  1182. };
  1183. });
  1184. /*jslint unparam: false*/
  1185. // trigger it
  1186. $(el).trigger(event);
  1187. // attach the method
  1188. if (el[detachedType]) {
  1189. el[type] = el[detachedType];
  1190. el[detachedType] = null;
  1191. }
  1192. if (defaultFunction && !event.isDefaultPrevented() && !defaultPrevented) {
  1193. defaultFunction(event);
  1194. }
  1195. },
  1196. /**
  1197. * Extension method needed for MooTools
  1198. */
  1199. washMouseEvent: function (e) {
  1200. var ret = e.originalEvent || e;
  1201. // computed by jQuery, needed by IE8
  1202. if (ret.pageX === UNDEFINED) { // #1236
  1203. ret.pageX = e.pageX;
  1204. ret.pageY = e.pageY;
  1205. }
  1206. return ret;
  1207. },
  1208. /**
  1209. * Animate a HTML element or SVG element wrapper
  1210. * @param {Object} el
  1211. * @param {Object} params
  1212. * @param {Object} options jQuery-like animation options: duration, easing, callback
  1213. */
  1214. animate: function (el, params, options) {
  1215. var $el = $(el);
  1216. if (params.d) {
  1217. el.toD = params.d; // keep the array form for paths, used in $.fx.step.d
  1218. params.d = 1; // because in jQuery, animating to an array has a different meaning
  1219. }
  1220. $el.stop();
  1221. if (params.opacity !== UNDEFINED && el.attr) {
  1222. params.opacity += 'px'; // force jQuery to use same logic as width and height
  1223. }
  1224. $el.animate(params, options);
  1225. },
  1226. /**
  1227. * Stop running animation
  1228. */
  1229. stop: function (el) {
  1230. $(el).stop();
  1231. }
  1232. });
  1233. }(win.jQuery));
  1234. // check for a custom HighchartsAdapter defined prior to this file
  1235. var globalAdapter = win.HighchartsAdapter,
  1236. adapter = globalAdapter || {};
  1237. // Initialize the adapter
  1238. if (globalAdapter) {
  1239. globalAdapter.init.call(globalAdapter, pathAnim);
  1240. }
  1241. // Utility functions. If the HighchartsAdapter is not defined, adapter is an empty object
  1242. // and all the utility functions will be null. In that case they are populated by the
  1243. // default adapters below.
  1244. var adapterRun = adapter.adapterRun,
  1245. getScript = adapter.getScript,
  1246. inArray = adapter.inArray,
  1247. each = adapter.each,
  1248. grep = adapter.grep,
  1249. offset = adapter.offset,
  1250. map = adapter.map,
  1251. addEvent = adapter.addEvent,
  1252. removeEvent = adapter.removeEvent,
  1253. fireEvent = adapter.fireEvent,
  1254. washMouseEvent = adapter.washMouseEvent,
  1255. animate = adapter.animate,
  1256. stop = adapter.stop;
  1257. /* ****************************************************************************
  1258. * Handle the options *
  1259. *****************************************************************************/
  1260. var
  1261. defaultLabelOptions = {
  1262. enabled: true,
  1263. // rotation: 0,
  1264. align: 'center',
  1265. x: 0,
  1266. y: 15,
  1267. /*formatter: function () {
  1268. return this.value;
  1269. },*/
  1270. style: {
  1271. color: '#666',
  1272. cursor: 'default',
  1273. fontSize: '11px',
  1274. lineHeight: '14px'
  1275. }
  1276. };
  1277. defaultOptions = {
  1278. colors: ['#2f7ed8', '#0d233a', '#8bbc21', '#910000', '#1aadce', '#492970',
  1279. '#f28f43', '#77a1e5', '#c42525', '#a6c96a'],
  1280. symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'],
  1281. lang: {
  1282. loading: 'Loading...',
  1283. months: ['January', 'February', 'March', 'April', 'May', 'June', 'July',
  1284. 'August', 'September', 'October', 'November', 'December'],
  1285. shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  1286. weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  1287. decimalPoint: '.',
  1288. numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels
  1289. resetZoom: 'Reset zoom',
  1290. resetZoomTitle: 'Reset zoom level 1:1',
  1291. thousandsSep: ','
  1292. },
  1293. global: {
  1294. useUTC: true,
  1295. canvasToolsURL: 'http://code.highcharts.com/3.0.1/modules/canvas-tools.js',
  1296. VMLRadialGradientURL: 'http://code.highcharts.com/3.0.1/gfx/vml-radial-gradient.png'
  1297. },
  1298. chart: {
  1299. //animation: true,
  1300. //alignTicks: false,
  1301. //reflow: true,
  1302. //className: null,
  1303. //events: { load, selection },
  1304. //margin: [null],
  1305. //marginTop: null,
  1306. //marginRight: null,
  1307. //marginBottom: null,
  1308. //marginLeft: null,
  1309. borderColor: '#4572A7',
  1310. //borderWidth: 0,
  1311. borderRadius: 5,
  1312. defaultSeriesType: 'line',
  1313. ignoreHiddenSeries: true,
  1314. //inverted: false,
  1315. //shadow: false,
  1316. spacingTop: 10,
  1317. spacingRight: 10,
  1318. spacingBottom: 15,
  1319. spacingLeft: 10,
  1320. style: {
  1321. fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font
  1322. fontSize: '12px'
  1323. },
  1324. backgroundColor: '#FFFFFF',
  1325. //plotBackgroundColor: null,
  1326. plotBorderColor: '#C0C0C0',
  1327. //plotBorderWidth: 0,
  1328. //plotShadow: false,
  1329. //zoomType: ''
  1330. resetZoomButton: {
  1331. theme: {
  1332. zIndex: 20
  1333. },
  1334. position: {
  1335. align: 'right',
  1336. x: -10,
  1337. //verticalAlign: 'top',
  1338. y: 10
  1339. }
  1340. // relativeTo: 'plot'
  1341. }
  1342. },
  1343. title: {
  1344. text: 'Chart title',
  1345. align: 'center',
  1346. // floating: false,
  1347. // margin: 15,
  1348. // x: 0,
  1349. // verticalAlign: 'top',
  1350. y: 15,
  1351. style: {
  1352. color: '#274b6d',//#3E576F',
  1353. fontSize: '16px'
  1354. }
  1355. },
  1356. subtitle: {
  1357. text: '',
  1358. align: 'center',
  1359. // floating: false
  1360. // x: 0,
  1361. // verticalAlign: 'top',
  1362. y: 30,
  1363. style: {
  1364. color: '#4d759e'
  1365. }
  1366. },
  1367. plotOptions: {
  1368. line: { // base series options
  1369. allowPointSelect: false,
  1370. showCheckbox: false,
  1371. animation: {
  1372. duration: 1000
  1373. },
  1374. //connectNulls: false,
  1375. //cursor: 'default',
  1376. //clip: true,
  1377. //dashStyle: null,
  1378. //enableMouseTracking: true,
  1379. events: {},
  1380. //legendIndex: 0,
  1381. lineWidth: 2,
  1382. //shadow: false,
  1383. // stacking: null,
  1384. marker: {
  1385. enabled: true,
  1386. //symbol: null,
  1387. lineWidth: 0,
  1388. radius: 4,
  1389. lineColor: '#FFFFFF',
  1390. //fillColor: null,
  1391. states: { // states for a single point
  1392. hover: {
  1393. enabled: true
  1394. //radius: base + 2
  1395. },
  1396. select: {
  1397. fillColor: '#FFFFFF',
  1398. lineColor: '#000000',
  1399. lineWidth: 2
  1400. }
  1401. }
  1402. },
  1403. point: {
  1404. events: {}
  1405. },
  1406. dataLabels: merge(defaultLabelOptions, {
  1407. enabled: false,
  1408. formatter: function () {
  1409. return this.y;
  1410. },
  1411. verticalAlign: 'bottom', // above singular point
  1412. y: 0
  1413. // backgroundColor: undefined,
  1414. // borderColor: undefined,
  1415. // borderRadius: undefined,
  1416. // borderWidth: undefined,
  1417. // padding: 3,
  1418. // shadow: false
  1419. }),
  1420. cropThreshold: 300, // draw points outside the plot area when the number of points is less than this
  1421. pointRange: 0,
  1422. //pointStart: 0,
  1423. //pointInterval: 1,
  1424. showInLegend: true,
  1425. states: { // states for the entire series
  1426. hover: {
  1427. //enabled: false,
  1428. //lineWidth: base + 1,
  1429. marker: {
  1430. // lineWidth: base + 1,
  1431. // radius: base + 1
  1432. }
  1433. },
  1434. select: {
  1435. marker: {}
  1436. }
  1437. },
  1438. stickyTracking: true
  1439. //tooltip: {
  1440. //pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b>'
  1441. //valueDecimals: null,
  1442. //xDateFormat: '%A, %b %e, %Y',
  1443. //valuePrefix: '',
  1444. //ySuffix: ''
  1445. //}
  1446. // turboThreshold: 1000
  1447. // zIndex: null
  1448. }
  1449. },
  1450. labels: {
  1451. //items: [],
  1452. style: {
  1453. //font: defaultFont,
  1454. position: ABSOLUTE,
  1455. color: '#3E576F'
  1456. }
  1457. },
  1458. legend: {
  1459. enabled: true,
  1460. align: 'center',
  1461. //floating: false,
  1462. layout: 'horizontal',
  1463. labelFormatter: function () {
  1464. return this.name;
  1465. },
  1466. borderWidth: 1,
  1467. borderColor: '#909090',
  1468. borderRadius: 5,
  1469. navigation: {
  1470. // animation: true,
  1471. activeColor: '#274b6d',
  1472. // arrowSize: 12
  1473. inactiveColor: '#CCC'
  1474. // style: {} // text styles
  1475. },
  1476. // margin: 10,
  1477. // reversed: false,
  1478. shadow: false,
  1479. // backgroundColor: null,
  1480. /*style: {
  1481. padding: '5px'
  1482. },*/
  1483. itemStyle: {
  1484. cursor: 'pointer',
  1485. color: '#274b6d',
  1486. fontSize: '12px'
  1487. },
  1488. itemHoverStyle: {
  1489. //cursor: 'pointer', removed as of #601
  1490. color: '#000'
  1491. },
  1492. itemHiddenStyle: {
  1493. color: '#CCC'
  1494. },
  1495. itemCheckboxStyle: {
  1496. position: ABSOLUTE,
  1497. width: '13px', // for IE precision
  1498. height: '13px'
  1499. },
  1500. // itemWidth: undefined,
  1501. symbolWidth: 16,
  1502. symbolPadding: 5,
  1503. verticalAlign: 'bottom',
  1504. // width: undefined,
  1505. x: 0,
  1506. y: 0,
  1507. title: {
  1508. //text: null,
  1509. style: {
  1510. fontWeight: 'bold'
  1511. }
  1512. }
  1513. },
  1514. loading: {
  1515. // hideDuration: 100,
  1516. labelStyle: {
  1517. fontWeight: 'bold',
  1518. position: RELATIVE,
  1519. top: '1em'
  1520. },
  1521. // showDuration: 0,
  1522. style: {
  1523. position: ABSOLUTE,
  1524. backgroundColor: 'white',
  1525. opacity: 0.5,
  1526. textAlign: 'center'
  1527. }
  1528. },
  1529. tooltip: {
  1530. enabled: true,
  1531. animation: hasSVG,
  1532. //crosshairs: null,
  1533. backgroundColor: 'rgba(255, 255, 255, .85)',
  1534. borderWidth: 1,
  1535. borderRadius: 3,
  1536. dateTimeLabelFormats: {
  1537. millisecond: '%A, %b %e, %H:%M:%S.%L',
  1538. second: '%A, %b %e, %H:%M:%S',
  1539. minute: '%A, %b %e, %H:%M',
  1540. hour: '%A, %b %e, %H:%M',
  1541. day: '%A, %b %e, %Y',
  1542. week: 'Week from %A, %b %e, %Y',
  1543. month: '%B %Y',
  1544. year: '%Y'
  1545. },
  1546. //formatter: defaultFormatter,
  1547. headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>',
  1548. pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b><br/>',
  1549. shadow: true,
  1550. //shared: false,
  1551. snap: isTouchDevice ? 25 : 10,
  1552. style: {
  1553. color: '#333333',
  1554. cursor: 'default',
  1555. fontSize: '12px',
  1556. padding: '8px',
  1557. whiteSpace: 'nowrap'
  1558. }
  1559. //xDateFormat: '%A, %b %e, %Y',
  1560. //valueDecimals: null,
  1561. //valuePrefix: '',
  1562. //valueSuffix: ''
  1563. },
  1564. credits: {
  1565. enabled: true,
  1566. text: 'Highcharts.com',
  1567. href: 'http://www.highcharts.com',
  1568. position: {
  1569. align: 'right',
  1570. x: -10,
  1571. verticalAlign: 'bottom',
  1572. y: -5
  1573. },
  1574. style: {
  1575. cursor: 'pointer',
  1576. color: '#909090',
  1577. fontSize: '9px'
  1578. }
  1579. }
  1580. };
  1581. // Series defaults
  1582. var defaultPlotOptions = defaultOptions.plotOptions,
  1583. defaultSeriesOptions = defaultPlotOptions.line;
  1584. // set the default time methods
  1585. setTimeMethods();
  1586. /**
  1587. * Set the time methods globally based on the useUTC option. Time method can be either
  1588. * local time or UTC (default).
  1589. */
  1590. function setTimeMethods() {
  1591. var useUTC = defaultOptions.global.useUTC,
  1592. GET = useUTC ? 'getUTC' : 'get',
  1593. SET = useUTC ? 'setUTC' : 'set';
  1594. makeTime = useUTC ? Date.UTC : function (year, month, date, hours, minutes, seconds) {
  1595. return new Date(
  1596. year,
  1597. month,
  1598. pick(date, 1),
  1599. pick(hours, 0),
  1600. pick(minutes, 0),
  1601. pick(seconds, 0)
  1602. ).getTime();
  1603. };
  1604. getMinutes = GET + 'Minutes';
  1605. getHours = GET + 'Hours';
  1606. getDay = GET + 'Day';
  1607. getDate = GET + 'Date';
  1608. getMonth = GET + 'Month';
  1609. getFullYear = GET + 'FullYear';
  1610. setMinutes = SET + 'Minutes';
  1611. setHours = SET + 'Hours';
  1612. setDate = SET + 'Date';
  1613. setMonth = SET + 'Month';
  1614. setFullYear = SET + 'FullYear';
  1615. }
  1616. /**
  1617. * Merge the default options with custom options and return the new options structure
  1618. * @param {Object} options The new custom options
  1619. */
  1620. function setOptions(options) {
  1621. // Pull out axis options and apply them to the respective default axis options
  1622. /*defaultXAxisOptions = merge(defaultXAxisOptions, options.xAxis);
  1623. defaultYAxisOptions = merge(defaultYAxisOptions, options.yAxis);
  1624. options.xAxis = options.yAxis = UNDEFINED;*/
  1625. // Merge in the default options
  1626. defaultOptions = merge(defaultOptions, options);
  1627. // Apply UTC
  1628. setTimeMethods();
  1629. return defaultOptions;
  1630. }
  1631. /**
  1632. * Get the updated default options. Merely exposing defaultOptions for outside modules
  1633. * isn't enough because the setOptions method creates a new object.
  1634. */
  1635. function getOptions() {
  1636. return defaultOptions;
  1637. }
  1638. /**
  1639. * Handle color operations. The object methods are chainable.
  1640. * @param {String} input The input color in either rbga or hex format
  1641. */
  1642. var Color = function (input) {
  1643. // declare variables
  1644. var rgba = [], result, stops;
  1645. /**
  1646. * Parse the input color to rgba array
  1647. * @param {String} input
  1648. */
  1649. function init(input) {
  1650. // Gradients
  1651. if (input && input.stops) {
  1652. stops = map(input.stops, function (stop) {
  1653. return Color(stop[1]);
  1654. });
  1655. // Solid colors
  1656. } else {
  1657. // rgba
  1658. result = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/.exec(input);
  1659. if (result) {
  1660. rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)];
  1661. } else {
  1662. // hex
  1663. result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(input);
  1664. if (result) {
  1665. rgba = [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1];
  1666. } else {
  1667. // rgb
  1668. result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(input);
  1669. if (result) {
  1670. rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1];
  1671. }
  1672. }
  1673. }
  1674. }
  1675. }
  1676. /**
  1677. * Return the color a specified format
  1678. * @param {String} format
  1679. */
  1680. function get(format) {
  1681. var ret;
  1682. if (stops) {
  1683. ret = merge(input);
  1684. ret.stops = [].concat(ret.stops);
  1685. each(stops, function (stop, i) {
  1686. ret.stops[i] = [ret.stops[i][0], stop.get(format)];
  1687. });
  1688. // it's NaN if gradient colors on a column chart
  1689. } else if (rgba && !isNaN(rgba[0])) {
  1690. if (format === 'rgb') {
  1691. ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')';
  1692. } else if (format === 'a') {
  1693. ret = rgba[3];
  1694. } else {
  1695. ret = 'rgba(' + rgba.join(',') + ')';
  1696. }
  1697. } else {
  1698. ret = input;
  1699. }
  1700. return ret;
  1701. }
  1702. /**
  1703. * Brighten the color
  1704. * @param {Number} alpha
  1705. */
  1706. function brighten(alpha) {
  1707. if (stops) {
  1708. each(stops, function (stop) {
  1709. stop.brighten(alpha);
  1710. });
  1711. } else if (isNumber(alpha) && alpha !== 0) {
  1712. var i;
  1713. for (i = 0; i < 3; i++) {
  1714. rgba[i] += pInt(alpha * 255);
  1715. if (rgba[i] < 0) {
  1716. rgba[i] = 0;
  1717. }
  1718. if (rgba[i] > 255) {
  1719. rgba[i] = 255;
  1720. }
  1721. }
  1722. }
  1723. return this;
  1724. }
  1725. /**
  1726. * Set the color's opacity to a given alpha value
  1727. * @param {Number} alpha
  1728. */
  1729. function setOpacity(alpha) {
  1730. rgba[3] = alpha;
  1731. return this;
  1732. }
  1733. // initialize: parse the input
  1734. init(input);
  1735. // public methods
  1736. return {
  1737. get: get,
  1738. brighten: brighten,
  1739. rgba: rgba,
  1740. setOpacity: setOpacity
  1741. };
  1742. };
  1743. /**
  1744. * A wrapper object for SVG elements
  1745. */
  1746. function SVGElement() {}
  1747. SVGElement.prototype = {
  1748. /**
  1749. * Initialize the SVG renderer
  1750. * @param {Object} renderer
  1751. * @param {String} nodeName
  1752. */
  1753. init: function (renderer, nodeName) {
  1754. var wrapper = this;
  1755. wrapper.element = nodeName === 'span' ?
  1756. createElement(nodeName) :
  1757. doc.createElementNS(SVG_NS, nodeName);
  1758. wrapper.renderer = renderer;
  1759. /**
  1760. * A collection of attribute setters. These methods, if defined, are called right before a certain
  1761. * attribute is set on an element wrapper. Returning false prevents the default attribute
  1762. * setter to run. Returning a value causes the default setter to set that value. Used in
  1763. * Renderer.label.
  1764. */
  1765. wrapper.attrSetters = {};
  1766. },
  1767. /**
  1768. * Default base for animation
  1769. */
  1770. opacity: 1,
  1771. /**
  1772. * Animate a given attribute
  1773. * @param {Object} params
  1774. * @param {Number} options The same options as in jQuery animation
  1775. * @param {Function} complete Function to perform at the end of animation
  1776. */
  1777. animate: function (params, options, complete) {
  1778. var animOptions = pick(options, globalAnimation, true);
  1779. stop(this); // stop regardless of animation actually running, or reverting to .attr (#607)
  1780. if (animOptions) {
  1781. animOptions = merge(animOptions);
  1782. if (complete) { // allows using a callback with the global animation without overwriting it
  1783. animOptions.complete = complete;
  1784. }
  1785. animate(this, params, animOptions);
  1786. } else {
  1787. this.attr(params);
  1788. if (complete) {
  1789. complete();
  1790. }
  1791. }
  1792. },
  1793. /**
  1794. * Set or get a given attribute
  1795. * @param {Object|String} hash
  1796. * @param {Mixed|Undefined} val
  1797. */
  1798. attr: function (hash, val) {
  1799. var wrapper = this,
  1800. key,
  1801. value,
  1802. result,
  1803. i,
  1804. child,
  1805. element = wrapper.element,
  1806. nodeName = element.nodeName.toLowerCase(), // Android2 requires lower for "text"
  1807. renderer = wrapper.renderer,
  1808. skipAttr,
  1809. titleNode,
  1810. attrSetters = wrapper.attrSetters,
  1811. shadows = wrapper.shadows,
  1812. hasSetSymbolSize,
  1813. doTransform,
  1814. ret = wrapper;
  1815. // single key-value pair
  1816. if (isString(hash) && defined(val)) {
  1817. key = hash;
  1818. hash = {};
  1819. hash[key] = val;
  1820. }
  1821. // used as a getter: first argument is a string, second is undefined
  1822. if (isString(hash)) {
  1823. key = hash;
  1824. if (nodeName === 'circle') {
  1825. key = { x: 'cx', y: 'cy' }[key] || key;
  1826. } else if (key === 'strokeWidth') {
  1827. key = 'stroke-width';
  1828. }
  1829. ret = attr(element, key) || wrapper[key] || 0;
  1830. if (key !== 'd' && key !== 'visibility') { // 'd' is string in animation step
  1831. ret = parseFloat(ret);
  1832. }
  1833. // setter
  1834. } else {
  1835. for (key in hash) {
  1836. skipAttr = false; // reset
  1837. value = hash[key];
  1838. // check for a specific attribute setter
  1839. result = attrSetters[key] && attrSetters[key].call(wrapper, value, key);
  1840. if (result !== false) {
  1841. if (result !== UNDEFINED) {
  1842. value = result; // the attribute setter has returned a new value to set
  1843. }
  1844. // paths
  1845. if (key === 'd') {
  1846. if (value && value.join) { // join path
  1847. value = value.join(' ');
  1848. }
  1849. if (/(NaN| {2}|^$)/.test(value)) {
  1850. value = 'M 0 0';
  1851. }
  1852. //wrapper.d = value; // shortcut for animations
  1853. // update child tspans x values
  1854. } else if (key === 'x' && nodeName === 'text') {
  1855. for (i = 0; i < element.childNodes.length; i++) {
  1856. child = element.childNodes[i];
  1857. // if the x values are equal, the tspan represents a linebreak
  1858. if (attr(child, 'x') === attr(element, 'x')) {
  1859. //child.setAttribute('x', value);
  1860. attr(child, 'x', value);
  1861. }
  1862. }
  1863. } else if (wrapper.rotation && (key === 'x' || key === 'y')) {
  1864. doTransform = true;
  1865. // apply gradients
  1866. } else if (key === 'fill') {
  1867. value = renderer.color(value, element, key);
  1868. // circle x and y
  1869. } else if (nodeName === 'circle' && (key === 'x' || key === 'y')) {
  1870. key = { x: 'cx', y: 'cy' }[key] || key;
  1871. // rectangle border radius
  1872. } else if (nodeName === 'rect' && key === 'r') {
  1873. attr(element, {
  1874. rx: value,
  1875. ry: value
  1876. });
  1877. skipAttr = true;
  1878. // translation and text rotation
  1879. } else if (key === 'translateX' || key === 'translateY' || key === 'rotation' ||
  1880. key === 'verticalAlign' || key === 'scaleX' || key === 'scaleY') {
  1881. doTransform = true;
  1882. skipAttr = true;
  1883. // apply opacity as subnode (required by legacy WebKit and Batik)
  1884. } else if (key === 'stroke') {
  1885. value = renderer.color(value, element, key);
  1886. // emulate VML's dashstyle implementation
  1887. } else if (key === 'dashstyle') {
  1888. key = 'stroke-dasharray';
  1889. value = value && value.toLowerCase();
  1890. if (value === 'solid') {
  1891. value = NONE;
  1892. } else if (value) {
  1893. value = value
  1894. .replace('shortdashdotdot', '3,1,1,1,1,1,')
  1895. .replace('shortdashdot', '3,1,1,1')
  1896. .replace('shortdot', '1,1,')
  1897. .replace('shortdash', '3,1,')
  1898. .replace('longdash', '8,3,')
  1899. .replace(/dot/g, '1,3,')
  1900. .replace('dash', '4,3,')
  1901. .replace(/,$/, '')
  1902. .split(','); // ending comma
  1903. i = value.length;
  1904. while (i--) {
  1905. value[i] = pInt(value[i]) * hash['stroke-width'];
  1906. }
  1907. value = value.join(',');
  1908. }
  1909. // IE9/MooTools combo: MooTools returns objects instead of numbers and IE9 Beta 2
  1910. // is unable to cast them. Test again with final IE9.
  1911. } else if (key === 'width') {
  1912. value = pInt(value);
  1913. // Text alignment
  1914. } else if (key === 'align') {
  1915. key = 'text-anchor';
  1916. value = { left: 'start', center: 'middle', right: 'end' }[value];
  1917. // Title requires a subnode, #431
  1918. } else if (key === 'title') {
  1919. titleNode = element.getElementsByTagName('title')[0];
  1920. if (!titleNode) {
  1921. titleNode = doc.createElementNS(SVG_NS, 'title');
  1922. element.appendChild(titleNode);
  1923. }
  1924. titleNode.textContent = value;
  1925. }
  1926. // jQuery animate changes case
  1927. if (key === 'strokeWidth') {
  1928. key = 'stroke-width';
  1929. }
  1930. // In Chrome/Win < 6 as well as Batik, the stroke attribute can't be set when the stroke-
  1931. // width is 0. #1369
  1932. if (key === 'stroke-width' || key === 'stroke') {
  1933. wrapper[key] = value;
  1934. // Only apply the stroke attribute if the stroke width is defined and larger than 0
  1935. if (wrapper.stroke && wrapper['stroke-width']) {
  1936. attr(element, 'stroke', wrapper.stroke);
  1937. attr(element, 'stroke-width', wrapper['stroke-width']);
  1938. wrapper.hasStroke = true;
  1939. } else if (key === 'stroke-width' && value === 0 && wrapper.hasStroke) {
  1940. element.removeAttribute('stroke');
  1941. wrapper.hasStroke = false;
  1942. }
  1943. skipAttr = true;
  1944. }
  1945. // symbols
  1946. if (wrapper.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) {
  1947. if (!hasSetSymbolSize) {
  1948. wrapper.symbolAttr(hash);
  1949. hasSetSymbolSize = true;
  1950. }
  1951. skipAttr = true;
  1952. }
  1953. // let the shadow follow the main element
  1954. if (shadows && /^(width|height|visibility|x|y|d|transform)$/.test(key)) {
  1955. i = shadows.length;
  1956. while (i--) {
  1957. attr(
  1958. shadows[i],
  1959. key,
  1960. key === 'height' ?
  1961. mathMax(value - (shadows[i].cutHeight || 0), 0) :
  1962. value
  1963. );
  1964. }
  1965. }
  1966. // validate heights
  1967. if ((key === 'width' || key === 'height') && nodeName === 'rect' && value < 0) {
  1968. value = 0;
  1969. }
  1970. // Record for animation and quick access without polling the DOM
  1971. wrapper[key] = value;
  1972. if (key === 'text') {
  1973. // Delete bBox memo when the text changes
  1974. if (value !== wrapper.textStr) {
  1975. delete wrapper.bBox;
  1976. }
  1977. wrapper.textStr = value;
  1978. if (wrapper.added) {
  1979. renderer.buildText(wrapper);
  1980. }
  1981. } else if (!skipAttr) {
  1982. attr(element, key, value);
  1983. }
  1984. }
  1985. }
  1986. // Update transform. Do this outside the loop to prevent redundant updating for batch setting
  1987. // of attributes.
  1988. if (doTransform) {
  1989. wrapper.updateTransform();
  1990. }
  1991. }
  1992. return ret;
  1993. },
  1994. /**
  1995. * Add a class name to an element
  1996. */
  1997. addClass: function (className) {
  1998. attr(this.element, 'class', attr(this.element, 'class') + ' ' + className);
  1999. return this;
  2000. },
  2001. /* hasClass and removeClass are not (yet) needed
  2002. hasClass: function (className) {
  2003. return attr(this.element, 'class').indexOf(className) !== -1;
  2004. },
  2005. removeClass: function (className) {
  2006. attr(this.element, 'class', attr(this.element, 'class').replace(className, ''));
  2007. return this;
  2008. },
  2009. */
  2010. /**
  2011. * If one of the symbol size affecting parameters are changed,
  2012. * check all the others only once for each call to an element's
  2013. * .attr() method
  2014. * @param {Object} hash
  2015. */
  2016. symbolAttr: function (hash) {
  2017. var wrapper = this;
  2018. each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function (key) {
  2019. wrapper[key] = pick(hash[key], wrapper[key]);
  2020. });
  2021. wrapper.attr({
  2022. d: wrapper.renderer.symbols[wrapper.symbolName](wrapper.x, wrapper.y, wrapper.width, wrapper.height, wrapper)
  2023. });
  2024. },
  2025. /**
  2026. * Apply a clipping path to this object
  2027. * @param {String} id
  2028. */
  2029. clip: function (clipRect) {
  2030. return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : NONE);
  2031. },
  2032. /**
  2033. * Calculate the coordinates needed for drawing a rectangle crisply and return the
  2034. * calculated attributes
  2035. * @param {Number} strokeWidth
  2036. * @param {Number} x
  2037. * @param {Number} y
  2038. * @param {Number} width
  2039. * @param {Number} height
  2040. */
  2041. crisp: function (strokeWidth, x, y, width, height) {
  2042. var wrapper = this,
  2043. key,
  2044. attribs = {},
  2045. values = {},
  2046. normalizer;
  2047. strokeWidth = strokeWidth || wrapper.strokeWidth || (wrapper.attr && wrapper.attr('stroke-width')) || 0;
  2048. normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors
  2049. // normalize for crisp edges
  2050. values.x = mathFloor(x || wrapper.x || 0) + normalizer;
  2051. values.y = mathFloor(y || wrapper.y || 0) + normalizer;
  2052. values.width = mathFloor((width || wrapper.width || 0) - 2 * normalizer);
  2053. values.height = mathFloor((height || wrapper.height || 0) - 2 * normalizer);
  2054. values.strokeWidth = strokeWidth;
  2055. for (key in values) {
  2056. if (wrapper[key] !== values[key]) { // only set attribute if changed
  2057. wrapper[key] = attribs[key] = values[key];
  2058. }
  2059. }
  2060. return attribs;
  2061. },
  2062. /**
  2063. * Set styles for the element
  2064. * @param {Object} styles
  2065. */
  2066. css: function (styles) {
  2067. /*jslint unparam: true*//* allow unused param a in the regexp function below */
  2068. var elemWrapper = this,
  2069. elem = elemWrapper.element,
  2070. textWidth = styles && styles.width && elem.nodeName.toLowerCase() === 'text',
  2071. n,
  2072. serializedCss = '',
  2073. hyphenate = function (a, b) { return '-' + b.toLowerCase(); };
  2074. /*jslint unparam: false*/
  2075. // convert legacy
  2076. if (styles && styles.color) {
  2077. styles.fill = styles.color;
  2078. }
  2079. // Merge the new styles with the old ones
  2080. styles = extend(
  2081. elemWrapper.styles,
  2082. styles
  2083. );
  2084. // store object
  2085. elemWrapper.styles = styles;
  2086. // Don't handle line wrap on canvas
  2087. if (useCanVG && textWidth) {
  2088. delete styles.width;
  2089. }
  2090. // serialize and set style attribute
  2091. if (isIE && !hasSVG) { // legacy IE doesn't support setting style attribute
  2092. if (textWidth) {
  2093. delete styles.width;
  2094. }
  2095. css(elemWrapper.element, styles);
  2096. } else {
  2097. for (n in styles) {
  2098. serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';';
  2099. }
  2100. elemWrapper.attr({
  2101. style: serializedCss
  2102. });
  2103. }
  2104. // re-build text
  2105. if (textWidth && elemWrapper.added) {
  2106. elemWrapper.renderer.buildText(elemWrapper);
  2107. }
  2108. return elemWrapper;
  2109. },
  2110. /**
  2111. * Add an event listener
  2112. * @param {String} eventType
  2113. * @param {Function} handler
  2114. */
  2115. on: function (eventType, handler) {
  2116. // touch
  2117. if (hasTouch && eventType === 'click') {
  2118. this.element.ontouchstart = function (e) {
  2119. e.preventDefault();
  2120. handler();
  2121. };
  2122. }
  2123. // simplest possible event model for internal use
  2124. this.element['on' + eventType] = handler;
  2125. return this;
  2126. },
  2127. /**
  2128. * Set the coordinates needed to draw a consistent radial gradient across
  2129. * pie slices regardless of positioning inside the chart. The format is
  2130. * [centerX, centerY, diameter] in pixels.
  2131. */
  2132. setRadialReference: function (coordinates) {
  2133. this.element.radialReference = coordinates;
  2134. return this;
  2135. },
  2136. /**
  2137. * Move an object and its children by x and y values
  2138. * @param {Number} x
  2139. * @param {Number} y
  2140. */
  2141. translate: function (x, y) {
  2142. return this.attr({
  2143. translateX: x,
  2144. translateY: y
  2145. });
  2146. },
  2147. /**
  2148. * Invert a group, rotate and flip
  2149. */
  2150. invert: function () {
  2151. var wrapper = this;
  2152. wrapper.inverted = true;
  2153. wrapper.updateTransform();
  2154. return wrapper;
  2155. },
  2156. /**
  2157. * Apply CSS to HTML elements. This is used in text within SVG rendering and
  2158. * by the VML renderer
  2159. */
  2160. htmlCss: function (styles) {
  2161. var wrapper = this,
  2162. element = wrapper.element,
  2163. textWidth = styles && element.tagName === 'SPAN' && styles.width;
  2164. if (textWidth) {
  2165. delete styles.width;
  2166. wrapper.textWidth = textWidth;
  2167. wrapper.updateTransform();
  2168. }
  2169. wrapper.styles = extend(wrapper.styles, styles);
  2170. css(wrapper.element, styles);
  2171. return wrapper;
  2172. },
  2173. /**
  2174. * VML and useHTML method for calculating the bounding box based on offsets
  2175. * @param {Boolean} refresh Whether to force a fresh value from the DOM or to
  2176. * use the cached value
  2177. *
  2178. * @return {Object} A hash containing values for x, y, width and height
  2179. */
  2180. htmlGetBBox: function () {
  2181. var wrapper = this,
  2182. element = wrapper.element,
  2183. bBox = wrapper.bBox;
  2184. // faking getBBox in exported SVG in legacy IE
  2185. if (!bBox) {
  2186. // faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?)
  2187. if (element.nodeName === 'text') {
  2188. element.style.position = ABSOLUTE;
  2189. }
  2190. bBox = wrapper.bBox = {
  2191. x: element.offsetLeft,
  2192. y: element.offsetTop,
  2193. width: element.offsetWidth,
  2194. height: element.offsetHeight
  2195. };
  2196. }
  2197. return bBox;
  2198. },
  2199. /**
  2200. * VML override private method to update elements based on internal
  2201. * properties based on SVG transform
  2202. */
  2203. htmlUpdateTransform: function () {
  2204. // aligning non added elements is expensive
  2205. if (!this.added) {
  2206. this.alignOnAdd = true;
  2207. return;
  2208. }
  2209. var wrapper = this,
  2210. renderer = wrapper.renderer,
  2211. elem = wrapper.element,
  2212. translateX = wrapper.translateX || 0,
  2213. translateY = wrapper.translateY || 0,
  2214. x = wrapper.x || 0,
  2215. y = wrapper.y || 0,
  2216. align = wrapper.textAlign || 'left',
  2217. alignCorrection = { left: 0, center: 0.5, right: 1 }[align],
  2218. nonLeft = align && align !== 'left',
  2219. shadows = wrapper.shadows;
  2220. // apply translate
  2221. if (translateX || translateY) {
  2222. css(elem, {
  2223. marginLeft: translateX,
  2224. marginTop: translateY
  2225. });
  2226. if (shadows) { // used in labels/tooltip
  2227. each(shadows, function (shadow) {
  2228. css(shadow, {
  2229. marginLeft: translateX + 1,
  2230. marginTop: translateY + 1
  2231. });
  2232. });
  2233. }
  2234. }
  2235. // apply inversion
  2236. if (wrapper.inverted) { // wrapper is a group
  2237. each(elem.childNodes, function (child) {
  2238. renderer.invertChild(child, elem);
  2239. });
  2240. }
  2241. if (elem.tagName === 'SPAN') {
  2242. var width, height,
  2243. rotation = wrapper.rotation,
  2244. baseline,
  2245. radians = 0,
  2246. costheta = 1,
  2247. sintheta = 0,
  2248. quad,
  2249. textWidth = pInt(wrapper.textWidth),
  2250. xCorr = wrapper.xCorr || 0,
  2251. yCorr = wrapper.yCorr || 0,
  2252. currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth].join(','),
  2253. rotationStyle = {},
  2254. cssTransformKey;
  2255. if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed
  2256. if (defined(rotation)) {
  2257. if (renderer.isSVG) { // #916
  2258. cssTransformKey = isIE ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : '';
  2259. rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)';
  2260. } else {
  2261. radians = rotation * deg2rad; // deg to rad
  2262. costheta = mathCos(radians);
  2263. sintheta = mathSin(radians);
  2264. // Adjust for alignment and rotation. Rotation of useHTML content is not yet implemented
  2265. // but it can probably be implemented for Firefox 3.5+ on user request. FF3.5+
  2266. // has support for CSS3 transform. The getBBox method also needs to be updated
  2267. // to compensate for the rotation, like it currently does for SVG.
  2268. // Test case: http://highcharts.com/tests/?file=text-rotation
  2269. rotationStyle.filter = rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta,
  2270. ', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta,
  2271. ', sizingMethod=\'auto expand\')'].join('') : NONE;
  2272. }
  2273. css(elem, rotationStyle);
  2274. }
  2275. width = pick(wrapper.elemWidth, elem.offsetWidth);
  2276. height = pick(wrapper.elemHeight, elem.offsetHeight);
  2277. // update textWidth
  2278. if (width > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254
  2279. css(elem, {
  2280. width: textWidth + PX,
  2281. display: 'block',
  2282. whiteSpace: 'normal'
  2283. });
  2284. width = textWidth;
  2285. }
  2286. // correct x and y
  2287. baseline = renderer.fontMetrics(elem.style.fontSize).b;
  2288. xCorr = costheta < 0 && -width;
  2289. yCorr = sintheta < 0 && -height;
  2290. // correct for baseline and corners spilling out after rotation
  2291. quad = costheta * sintheta < 0;
  2292. xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection);
  2293. yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1);
  2294. // correct for the length/height of the text
  2295. if (nonLeft) {
  2296. xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1);
  2297. if (rotation) {
  2298. yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1);
  2299. }
  2300. css(elem, {
  2301. textAlign: align
  2302. });
  2303. }
  2304. // record correction
  2305. wrapper.xCorr = xCorr;
  2306. wrapper.yCorr = yCorr;
  2307. }
  2308. // apply position with correction
  2309. css(elem, {
  2310. left: (x + xCorr) + PX,
  2311. top: (y + yCorr) + PX
  2312. });
  2313. // force reflow in webkit to apply the left and top on useHTML element (#1249)
  2314. if (isWebKit) {
  2315. height = elem.offsetHeight; // assigned to height for JSLint purpose
  2316. }
  2317. // record current text transform
  2318. wrapper.cTT = currentTextTransform;
  2319. }
  2320. },
  2321. /**
  2322. * Private method to update the transform attribute based on internal
  2323. * properties
  2324. */
  2325. updateTransform: function () {
  2326. var wrapper = this,
  2327. translateX = wrapper.translateX || 0,
  2328. translateY = wrapper.translateY || 0,
  2329. scaleX = wrapper.scaleX,
  2330. scaleY = wrapper.scaleY,
  2331. inverted = wrapper.inverted,
  2332. rotation = wrapper.rotation,
  2333. transform = [];
  2334. // flipping affects translate as adjustment for flipping around the group's axis
  2335. if (inverted) {
  2336. translateX += wrapper.attr('width');
  2337. translateY += wrapper.attr('height');
  2338. }
  2339. // apply translate
  2340. if (translateX || translateY) {
  2341. transform.push('translate(' + translateX + ',' + translateY + ')');
  2342. }
  2343. // apply rotation
  2344. if (inverted) {
  2345. transform.push('rotate(90) scale(-1,1)');
  2346. } else if (rotation) { // text rotation
  2347. transform.push('rotate(' + rotation + ' ' + (wrapper.x || 0) + ' ' + (wrapper.y || 0) + ')');
  2348. }
  2349. // apply scale
  2350. if (defined(scaleX) || defined(scaleY)) {
  2351. transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')');
  2352. }
  2353. if (transform.length) {
  2354. attr(wrapper.element, 'transform', transform.join(' '));
  2355. }
  2356. },
  2357. /**
  2358. * Bring the element to the front
  2359. */
  2360. toFront: function () {
  2361. var element = this.element;
  2362. element.parentNode.appendChild(element);
  2363. return this;
  2364. },
  2365. /**
  2366. * Break down alignment options like align, verticalAlign, x and y
  2367. * to x and y relative to the chart.
  2368. *
  2369. * @param {Object} alignOptions
  2370. * @param {Boolean} alignByTranslate
  2371. * @param {String[Object} box The box to align to, needs a width and height. When the
  2372. * box is a string, it refers to an object in the Renderer. For example, when
  2373. * box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height
  2374. * x and y properties.
  2375. *
  2376. */
  2377. align: function (alignOptions, alignByTranslate, box) {
  2378. var align,
  2379. vAlign,
  2380. x,
  2381. y,
  2382. attribs = {},
  2383. alignTo,
  2384. renderer = this.renderer,
  2385. alignedObjects = renderer.alignedObjects;
  2386. // First call on instanciate
  2387. if (alignOptions) {
  2388. this.alignOptions = alignOptions;
  2389. this.alignByTranslate = alignByTranslate;
  2390. if (!box || isString(box)) { // boxes other than renderer handle this internally
  2391. this.alignTo = alignTo = box || 'renderer';
  2392. erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize
  2393. alignedObjects.push(this);
  2394. box = null; // reassign it below
  2395. }
  2396. // When called on resize, no arguments are supplied
  2397. } else {
  2398. alignOptions = this.alignOptions;
  2399. alignByTranslate = this.alignByTranslate;
  2400. alignTo = this.alignTo;
  2401. }
  2402. box = pick(box, renderer[alignTo], renderer);
  2403. // Assign variables
  2404. align = alignOptions.align;
  2405. vAlign = alignOptions.verticalAlign;
  2406. x = (box.x || 0) + (alignOptions.x || 0); // default: left align
  2407. y = (box.y || 0) + (alignOptions.y || 0); // default: top align
  2408. // Align
  2409. if (align === 'right' || align === 'center') {
  2410. x += (box.width - (alignOptions.width || 0)) /
  2411. { right: 1, center: 2 }[align];
  2412. }
  2413. attribs[alignByTranslate ? 'translateX' : 'x'] = mathRound(x);
  2414. // Vertical align
  2415. if (vAlign === 'bottom' || vAlign === 'middle') {
  2416. y += (box.height - (alignOptions.height || 0)) /
  2417. ({ bottom: 1, middle: 2 }[vAlign] || 1);
  2418. }
  2419. attribs[alignByTranslate ? 'translateY' : 'y'] = mathRound(y);
  2420. // Animate only if already placed
  2421. this[this.placed ? 'animate' : 'attr'](attribs);
  2422. this.placed = true;
  2423. this.alignAttr = attribs;
  2424. return this;
  2425. },
  2426. /**
  2427. * Get the bounding box (width, height, x and y) for the element
  2428. */
  2429. getBBox: function () {
  2430. var wrapper = this,
  2431. bBox = wrapper.bBox,
  2432. renderer = wrapper.renderer,
  2433. width,
  2434. height,
  2435. rotation = wrapper.rotation,
  2436. element = wrapper.element,
  2437. styles = wrapper.styles,
  2438. rad = rotation * deg2rad;
  2439. if (!bBox) {
  2440. // SVG elements
  2441. if (element.namespaceURI === SVG_NS || renderer.forExport) {
  2442. try { // Fails in Firefox if the container has display: none.
  2443. bBox = element.getBBox ?
  2444. // SVG: use extend because IE9 is not allowed to change width and height in case
  2445. // of rotation (below)
  2446. extend({}, element.getBBox()) :
  2447. // Canvas renderer and legacy IE in export mode
  2448. {
  2449. width: element.offsetWidth,
  2450. height: element.offsetHeight
  2451. };
  2452. } catch (e) {}
  2453. // If the bBox is not set, the try-catch block above failed. The other condition
  2454. // is for Opera that returns a width of -Infinity on hidden elements.
  2455. if (!bBox || bBox.width < 0) {
  2456. bBox = { width: 0, height: 0 };
  2457. }
  2458. // VML Renderer or useHTML within SVG
  2459. } else {
  2460. bBox = wrapper.htmlGetBBox();
  2461. }
  2462. // True SVG elements as well as HTML elements in modern browsers using the .useHTML option
  2463. // need to compensated for rotation
  2464. if (renderer.isSVG) {
  2465. width = bBox.width;
  2466. height = bBox.height;
  2467. // Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669)
  2468. if (isIE && styles && styles.fontSize === '11px' && height.toPrecision(3) === '22.7') {
  2469. bBox.height = height = 14;
  2470. }
  2471. // Adjust for rotated text
  2472. if (rotation) {
  2473. bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad));
  2474. bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad));
  2475. }
  2476. }
  2477. wrapper.bBox = bBox;
  2478. }
  2479. return bBox;
  2480. },
  2481. /**
  2482. * Show the element
  2483. */
  2484. show: function () {
  2485. return this.attr({ visibility: VISIBLE });
  2486. },
  2487. /**
  2488. * Hide the element
  2489. */
  2490. hide: function () {
  2491. return this.attr({ visibility: HIDDEN });
  2492. },
  2493. fadeOut: function (duration) {
  2494. var elemWrapper = this;
  2495. elemWrapper.animate({
  2496. opacity: 0
  2497. }, {
  2498. duration: duration || 150,
  2499. complete: function () {
  2500. elemWrapper.hide();
  2501. }
  2502. });
  2503. },
  2504. /**
  2505. * Add the element
  2506. * @param {Object|Undefined} parent Can be an element, an element wrapper or undefined
  2507. * to append the element to the renderer.box.
  2508. */
  2509. add: function (parent) {
  2510. var renderer = this.renderer,
  2511. parentWrapper = parent || renderer,
  2512. parentNode = parentWrapper.element || renderer.box,
  2513. childNodes = parentNode.childNodes,
  2514. element = this.element,
  2515. zIndex = attr(element, 'zIndex'),
  2516. otherElement,
  2517. otherZIndex,
  2518. i,
  2519. inserted;
  2520. if (parent) {
  2521. this.parentGroup = parent;
  2522. }
  2523. // mark as inverted
  2524. this.parentInverted = parent && parent.inverted;
  2525. // build formatted text
  2526. if (this.textStr !== undefined) {
  2527. renderer.buildText(this);
  2528. }
  2529. // mark the container as having z indexed children
  2530. if (zIndex) {
  2531. parentWrapper.handleZ = true;
  2532. zIndex = pInt(zIndex);
  2533. }
  2534. // insert according to this and other elements' zIndex
  2535. if (parentWrapper.handleZ) { // this element or any of its siblings has a z index
  2536. for (i = 0; i < childNodes.length; i++) {
  2537. otherElement = childNodes[i];
  2538. otherZIndex = attr(otherElement, 'zIndex');
  2539. if (otherElement !== element && (
  2540. // insert before the first element with a higher zIndex
  2541. pInt(otherZIndex) > zIndex ||
  2542. // if no zIndex given, insert before the first element with a zIndex
  2543. (!defined(zIndex) && defined(otherZIndex))
  2544. )) {
  2545. parentNode.insertBefore(element, otherElement);
  2546. inserted = true;
  2547. break;
  2548. }
  2549. }
  2550. }
  2551. // default: append at the end
  2552. if (!inserted) {
  2553. parentNode.appendChild(element);
  2554. }
  2555. // mark as added
  2556. this.added = true;
  2557. // fire an event for internal hooks
  2558. fireEvent(this, 'add');
  2559. return this;
  2560. },
  2561. /**
  2562. * Removes a child either by removeChild or move to garbageBin.
  2563. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not.
  2564. */
  2565. safeRemoveChild: function (element) {
  2566. var parentNode = element.parentNode;
  2567. if (parentNode) {
  2568. parentNode.removeChild(element);
  2569. }
  2570. },
  2571. /**
  2572. * Destroy the element and element wrapper
  2573. */
  2574. destroy: function () {
  2575. var wrapper = this,
  2576. element = wrapper.element || {},
  2577. shadows = wrapper.shadows,
  2578. key,
  2579. i;
  2580. // remove events
  2581. element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null;
  2582. stop(wrapper); // stop running animations
  2583. if (wrapper.clipPath) {
  2584. wrapper.clipPath = wrapper.clipPath.destroy();
  2585. }
  2586. // Destroy stops in case this is a gradient object
  2587. if (wrapper.stops) {
  2588. for (i = 0; i < wrapper.stops.length; i++) {
  2589. wrapper.stops[i] = wrapper.stops[i].destroy();
  2590. }
  2591. wrapper.stops = null;
  2592. }
  2593. // remove element
  2594. wrapper.safeRemoveChild(element);
  2595. // destroy shadows
  2596. if (shadows) {
  2597. each(shadows, function (shadow) {
  2598. wrapper.safeRemoveChild(shadow);
  2599. });
  2600. }
  2601. // remove from alignObjects
  2602. if (wrapper.alignTo) {
  2603. erase(wrapper.renderer.alignedObjects, wrapper);
  2604. }
  2605. for (key in wrapper) {
  2606. delete wrapper[key];
  2607. }
  2608. return null;
  2609. },
  2610. /**
  2611. * Add a shadow to the element. Must be done after the element is added to the DOM
  2612. * @param {Boolean|Object} shadowOptions
  2613. */
  2614. shadow: function (shadowOptions, group, cutOff) {
  2615. var shadows = [],
  2616. i,
  2617. shadow,
  2618. element = this.element,
  2619. strokeWidth,
  2620. shadowWidth,
  2621. shadowElementOpacity,
  2622. // compensate for inverted plot area
  2623. transform;
  2624. if (shadowOptions) {
  2625. shadowWidth = pick(shadowOptions.width, 3);
  2626. shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth;
  2627. transform = this.parentInverted ?
  2628. '(-1,-1)' :
  2629. '(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')';
  2630. for (i = 1; i <= shadowWidth; i++) {
  2631. shadow = element.cloneNode(0);
  2632. strokeWidth = (shadowWidth * 2) + 1 - (2 * i);
  2633. attr(shadow, {
  2634. 'isShadow': 'true',
  2635. 'stroke': shadowOptions.color || 'black',
  2636. 'stroke-opacity': shadowElementOpacity * i,
  2637. 'stroke-width': strokeWidth,
  2638. 'transform': 'translate' + transform,
  2639. 'fill': NONE
  2640. });
  2641. if (cutOff) {
  2642. attr(shadow, 'height', mathMax(attr(shadow, 'height') - strokeWidth, 0));
  2643. shadow.cutHeight = strokeWidth;
  2644. }
  2645. if (group) {
  2646. group.element.appendChild(shadow);
  2647. } else {
  2648. element.parentNode.insertBefore(shadow, element);
  2649. }
  2650. shadows.push(shadow);
  2651. }
  2652. this.shadows = shadows;
  2653. }
  2654. return this;
  2655. }
  2656. };
  2657. /**
  2658. * The default SVG renderer
  2659. */
  2660. var SVGRenderer = function () {
  2661. this.init.apply(this, arguments);
  2662. };
  2663. SVGRenderer.prototype = {
  2664. Element: SVGElement,
  2665. /**
  2666. * Initialize the SVGRenderer
  2667. * @param {Object} container
  2668. * @param {Number} width
  2669. * @param {Number} height
  2670. * @param {Boolean} forExport
  2671. */
  2672. init: function (container, width, height, forExport) {
  2673. var renderer = this,
  2674. loc = location,
  2675. boxWrapper,
  2676. desc;
  2677. boxWrapper = renderer.createElement('svg')
  2678. .attr({
  2679. xmlns: SVG_NS,
  2680. version: '1.1'
  2681. });
  2682. container.appendChild(boxWrapper.element);
  2683. // object properties
  2684. renderer.isSVG = true;
  2685. renderer.box = boxWrapper.element;
  2686. renderer.boxWrapper = boxWrapper;
  2687. renderer.alignedObjects = [];
  2688. // Page url used for internal references. #24, #672, #1070
  2689. renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ?
  2690. loc.href
  2691. .replace(/#.*?$/, '') // remove the hash
  2692. .replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes
  2693. .replace(/ /g, '%20') : // replace spaces (needed for Safari only)
  2694. '';
  2695. // Add description
  2696. desc = this.createElement('desc').add();
  2697. desc.element.appendChild(doc.createTextNode('Created with ' + PRODUCT + ' ' + VERSION));
  2698. renderer.defs = this.createElement('defs').add();
  2699. renderer.forExport = forExport;
  2700. renderer.gradients = {}; // Object where gradient SvgElements are stored
  2701. renderer.setSize(width, height, false);
  2702. // Issue 110 workaround:
  2703. // In Firefox, if a div is positioned by percentage, its pixel position may land
  2704. // between pixels. The container itself doesn't display this, but an SVG element
  2705. // inside this container will be drawn at subpixel precision. In order to draw
  2706. // sharp lines, this must be compensated for. This doesn't seem to work inside
  2707. // iframes though (like in jsFiddle).
  2708. var subPixelFix, rect;
  2709. if (isFirefox && container.getBoundingClientRect) {
  2710. renderer.subPixelFix = subPixelFix = function () {
  2711. css(container, { left: 0, top: 0 });
  2712. rect = container.getBoundingClientRect();
  2713. css(container, {
  2714. left: (mathCeil(rect.left) - rect.left) + PX,
  2715. top: (mathCeil(rect.top) - rect.top) + PX
  2716. });
  2717. };
  2718. // run the fix now
  2719. subPixelFix();
  2720. // run it on resize
  2721. addEvent(win, 'resize', subPixelFix);
  2722. }
  2723. },
  2724. /**
  2725. * Detect whether the renderer is hidden. This happens when one of the parent elements
  2726. * has display: none. #608.
  2727. */
  2728. isHidden: function () {
  2729. return !this.boxWrapper.getBBox().width;
  2730. },
  2731. /**
  2732. * Destroys the renderer and its allocated members.
  2733. */
  2734. destroy: function () {
  2735. var renderer = this,
  2736. rendererDefs = renderer.defs;
  2737. renderer.box = null;
  2738. renderer.boxWrapper = renderer.boxWrapper.destroy();
  2739. // Call destroy on all gradient elements
  2740. destroyObjectProperties(renderer.gradients || {});
  2741. renderer.gradients = null;
  2742. // Defs are null in VMLRenderer
  2743. // Otherwise, destroy them here.
  2744. if (rendererDefs) {
  2745. renderer.defs = rendererDefs.destroy();
  2746. }
  2747. // Remove sub pixel fix handler
  2748. // We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed
  2749. // See issue #982
  2750. if (renderer.subPixelFix) {
  2751. removeEvent(win, 'resize', renderer.subPixelFix);
  2752. }
  2753. renderer.alignedObjects = null;
  2754. return null;
  2755. },
  2756. /**
  2757. * Create a wrapper for an SVG element
  2758. * @param {Object} nodeName
  2759. */
  2760. createElement: function (nodeName) {
  2761. var wrapper = new this.Element();
  2762. wrapper.init(this, nodeName);
  2763. return wrapper;
  2764. },
  2765. /**
  2766. * Dummy function for use in canvas renderer
  2767. */
  2768. draw: function () {},
  2769. /**
  2770. * Parse a simple HTML string into SVG tspans
  2771. *
  2772. * @param {Object} textNode The parent text SVG node
  2773. */
  2774. buildText: function (wrapper) {
  2775. var textNode = wrapper.element,
  2776. renderer = this,
  2777. forExport = renderer.forExport,
  2778. lines = pick(wrapper.textStr, '').toString()
  2779. .replace(/<(b|strong)>/g, '<span style="font-weight:bold">')
  2780. .replace(/<(i|em)>/g, '<span style="font-style:italic">')
  2781. .replace(/<a/g, '<span')
  2782. .replace(/<\/(b|strong|i|em|a)>/g, '</span>')
  2783. .split(/<br.*?>/g),
  2784. childNodes = textNode.childNodes,
  2785. styleRegex = /style="([^"]+)"/,
  2786. hrefRegex = /href="([^"]+)"/,
  2787. parentX = attr(textNode, 'x'),
  2788. textStyles = wrapper.styles,
  2789. width = textStyles && textStyles.width && pInt(textStyles.width),
  2790. textLineHeight = textStyles && textStyles.lineHeight,
  2791. i = childNodes.length;
  2792. /// remove old text
  2793. while (i--) {
  2794. textNode.removeChild(childNodes[i]);
  2795. }
  2796. if (width && !wrapper.added) {
  2797. this.box.appendChild(textNode); // attach it to the DOM to read offset width
  2798. }
  2799. // remove empty line at end
  2800. if (lines[lines.length - 1] === '') {
  2801. lines.pop();
  2802. }
  2803. // build the lines
  2804. each(lines, function (line, lineNo) {
  2805. var spans, spanNo = 0;
  2806. line = line.replace(/<span/g, '|||<span').replace(/<\/span>/g, '</span>|||');
  2807. spans = line.split('|||');
  2808. each(spans, function (span) {
  2809. if (span !== '' || spans.length === 1) {
  2810. var attributes = {},
  2811. tspan = doc.createElementNS(SVG_NS, 'tspan'),
  2812. spanStyle; // #390
  2813. if (styleRegex.test(span)) {
  2814. spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2');
  2815. attr(tspan, 'style', spanStyle);
  2816. }
  2817. if (hrefRegex.test(span) && !forExport) { // Not for export - #1529
  2818. attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"');
  2819. css(tspan, { cursor: 'pointer' });
  2820. }
  2821. span = (span.replace(/<(.|\n)*?>/g, '') || ' ')
  2822. .replace(/&lt;/g, '<')
  2823. .replace(/&gt;/g, '>');
  2824. // add the text node
  2825. tspan.appendChild(doc.createTextNode(span));
  2826. if (!spanNo) { // first span in a line, align it to the left
  2827. attributes.x = parentX;
  2828. } else {
  2829. attributes.dx = 0; // #16
  2830. }
  2831. // add attributes
  2832. attr(tspan, attributes);
  2833. // first span on subsequent line, add the line height
  2834. if (!spanNo && lineNo) {
  2835. // allow getting the right offset height in exporting in IE
  2836. if (!hasSVG && forExport) {
  2837. css(tspan, { display: 'block' });
  2838. }
  2839. // Set the line height based on the font size of either
  2840. // the text element or the tspan element
  2841. attr(
  2842. tspan,
  2843. 'dy',
  2844. textLineHeight || renderer.fontMetrics(
  2845. /px$/.test(tspan.style.fontSize) ?
  2846. tspan.style.fontSize :
  2847. textStyles.fontSize
  2848. ).h,
  2849. // Safari 6.0.2 - too optimized for its own good (#1539)
  2850. // TODO: revisit this with future versions of Safari
  2851. isWebKit && tspan.offsetHeight
  2852. );
  2853. }
  2854. // Append it
  2855. textNode.appendChild(tspan);
  2856. spanNo++;
  2857. // check width and apply soft breaks
  2858. if (width) {
  2859. var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273
  2860. tooLong,
  2861. actualWidth,
  2862. rest = [];
  2863. while (words.length || rest.length) {
  2864. delete wrapper.bBox; // delete cache
  2865. actualWidth = wrapper.getBBox().width;
  2866. tooLong = actualWidth > width;
  2867. if (!tooLong || words.length === 1) { // new line needed
  2868. words = rest;
  2869. rest = [];
  2870. if (words.length) {
  2871. tspan = doc.createElementNS(SVG_NS, 'tspan');
  2872. attr(tspan, {
  2873. dy: textLineHeight || 16,
  2874. x: parentX
  2875. });
  2876. if (spanStyle) { // #390
  2877. attr(tspan, 'style', spanStyle);
  2878. }
  2879. textNode.appendChild(tspan);
  2880. if (actualWidth > width) { // a single word is pressing it out
  2881. width = actualWidth;
  2882. }
  2883. }
  2884. } else { // append to existing line tspan
  2885. tspan.removeChild(tspan.firstChild);
  2886. rest.unshift(words.pop());
  2887. }
  2888. if (words.length) {
  2889. tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-')));
  2890. }
  2891. }
  2892. }
  2893. }
  2894. });
  2895. });
  2896. },
  2897. /**
  2898. * Create a button with preset states
  2899. * @param {String} text
  2900. * @param {Number} x
  2901. * @param {Number} y
  2902. * @param {Function} callback
  2903. * @param {Object} normalState
  2904. * @param {Object} hoverState
  2905. * @param {Object} pressedState
  2906. */
  2907. button: function (text, x, y, callback, normalState, hoverState, pressedState) {
  2908. var label = this.label(text, x, y, null, null, null, null, null, 'button'),
  2909. curState = 0,
  2910. stateOptions,
  2911. stateStyle,
  2912. normalStyle,
  2913. hoverStyle,
  2914. pressedStyle,
  2915. STYLE = 'style',
  2916. verticalGradient = { x1: 0, y1: 0, x2: 0, y2: 1 };
  2917. // Normal state - prepare the attributes
  2918. normalState = merge({
  2919. 'stroke-width': 1,
  2920. stroke: '#CCCCCC',
  2921. fill: {
  2922. linearGradient: verticalGradient,
  2923. stops: [
  2924. [0, '#FEFEFE'],
  2925. [1, '#F6F6F6']
  2926. ]
  2927. },
  2928. r: 2,
  2929. padding: 5,
  2930. style: {
  2931. color: 'black'
  2932. }
  2933. }, normalState);
  2934. normalStyle = normalState[STYLE];
  2935. delete normalState[STYLE];
  2936. // Hover state
  2937. hoverState = merge(normalState, {
  2938. stroke: '#68A',
  2939. fill: {
  2940. linearGradient: verticalGradient,
  2941. stops: [
  2942. [0, '#FFF'],
  2943. [1, '#ACF']
  2944. ]
  2945. }
  2946. }, hoverState);
  2947. hoverStyle = hoverState[STYLE];
  2948. delete hoverState[STYLE];
  2949. // Pressed state
  2950. pressedState = merge(normalState, {
  2951. stroke: '#68A',
  2952. fill: {
  2953. linearGradient: verticalGradient,
  2954. stops: [
  2955. [0, '#9BD'],
  2956. [1, '#CDF']
  2957. ]
  2958. }
  2959. }, pressedState);
  2960. pressedStyle = pressedState[STYLE];
  2961. delete pressedState[STYLE];
  2962. // add the events
  2963. addEvent(label.element, 'mouseenter', function () {
  2964. label.attr(hoverState)
  2965. .css(hoverStyle);
  2966. });
  2967. addEvent(label.element, 'mouseleave', function () {
  2968. stateOptions = [normalState, hoverState, pressedState][curState];
  2969. stateStyle = [normalStyle, hoverStyle, pressedStyle][curState];
  2970. label.attr(stateOptions)
  2971. .css(stateStyle);
  2972. });
  2973. label.setState = function (state) {
  2974. curState = state;
  2975. if (!state) {
  2976. label.attr(normalState)
  2977. .css(normalStyle);
  2978. } else if (state === 2) {
  2979. label.attr(pressedState)
  2980. .css(pressedStyle);
  2981. }
  2982. };
  2983. return label
  2984. .on('click', function () {
  2985. callback.call(label);
  2986. })
  2987. .attr(normalState)
  2988. .css(extend({ cursor: 'default' }, normalStyle));
  2989. },
  2990. /**
  2991. * Make a straight line crisper by not spilling out to neighbour pixels
  2992. * @param {Array} points
  2993. * @param {Number} width
  2994. */
  2995. crispLine: function (points, width) {
  2996. // points format: [M, 0, 0, L, 100, 0]
  2997. // normalize to a crisp line
  2998. if (points[1] === points[4]) {
  2999. // Substract due to #1129. Now bottom and left axis gridlines behave the same.
  3000. points[1] = points[4] = mathRound(points[1]) - (width % 2 / 2);
  3001. }
  3002. if (points[2] === points[5]) {
  3003. points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2);
  3004. }
  3005. return points;
  3006. },
  3007. /**
  3008. * Draw a path
  3009. * @param {Array} path An SVG path in array form
  3010. */
  3011. path: function (path) {
  3012. var attr = {
  3013. fill: NONE
  3014. };
  3015. if (isArray(path)) {
  3016. attr.d = path;
  3017. } else if (isObject(path)) { // attributes
  3018. extend(attr, path);
  3019. }
  3020. return this.createElement('path').attr(attr);
  3021. },
  3022. /**
  3023. * Draw and return an SVG circle
  3024. * @param {Number} x The x position
  3025. * @param {Number} y The y position
  3026. * @param {Number} r The radius
  3027. */
  3028. circle: function (x, y, r) {
  3029. var attr = isObject(x) ?
  3030. x :
  3031. {
  3032. x: x,
  3033. y: y,
  3034. r: r
  3035. };
  3036. return this.createElement('circle').attr(attr);
  3037. },
  3038. /**
  3039. * Draw and return an arc
  3040. * @param {Number} x X position
  3041. * @param {Number} y Y position
  3042. * @param {Number} r Radius
  3043. * @param {Number} innerR Inner radius like used in donut charts
  3044. * @param {Number} start Starting angle
  3045. * @param {Number} end Ending angle
  3046. */
  3047. arc: function (x, y, r, innerR, start, end) {
  3048. // arcs are defined as symbols for the ability to set
  3049. // attributes in attr and animate
  3050. if (isObject(x)) {
  3051. y = x.y;
  3052. r = x.r;
  3053. innerR = x.innerR;
  3054. start = x.start;
  3055. end = x.end;
  3056. x = x.x;
  3057. }
  3058. return this.symbol('arc', x || 0, y || 0, r || 0, r || 0, {
  3059. innerR: innerR || 0,
  3060. start: start || 0,
  3061. end: end || 0
  3062. });
  3063. },
  3064. /**
  3065. * Draw and return a rectangle
  3066. * @param {Number} x Left position
  3067. * @param {Number} y Top position
  3068. * @param {Number} width
  3069. * @param {Number} height
  3070. * @param {Number} r Border corner radius
  3071. * @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing
  3072. */
  3073. rect: function (x, y, width, height, r, strokeWidth) {
  3074. r = isObject(x) ? x.r : r;
  3075. var wrapper = this.createElement('rect').attr({
  3076. rx: r,
  3077. ry: r,
  3078. fill: NONE
  3079. });
  3080. return wrapper.attr(
  3081. isObject(x) ?
  3082. x :
  3083. // do not crispify when an object is passed in (as in column charts)
  3084. wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0))
  3085. );
  3086. },
  3087. /**
  3088. * Resize the box and re-align all aligned elements
  3089. * @param {Object} width
  3090. * @param {Object} height
  3091. * @param {Boolean} animate
  3092. *
  3093. */
  3094. setSize: function (width, height, animate) {
  3095. var renderer = this,
  3096. alignedObjects = renderer.alignedObjects,
  3097. i = alignedObjects.length;
  3098. renderer.width = width;
  3099. renderer.height = height;
  3100. renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({
  3101. width: width,
  3102. height: height
  3103. });
  3104. while (i--) {
  3105. alignedObjects[i].align();
  3106. }
  3107. },
  3108. /**
  3109. * Create a group
  3110. * @param {String} name The group will be given a class name of 'highcharts-{name}'.
  3111. * This can be used for styling and scripting.
  3112. */
  3113. g: function (name) {
  3114. var elem = this.createElement('g');
  3115. return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem;
  3116. },
  3117. /**
  3118. * Display an image
  3119. * @param {String} src
  3120. * @param {Number} x
  3121. * @param {Number} y
  3122. * @param {Number} width
  3123. * @param {Number} height
  3124. */
  3125. image: function (src, x, y, width, height) {
  3126. var attribs = {
  3127. preserveAspectRatio: NONE
  3128. },
  3129. elemWrapper;
  3130. // optional properties
  3131. if (arguments.length > 1) {
  3132. extend(attribs, {
  3133. x: x,
  3134. y: y,
  3135. width: width,
  3136. height: height
  3137. });
  3138. }
  3139. elemWrapper = this.createElement('image').attr(attribs);
  3140. // set the href in the xlink namespace
  3141. if (elemWrapper.element.setAttributeNS) {
  3142. elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink',
  3143. 'href', src);
  3144. } else {
  3145. // could be exporting in IE
  3146. // using href throws "not supported" in ie7 and under, requries regex shim to fix later
  3147. elemWrapper.element.setAttribute('hc-svg-href', src);
  3148. }
  3149. return elemWrapper;
  3150. },
  3151. /**
  3152. * Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object.
  3153. *
  3154. * @param {Object} symbol
  3155. * @param {Object} x
  3156. * @param {Object} y
  3157. * @param {Object} radius
  3158. * @param {Object} options
  3159. */
  3160. symbol: function (symbol, x, y, width, height, options) {
  3161. var obj,
  3162. // get the symbol definition function
  3163. symbolFn = this.symbols[symbol],
  3164. // check if there's a path defined for this symbol
  3165. path = symbolFn && symbolFn(
  3166. mathRound(x),
  3167. mathRound(y),
  3168. width,
  3169. height,
  3170. options
  3171. ),
  3172. imageElement,
  3173. imageRegex = /^url\((.*?)\)$/,
  3174. imageSrc,
  3175. imageSize,
  3176. centerImage;
  3177. if (path) {
  3178. obj = this.path(path);
  3179. // expando properties for use in animate and attr
  3180. extend(obj, {
  3181. symbolName: symbol,
  3182. x: x,
  3183. y: y,
  3184. width: width,
  3185. height: height
  3186. });
  3187. if (options) {
  3188. extend(obj, options);
  3189. }
  3190. // image symbols
  3191. } else if (imageRegex.test(symbol)) {
  3192. // On image load, set the size and position
  3193. centerImage = function (img, size) {
  3194. if (img.element) { // it may be destroyed in the meantime (#1390)
  3195. img.attr({
  3196. width: size[0],
  3197. height: size[1]
  3198. });
  3199. if (!img.alignByTranslate) { // #185
  3200. img.translate(
  3201. mathRound((width - size[0]) / 2), // #1378
  3202. mathRound((height - size[1]) / 2)
  3203. );
  3204. }
  3205. }
  3206. };
  3207. imageSrc = symbol.match(imageRegex)[1];
  3208. imageSize = symbolSizes[imageSrc];
  3209. // Ireate the image synchronously, add attribs async
  3210. obj = this.image(imageSrc)
  3211. .attr({
  3212. x: x,
  3213. y: y
  3214. });
  3215. obj.isImg = true;
  3216. if (imageSize) {
  3217. centerImage(obj, imageSize);
  3218. } else {
  3219. // Initialize image to be 0 size so export will still function if there's no cached sizes.
  3220. //
  3221. obj.attr({ width: 0, height: 0 });
  3222. // Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8,
  3223. // the created element must be assigned to a variable in order to load (#292).
  3224. imageElement = createElement('img', {
  3225. onload: function () {
  3226. centerImage(obj, symbolSizes[imageSrc] = [this.width, this.height]);
  3227. },
  3228. src: imageSrc
  3229. });
  3230. }
  3231. }
  3232. return obj;
  3233. },
  3234. /**
  3235. * An extendable collection of functions for defining symbol paths.
  3236. */
  3237. symbols: {
  3238. 'circle': function (x, y, w, h) {
  3239. var cpw = 0.166 * w;
  3240. return [
  3241. M, x + w / 2, y,
  3242. 'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h,
  3243. 'C', x - cpw, y + h, x - cpw, y, x + w / 2, y,
  3244. 'Z'
  3245. ];
  3246. },
  3247. 'square': function (x, y, w, h) {
  3248. return [
  3249. M, x, y,
  3250. L, x + w, y,
  3251. x + w, y + h,
  3252. x, y + h,
  3253. 'Z'
  3254. ];
  3255. },
  3256. 'triangle': function (x, y, w, h) {
  3257. return [
  3258. M, x + w / 2, y,
  3259. L, x + w, y + h,
  3260. x, y + h,
  3261. 'Z'
  3262. ];
  3263. },
  3264. 'triangle-down': function (x, y, w, h) {
  3265. return [
  3266. M, x, y,
  3267. L, x + w, y,
  3268. x + w / 2, y + h,
  3269. 'Z'
  3270. ];
  3271. },
  3272. 'diamond': function (x, y, w, h) {
  3273. return [
  3274. M, x + w / 2, y,
  3275. L, x + w, y + h / 2,
  3276. x + w / 2, y + h,
  3277. x, y + h / 2,
  3278. 'Z'
  3279. ];
  3280. },
  3281. 'arc': function (x, y, w, h, options) {
  3282. var start = options.start,
  3283. radius = options.r || w || h,
  3284. end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561)
  3285. innerRadius = options.innerR,
  3286. open = options.open,
  3287. cosStart = mathCos(start),
  3288. sinStart = mathSin(start),
  3289. cosEnd = mathCos(end),
  3290. sinEnd = mathSin(end),
  3291. longArc = options.end - start < mathPI ? 0 : 1;
  3292. return [
  3293. M,
  3294. x + radius * cosStart,
  3295. y + radius * sinStart,
  3296. 'A', // arcTo
  3297. radius, // x radius
  3298. radius, // y radius
  3299. 0, // slanting
  3300. longArc, // long or short arc
  3301. 1, // clockwise
  3302. x + radius * cosEnd,
  3303. y + radius * sinEnd,
  3304. open ? M : L,
  3305. x + innerRadius * cosEnd,
  3306. y + innerRadius * sinEnd,
  3307. 'A', // arcTo
  3308. innerRadius, // x radius
  3309. innerRadius, // y radius
  3310. 0, // slanting
  3311. longArc, // long or short arc
  3312. 0, // clockwise
  3313. x + innerRadius * cosStart,
  3314. y + innerRadius * sinStart,
  3315. open ? '' : 'Z' // close
  3316. ];
  3317. }
  3318. },
  3319. /**
  3320. * Define a clipping rectangle
  3321. * @param {String} id
  3322. * @param {Number} x
  3323. * @param {Number} y
  3324. * @param {Number} width
  3325. * @param {Number} height
  3326. */
  3327. clipRect: function (x, y, width, height) {
  3328. var wrapper,
  3329. id = PREFIX + idCounter++,
  3330. clipPath = this.createElement('clipPath').attr({
  3331. id: id
  3332. }).add(this.defs);
  3333. wrapper = this.rect(x, y, width, height, 0).add(clipPath);
  3334. wrapper.id = id;
  3335. wrapper.clipPath = clipPath;
  3336. return wrapper;
  3337. },
  3338. /**
  3339. * Take a color and return it if it's a string, make it a gradient if it's a
  3340. * gradient configuration object. Prior to Highstock, an array was used to define
  3341. * a linear gradient with pixel positions relative to the SVG. In newer versions
  3342. * we change the coordinates to apply relative to the shape, using coordinates
  3343. * 0-1 within the shape. To preserve backwards compatibility, linearGradient
  3344. * in this definition is an object of x1, y1, x2 and y2.
  3345. *
  3346. * @param {Object} color The color or config object
  3347. */
  3348. color: function (color, elem, prop) {
  3349. var renderer = this,
  3350. colorObject,
  3351. regexRgba = /^rgba/,
  3352. gradName,
  3353. gradAttr,
  3354. gradients,
  3355. gradientObject,
  3356. stops,
  3357. stopColor,
  3358. stopOpacity,
  3359. radialReference,
  3360. n,
  3361. id,
  3362. key = [];
  3363. // Apply linear or radial gradients
  3364. if (color && color.linearGradient) {
  3365. gradName = 'linearGradient';
  3366. } else if (color && color.radialGradient) {
  3367. gradName = 'radialGradient';
  3368. }
  3369. if (gradName) {
  3370. gradAttr = color[gradName];
  3371. gradients = renderer.gradients;
  3372. stops = color.stops;
  3373. radialReference = elem.radialReference;
  3374. // Keep < 2.2 kompatibility
  3375. if (isArray(gradAttr)) {
  3376. color[gradName] = gradAttr = {
  3377. x1: gradAttr[0],
  3378. y1: gradAttr[1],
  3379. x2: gradAttr[2],
  3380. y2: gradAttr[3],
  3381. gradientUnits: 'userSpaceOnUse'
  3382. };
  3383. }
  3384. // Correct the radial gradient for the radial reference system
  3385. if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) {
  3386. gradAttr = merge(gradAttr, {
  3387. cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2],
  3388. cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2],
  3389. r: gradAttr.r * radialReference[2],
  3390. gradientUnits: 'userSpaceOnUse'
  3391. });
  3392. }
  3393. // Build the unique key to detect whether we need to create a new element (#1282)
  3394. for (n in gradAttr) {
  3395. if (n !== 'id') {
  3396. key.push(n, gradAttr[n]);
  3397. }
  3398. }
  3399. for (n in stops) {
  3400. key.push(stops[n]);
  3401. }
  3402. key = key.join(',');
  3403. // Check if a gradient object with the same config object is created within this renderer
  3404. if (gradients[key]) {
  3405. id = gradients[key].id;
  3406. } else {
  3407. // Set the id and create the element
  3408. gradAttr.id = id = PREFIX + idCounter++;
  3409. gradients[key] = gradientObject = renderer.createElement(gradName)
  3410. .attr(gradAttr)
  3411. .add(renderer.defs);
  3412. // The gradient needs to keep a list of stops to be able to destroy them
  3413. gradientObject.stops = [];
  3414. each(stops, function (stop) {
  3415. var stopObject;
  3416. if (regexRgba.test(stop[1])) {
  3417. colorObject = Color(stop[1]);
  3418. stopColor = colorObject.get('rgb');
  3419. stopOpacity = colorObject.get('a');
  3420. } else {
  3421. stopColor = stop[1];
  3422. stopOpacity = 1;
  3423. }
  3424. stopObject = renderer.createElement('stop').attr({
  3425. offset: stop[0],
  3426. 'stop-color': stopColor,
  3427. 'stop-opacity': stopOpacity
  3428. }).add(gradientObject);
  3429. // Add the stop element to the gradient
  3430. gradientObject.stops.push(stopObject);
  3431. });
  3432. }
  3433. // Return the reference to the gradient object
  3434. return 'url(' + renderer.url + '#' + id + ')';
  3435. // Webkit and Batik can't show rgba.
  3436. } else if (regexRgba.test(color)) {
  3437. colorObject = Color(color);
  3438. attr(elem, prop + '-opacity', colorObject.get('a'));
  3439. return colorObject.get('rgb');
  3440. } else {
  3441. // Remove the opacity attribute added above. Does not throw if the attribute is not there.
  3442. elem.removeAttribute(prop + '-opacity');
  3443. return color;
  3444. }
  3445. },
  3446. /**
  3447. * Add text to the SVG object
  3448. * @param {String} str
  3449. * @param {Number} x Left position
  3450. * @param {Number} y Top position
  3451. * @param {Boolean} useHTML Use HTML to render the text
  3452. */
  3453. text: function (str, x, y, useHTML) {
  3454. // declare variables
  3455. var renderer = this,
  3456. defaultChartStyle = defaultOptions.chart.style,
  3457. fakeSVG = useCanVG || (!hasSVG && renderer.forExport),
  3458. wrapper;
  3459. if (useHTML && !renderer.forExport) {
  3460. return renderer.html(str, x, y);
  3461. }
  3462. x = mathRound(pick(x, 0));
  3463. y = mathRound(pick(y, 0));
  3464. wrapper = renderer.createElement('text')
  3465. .attr({
  3466. x: x,
  3467. y: y,
  3468. text: str
  3469. })
  3470. .css({
  3471. fontFamily: defaultChartStyle.fontFamily,
  3472. fontSize: defaultChartStyle.fontSize
  3473. });
  3474. // Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063)
  3475. if (fakeSVG) {
  3476. wrapper.css({
  3477. position: ABSOLUTE
  3478. });
  3479. }
  3480. wrapper.x = x;
  3481. wrapper.y = y;
  3482. return wrapper;
  3483. },
  3484. /**
  3485. * Create HTML text node. This is used by the VML renderer as well as the SVG
  3486. * renderer through the useHTML option.
  3487. *
  3488. * @param {String} str
  3489. * @param {Number} x
  3490. * @param {Number} y
  3491. */
  3492. html: function (str, x, y) {
  3493. var defaultChartStyle = defaultOptions.chart.style,
  3494. wrapper = this.createElement('span'),
  3495. attrSetters = wrapper.attrSetters,
  3496. element = wrapper.element,
  3497. renderer = wrapper.renderer;
  3498. // Text setter
  3499. attrSetters.text = function (value) {
  3500. if (value !== element.innerHTML) {
  3501. delete this.bBox;
  3502. }
  3503. element.innerHTML = value;
  3504. return false;
  3505. };
  3506. // Various setters which rely on update transform
  3507. attrSetters.x = attrSetters.y = attrSetters.align = function (value, key) {
  3508. if (key === 'align') {
  3509. key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML.
  3510. }
  3511. wrapper[key] = value;
  3512. wrapper.htmlUpdateTransform();
  3513. return false;
  3514. };
  3515. // Set the default attributes
  3516. wrapper.attr({
  3517. text: str,
  3518. x: mathRound(x),
  3519. y: mathRound(y)
  3520. })
  3521. .css({
  3522. position: ABSOLUTE,
  3523. whiteSpace: 'nowrap',
  3524. fontFamily: defaultChartStyle.fontFamily,
  3525. fontSize: defaultChartStyle.fontSize
  3526. });
  3527. // Use the HTML specific .css method
  3528. wrapper.css = wrapper.htmlCss;
  3529. // This is specific for HTML within SVG
  3530. if (renderer.isSVG) {
  3531. wrapper.add = function (svgGroupWrapper) {
  3532. var htmlGroup,
  3533. container = renderer.box.parentNode,
  3534. parentGroup,
  3535. parents = [];
  3536. // Create a mock group to hold the HTML elements
  3537. if (svgGroupWrapper) {
  3538. htmlGroup = svgGroupWrapper.div;
  3539. if (!htmlGroup) {
  3540. // Read the parent chain into an array and read from top down
  3541. parentGroup = svgGroupWrapper;
  3542. while (parentGroup) {
  3543. parents.push(parentGroup);
  3544. // Move up to the next parent group
  3545. parentGroup = parentGroup.parentGroup;
  3546. }
  3547. // Ensure dynamically updating position when any parent is translated
  3548. each(parents.reverse(), function (parentGroup) {
  3549. var htmlGroupStyle;
  3550. // Create a HTML div and append it to the parent div to emulate
  3551. // the SVG group structure
  3552. htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, {
  3553. className: attr(parentGroup.element, 'class')
  3554. }, {
  3555. position: ABSOLUTE,
  3556. left: (parentGroup.translateX || 0) + PX,
  3557. top: (parentGroup.translateY || 0) + PX
  3558. }, htmlGroup || container); // the top group is appended to container
  3559. // Shortcut
  3560. htmlGroupStyle = htmlGroup.style;
  3561. // Set listeners to update the HTML div's position whenever the SVG group
  3562. // position is changed
  3563. extend(parentGroup.attrSetters, {
  3564. translateX: function (value) {
  3565. htmlGroupStyle.left = value + PX;
  3566. },
  3567. translateY: function (value) {
  3568. htmlGroupStyle.top = value + PX;
  3569. },
  3570. visibility: function (value, key) {
  3571. htmlGroupStyle[key] = value;
  3572. }
  3573. });
  3574. });
  3575. }
  3576. } else {
  3577. htmlGroup = container;
  3578. }
  3579. htmlGroup.appendChild(element);
  3580. // Shared with VML:
  3581. wrapper.added = true;
  3582. if (wrapper.alignOnAdd) {
  3583. wrapper.htmlUpdateTransform();
  3584. }
  3585. return wrapper;
  3586. };
  3587. }
  3588. return wrapper;
  3589. },
  3590. /**
  3591. * Utility to return the baseline offset and total line height from the font size
  3592. */
  3593. fontMetrics: function (fontSize) {
  3594. fontSize = pInt(fontSize || 11);
  3595. // Empirical values found by comparing font size and bounding box height.
  3596. // Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/
  3597. var lineHeight = fontSize < 24 ? fontSize + 4 : mathRound(fontSize * 1.2),
  3598. baseline = mathRound(lineHeight * 0.8);
  3599. return {
  3600. h: lineHeight,
  3601. b: baseline
  3602. };
  3603. },
  3604. /**
  3605. * Add a label, a text item that can hold a colored or gradient background
  3606. * as well as a border and shadow.
  3607. * @param {string} str
  3608. * @param {Number} x
  3609. * @param {Number} y
  3610. * @param {String} shape
  3611. * @param {Number} anchorX In case the shape has a pointer, like a flag, this is the
  3612. * coordinates it should be pinned to
  3613. * @param {Number} anchorY
  3614. * @param {Boolean} baseline Whether to position the label relative to the text baseline,
  3615. * like renderer.text, or to the upper border of the rectangle.
  3616. * @param {String} className Class name for the group
  3617. */
  3618. label: function (str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) {
  3619. var renderer = this,
  3620. wrapper = renderer.g(className),
  3621. text = renderer.text('', 0, 0, useHTML)
  3622. .attr({
  3623. zIndex: 1
  3624. }),
  3625. //.add(wrapper),
  3626. box,
  3627. bBox,
  3628. alignFactor = 0,
  3629. padding = 3,
  3630. paddingLeft = 0,
  3631. width,
  3632. height,
  3633. wrapperX,
  3634. wrapperY,
  3635. crispAdjust = 0,
  3636. deferredAttr = {},
  3637. baselineOffset,
  3638. attrSetters = wrapper.attrSetters,
  3639. needsBox;
  3640. /**
  3641. * This function runs after the label is added to the DOM (when the bounding box is
  3642. * available), and after the text of the label is updated to detect the new bounding
  3643. * box and reflect it in the border box.
  3644. */
  3645. function updateBoxSize() {
  3646. var boxX,
  3647. boxY,
  3648. style = text.element.style;
  3649. bBox = (width === undefined || height === undefined || wrapper.styles.textAlign) &&
  3650. text.getBBox();
  3651. wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft;
  3652. wrapper.height = (height || bBox.height || 0) + 2 * padding;
  3653. // update the label-scoped y offset
  3654. baselineOffset = padding + renderer.fontMetrics(style && style.fontSize).b;
  3655. if (needsBox) {
  3656. // create the border box if it is not already present
  3657. if (!box) {
  3658. boxX = mathRound(-alignFactor * padding);
  3659. boxY = baseline ? -baselineOffset : 0;
  3660. wrapper.box = box = shape ?
  3661. renderer.symbol(shape, boxX, boxY, wrapper.width, wrapper.height) :
  3662. renderer.rect(boxX, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]);
  3663. box.add(wrapper);
  3664. }
  3665. // apply the box attributes
  3666. if (!box.isImg) { // #1630
  3667. box.attr(merge({
  3668. width: wrapper.width,
  3669. height: wrapper.height
  3670. }, deferredAttr));
  3671. }
  3672. deferredAttr = null;
  3673. }
  3674. }
  3675. /**
  3676. * This function runs after setting text or padding, but only if padding is changed
  3677. */
  3678. function updateTextPadding() {
  3679. var styles = wrapper.styles,
  3680. textAlign = styles && styles.textAlign,
  3681. x = paddingLeft + padding * (1 - alignFactor),
  3682. y;
  3683. // determin y based on the baseline
  3684. y = baseline ? 0 : baselineOffset;
  3685. // compensate for alignment
  3686. if (defined(width) && (textAlign === 'center' || textAlign === 'right')) {
  3687. x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width);
  3688. }
  3689. // update if anything changed
  3690. if (x !== text.x || y !== text.y) {
  3691. text.attr({
  3692. x: x,
  3693. y: y
  3694. });
  3695. }
  3696. // record current values
  3697. text.x = x;
  3698. text.y = y;
  3699. }
  3700. /**
  3701. * Set a box attribute, or defer it if the box is not yet created
  3702. * @param {Object} key
  3703. * @param {Object} value
  3704. */
  3705. function boxAttr(key, value) {
  3706. if (box) {
  3707. box.attr(key, value);
  3708. } else {
  3709. deferredAttr[key] = value;
  3710. }
  3711. }
  3712. function getSizeAfterAdd() {
  3713. text.add(wrapper);
  3714. wrapper.attr({
  3715. text: str, // alignment is available now
  3716. x: x,
  3717. y: y
  3718. });
  3719. if (box && defined(anchorX)) {
  3720. wrapper.attr({
  3721. anchorX: anchorX,
  3722. anchorY: anchorY
  3723. });
  3724. }
  3725. }
  3726. /**
  3727. * After the text element is added, get the desired size of the border box
  3728. * and add it before the text in the DOM.
  3729. */
  3730. addEvent(wrapper, 'add', getSizeAfterAdd);
  3731. /*
  3732. * Add specific attribute setters.
  3733. */
  3734. // only change local variables
  3735. attrSetters.width = function (value) {
  3736. width = value;
  3737. return false;
  3738. };
  3739. attrSetters.height = function (value) {
  3740. height = value;
  3741. return false;
  3742. };
  3743. attrSetters.padding = function (value) {
  3744. if (defined(value) && value !== padding) {
  3745. padding = value;
  3746. updateTextPadding();
  3747. }
  3748. return false;
  3749. };
  3750. attrSetters.paddingLeft = function (value) {
  3751. if (defined(value) && value !== paddingLeft) {
  3752. paddingLeft = value;
  3753. updateTextPadding();
  3754. }
  3755. return false;
  3756. };
  3757. // change local variable and set attribue as well
  3758. attrSetters.align = function (value) {
  3759. alignFactor = { left: 0, center: 0.5, right: 1 }[value];
  3760. return false; // prevent setting text-anchor on the group
  3761. };
  3762. // apply these to the box and the text alike
  3763. attrSetters.text = function (value, key) {
  3764. text.attr(key, value);
  3765. updateBoxSize();
  3766. updateTextPadding();
  3767. return false;
  3768. };
  3769. // apply these to the box but not to the text
  3770. attrSetters[STROKE_WIDTH] = function (value, key) {
  3771. needsBox = true;
  3772. crispAdjust = value % 2 / 2;
  3773. boxAttr(key, value);
  3774. return false;
  3775. };
  3776. attrSetters.stroke = attrSetters.fill = attrSetters.r = function (value, key) {
  3777. if (key === 'fill') {
  3778. needsBox = true;
  3779. }
  3780. boxAttr(key, value);
  3781. return false;
  3782. };
  3783. attrSetters.anchorX = function (value, key) {
  3784. anchorX = value;
  3785. boxAttr(key, value + crispAdjust - wrapperX);
  3786. return false;
  3787. };
  3788. attrSetters.anchorY = function (value, key) {
  3789. anchorY = value;
  3790. boxAttr(key, value - wrapperY);
  3791. return false;
  3792. };
  3793. // rename attributes
  3794. attrSetters.x = function (value) {
  3795. wrapper.x = value; // for animation getter
  3796. value -= alignFactor * ((width || bBox.width) + padding);
  3797. wrapperX = mathRound(value);
  3798. wrapper.attr('translateX', wrapperX);
  3799. return false;
  3800. };
  3801. attrSetters.y = function (value) {
  3802. wrapperY = wrapper.y = mathRound(value);
  3803. wrapper.attr('translateY', wrapperY);
  3804. return false;
  3805. };
  3806. // Redirect certain methods to either the box or the text
  3807. var baseCss = wrapper.css;
  3808. return extend(wrapper, {
  3809. /**
  3810. * Pick up some properties and apply them to the text instead of the wrapper
  3811. */
  3812. css: function (styles) {
  3813. if (styles) {
  3814. var textStyles = {};
  3815. styles = merge(styles); // create a copy to avoid altering the original object (#537)
  3816. each(['fontSize', 'fontWeight', 'fontFamily', 'color', 'lineHeight', 'width'], function (prop) {
  3817. if (styles[prop] !== UNDEFINED) {
  3818. textStyles[prop] = styles[prop];
  3819. delete styles[prop];
  3820. }
  3821. });
  3822. text.css(textStyles);
  3823. }
  3824. return baseCss.call(wrapper, styles);
  3825. },
  3826. /**
  3827. * Return the bounding box of the box, not the group
  3828. */
  3829. getBBox: function () {
  3830. return {
  3831. width: bBox.width + 2 * padding,
  3832. height: bBox.height + 2 * padding,
  3833. x: bBox.x - padding,
  3834. y: bBox.y - padding
  3835. };
  3836. },
  3837. /**
  3838. * Apply the shadow to the box
  3839. */
  3840. shadow: function (b) {
  3841. if (box) {
  3842. box.shadow(b);
  3843. }
  3844. return wrapper;
  3845. },
  3846. /**
  3847. * Destroy and release memory.
  3848. */
  3849. destroy: function () {
  3850. removeEvent(wrapper, 'add', getSizeAfterAdd);
  3851. // Added by button implementation
  3852. removeEvent(wrapper.element, 'mouseenter');
  3853. removeEvent(wrapper.element, 'mouseleave');
  3854. if (text) {
  3855. text = text.destroy();
  3856. }
  3857. if (box) {
  3858. box = box.destroy();
  3859. }
  3860. // Call base implementation to destroy the rest
  3861. SVGElement.prototype.destroy.call(wrapper);
  3862. // Release local pointers (#1298)
  3863. wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = getSizeAfterAdd = null;
  3864. }
  3865. });
  3866. }
  3867. }; // end SVGRenderer
  3868. // general renderer
  3869. Renderer = SVGRenderer;
  3870. /* ****************************************************************************
  3871. * *
  3872. * START OF INTERNET EXPLORER <= 8 SPECIFIC CODE *
  3873. * *
  3874. * For applications and websites that don't need IE support, like platform *
  3875. * targeted mobile apps and web apps, this code can be removed. *
  3876. * *
  3877. *****************************************************************************/
  3878. /**
  3879. * @constructor
  3880. */
  3881. var VMLRenderer, VMLElement;
  3882. if (!hasSVG && !useCanVG) {
  3883. /**
  3884. * The VML element wrapper.
  3885. */
  3886. Highcharts.VMLElement = VMLElement = {
  3887. /**
  3888. * Initialize a new VML element wrapper. It builds the markup as a string
  3889. * to minimize DOM traffic.
  3890. * @param {Object} renderer
  3891. * @param {Object} nodeName
  3892. */
  3893. init: function (renderer, nodeName) {
  3894. var wrapper = this,
  3895. markup = ['<', nodeName, ' filled="f" stroked="f"'],
  3896. style = ['position: ', ABSOLUTE, ';'],
  3897. isDiv = nodeName === DIV;
  3898. // divs and shapes need size
  3899. if (nodeName === 'shape' || isDiv) {
  3900. style.push('left:0;top:0;width:1px;height:1px;');
  3901. }
  3902. style.push('visibility: ', isDiv ? HIDDEN : VISIBLE);
  3903. markup.push(' style="', style.join(''), '"/>');
  3904. // create element with default attributes and style
  3905. if (nodeName) {
  3906. markup = isDiv || nodeName === 'span' || nodeName === 'img' ?
  3907. markup.join('')
  3908. : renderer.prepVML(markup);
  3909. wrapper.element = createElement(markup);
  3910. }
  3911. wrapper.renderer = renderer;
  3912. wrapper.attrSetters = {};
  3913. },
  3914. /**
  3915. * Add the node to the given parent
  3916. * @param {Object} parent
  3917. */
  3918. add: function (parent) {
  3919. var wrapper = this,
  3920. renderer = wrapper.renderer,
  3921. element = wrapper.element,
  3922. box = renderer.box,
  3923. inverted = parent && parent.inverted,
  3924. // get the parent node
  3925. parentNode = parent ?
  3926. parent.element || parent :
  3927. box;
  3928. // if the parent group is inverted, apply inversion on all children
  3929. if (inverted) { // only on groups
  3930. renderer.invertChild(element, parentNode);
  3931. }
  3932. // append it
  3933. parentNode.appendChild(element);
  3934. // align text after adding to be able to read offset
  3935. wrapper.added = true;
  3936. if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) {
  3937. wrapper.updateTransform();
  3938. }
  3939. // fire an event for internal hooks
  3940. fireEvent(wrapper, 'add');
  3941. return wrapper;
  3942. },
  3943. /**
  3944. * VML always uses htmlUpdateTransform
  3945. */
  3946. updateTransform: SVGElement.prototype.htmlUpdateTransform,
  3947. /**
  3948. * Get or set attributes
  3949. */
  3950. attr: function (hash, val) {
  3951. var wrapper = this,
  3952. key,
  3953. value,
  3954. i,
  3955. result,
  3956. element = wrapper.element || {},
  3957. elemStyle = element.style,
  3958. nodeName = element.nodeName,
  3959. renderer = wrapper.renderer,
  3960. symbolName = wrapper.symbolName,
  3961. hasSetSymbolSize,
  3962. shadows = wrapper.shadows,
  3963. skipAttr,
  3964. attrSetters = wrapper.attrSetters,
  3965. ret = wrapper;
  3966. // single key-value pair
  3967. if (isString(hash) && defined(val)) {
  3968. key = hash;
  3969. hash = {};
  3970. hash[key] = val;
  3971. }
  3972. // used as a getter, val is undefined
  3973. if (isString(hash)) {
  3974. key = hash;
  3975. if (key === 'strokeWidth' || key === 'stroke-width') {
  3976. ret = wrapper.strokeweight;
  3977. } else {
  3978. ret = wrapper[key];
  3979. }
  3980. // setter
  3981. } else {
  3982. for (key in hash) {
  3983. value = hash[key];
  3984. skipAttr = false;
  3985. // check for a specific attribute setter
  3986. result = attrSetters[key] && attrSetters[key].call(wrapper, value, key);
  3987. if (result !== false && value !== null) { // #620
  3988. if (result !== UNDEFINED) {
  3989. value = result; // the attribute setter has returned a new value to set
  3990. }
  3991. // prepare paths
  3992. // symbols
  3993. if (symbolName && /^(x|y|r|start|end|width|height|innerR|anchorX|anchorY)/.test(key)) {
  3994. // if one of the symbol size affecting parameters are changed,
  3995. // check all the others only once for each call to an element's
  3996. // .attr() method
  3997. if (!hasSetSymbolSize) {
  3998. wrapper.symbolAttr(hash);
  3999. hasSetSymbolSize = true;
  4000. }
  4001. skipAttr = true;
  4002. } else if (key === 'd') {
  4003. value = value || [];
  4004. wrapper.d = value.join(' '); // used in getter for animation
  4005. // convert paths
  4006. i = value.length;
  4007. var convertedPath = [],
  4008. clockwise;
  4009. while (i--) {
  4010. // Multiply by 10 to allow subpixel precision.
  4011. // Substracting half a pixel seems to make the coordinates
  4012. // align with SVG, but this hasn't been tested thoroughly
  4013. if (isNumber(value[i])) {
  4014. convertedPath[i] = mathRound(value[i] * 10) - 5;
  4015. } else if (value[i] === 'Z') { // close the path
  4016. convertedPath[i] = 'x';
  4017. } else {
  4018. convertedPath[i] = value[i];
  4019. // When the start X and end X coordinates of an arc are too close,
  4020. // they are rounded to the same value above. In this case, substract 1 from the end X
  4021. // position. #760, #1371.
  4022. if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) {
  4023. clockwise = value[i] === 'wa' ? 1 : -1; // #1642
  4024. if (convertedPath[i + 5] === convertedPath[i + 7]) {
  4025. convertedPath[i + 7] -= clockwise;
  4026. }
  4027. // Start and end Y (#1410)
  4028. if (convertedPath[i + 6] === convertedPath[i + 8]) {
  4029. convertedPath[i + 8] -= clockwise;
  4030. }
  4031. }
  4032. }
  4033. }
  4034. value = convertedPath.join(' ') || 'x';
  4035. element.path = value;
  4036. // update shadows
  4037. if (shadows) {
  4038. i = shadows.length;
  4039. while (i--) {
  4040. shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value;
  4041. }
  4042. }
  4043. skipAttr = true;
  4044. // handle visibility
  4045. } else if (key === 'visibility') {
  4046. // let the shadow follow the main element
  4047. if (shadows) {
  4048. i = shadows.length;
  4049. while (i--) {
  4050. shadows[i].style[key] = value;
  4051. }
  4052. }
  4053. // Instead of toggling the visibility CSS property, move the div out of the viewport.
  4054. // This works around #61 and #586
  4055. if (nodeName === 'DIV') {
  4056. value = value === HIDDEN ? '-999em' : 0;
  4057. // In order to redraw, IE7 needs the div to be visible when tucked away
  4058. // outside the viewport. So the visibility is actually opposite of
  4059. // the expected value. This applies to the tooltip only.
  4060. if (!docMode8) {
  4061. elemStyle[key] = value ? VISIBLE : HIDDEN;
  4062. }
  4063. key = 'top';
  4064. }
  4065. elemStyle[key] = value;
  4066. skipAttr = true;
  4067. // directly mapped to css
  4068. } else if (key === 'zIndex') {
  4069. if (value) {
  4070. elemStyle[key] = value;
  4071. }
  4072. skipAttr = true;
  4073. // x, y, width, height
  4074. } else if (inArray(key, ['x', 'y', 'width', 'height']) !== -1) {
  4075. wrapper[key] = value; // used in getter
  4076. if (key === 'x' || key === 'y') {
  4077. key = { x: 'left', y: 'top' }[key];
  4078. } else {
  4079. value = mathMax(0, value); // don't set width or height below zero (#311)
  4080. }
  4081. // clipping rectangle special
  4082. if (wrapper.updateClipping) {
  4083. wrapper[key] = value; // the key is now 'left' or 'top' for 'x' and 'y'
  4084. wrapper.updateClipping();
  4085. } else {
  4086. // normal
  4087. elemStyle[key] = value;
  4088. }
  4089. skipAttr = true;
  4090. // class name
  4091. } else if (key === 'class' && nodeName === 'DIV') {
  4092. // IE8 Standards mode has problems retrieving the className
  4093. element.className = value;
  4094. // stroke
  4095. } else if (key === 'stroke') {
  4096. value = renderer.color(value, element, key);
  4097. key = 'strokecolor';
  4098. // stroke width
  4099. } else if (key === 'stroke-width' || key === 'strokeWidth') {
  4100. element.stroked = value ? true : false;
  4101. key = 'strokeweight';
  4102. wrapper[key] = value; // used in getter, issue #113
  4103. if (isNumber(value)) {
  4104. value += PX;
  4105. }
  4106. // dashStyle
  4107. } else if (key === 'dashstyle') {
  4108. var strokeElem = element.getElementsByTagName('stroke')[0] ||
  4109. createElement(renderer.prepVML(['<stroke/>']), null, null, element);
  4110. strokeElem[key] = value || 'solid';
  4111. wrapper.dashstyle = value; /* because changing stroke-width will change the dash length
  4112. and cause an epileptic effect */
  4113. skipAttr = true;
  4114. // fill
  4115. } else if (key === 'fill') {
  4116. if (nodeName === 'SPAN') { // text color
  4117. elemStyle.color = value;
  4118. } else if (nodeName !== 'IMG') { // #1336
  4119. element.filled = value !== NONE ? true : false;
  4120. value = renderer.color(value, element, key, wrapper);
  4121. key = 'fillcolor';
  4122. }
  4123. // opacity: don't bother - animation is too slow and filters introduce artifacts
  4124. } else if (key === 'opacity') {
  4125. /*css(element, {
  4126. opacity: value
  4127. });*/
  4128. skipAttr = true;
  4129. // rotation on VML elements
  4130. } else if (nodeName === 'shape' && key === 'rotation') {
  4131. wrapper[key] = value;
  4132. // Correction for the 1x1 size of the shape container. Used in gauge needles.
  4133. element.style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX;
  4134. element.style.top = mathRound(mathCos(value * deg2rad)) + PX;
  4135. // translation for animation
  4136. } else if (key === 'translateX' || key === 'translateY' || key === 'rotation') {
  4137. wrapper[key] = value;
  4138. wrapper.updateTransform();
  4139. skipAttr = true;
  4140. // text for rotated and non-rotated elements
  4141. } else if (key === 'text') {
  4142. this.bBox = null;
  4143. element.innerHTML = value;
  4144. skipAttr = true;
  4145. }
  4146. if (!skipAttr) {
  4147. if (docMode8) { // IE8 setAttribute bug
  4148. element[key] = value;
  4149. } else {
  4150. attr(element, key, value);
  4151. }
  4152. }
  4153. }
  4154. }
  4155. }
  4156. return ret;
  4157. },
  4158. /**
  4159. * Set the element's clipping to a predefined rectangle
  4160. *
  4161. * @param {String} id The id of the clip rectangle
  4162. */
  4163. clip: function (clipRect) {
  4164. var wrapper = this,
  4165. clipMembers,
  4166. cssRet;
  4167. if (clipRect) {
  4168. clipMembers = clipRect.members;
  4169. erase(clipMembers, wrapper); // Ensure unique list of elements (#1258)
  4170. clipMembers.push(wrapper);
  4171. wrapper.destroyClip = function () {
  4172. erase(clipMembers, wrapper);
  4173. };
  4174. cssRet = clipRect.getCSS(wrapper);
  4175. } else {
  4176. if (wrapper.destroyClip) {
  4177. wrapper.destroyClip();
  4178. }
  4179. cssRet = { clip: docMode8 ? 'inherit' : 'rect(auto)' }; // #1214
  4180. }
  4181. return wrapper.css(cssRet);
  4182. },
  4183. /**
  4184. * Set styles for the element
  4185. * @param {Object} styles
  4186. */
  4187. css: SVGElement.prototype.htmlCss,
  4188. /**
  4189. * Removes a child either by removeChild or move to garbageBin.
  4190. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not.
  4191. */
  4192. safeRemoveChild: function (element) {
  4193. // discardElement will detach the node from its parent before attaching it
  4194. // to the garbage bin. Therefore it is important that the node is attached and have parent.
  4195. if (element.parentNode) {
  4196. discardElement(element);
  4197. }
  4198. },
  4199. /**
  4200. * Extend element.destroy by removing it from the clip members array
  4201. */
  4202. destroy: function () {
  4203. if (this.destroyClip) {
  4204. this.destroyClip();
  4205. }
  4206. return SVGElement.prototype.destroy.apply(this);
  4207. },
  4208. /**
  4209. * Add an event listener. VML override for normalizing event parameters.
  4210. * @param {String} eventType
  4211. * @param {Function} handler
  4212. */
  4213. on: function (eventType, handler) {
  4214. // simplest possible event model for internal use
  4215. this.element['on' + eventType] = function () {
  4216. var evt = win.event;
  4217. evt.target = evt.srcElement;
  4218. handler(evt);
  4219. };
  4220. return this;
  4221. },
  4222. /**
  4223. * In stacked columns, cut off the shadows so that they don't overlap
  4224. */
  4225. cutOffPath: function (path, length) {
  4226. var len;
  4227. path = path.split(/[ ,]/);
  4228. len = path.length;
  4229. if (len === 9 || len === 11) {
  4230. path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length;
  4231. }
  4232. return path.join(' ');
  4233. },
  4234. /**
  4235. * Apply a drop shadow by copying elements and giving them different strokes
  4236. * @param {Boolean|Object} shadowOptions
  4237. */
  4238. shadow: function (shadowOptions, group, cutOff) {
  4239. var shadows = [],
  4240. i,
  4241. element = this.element,
  4242. renderer = this.renderer,
  4243. shadow,
  4244. elemStyle = element.style,
  4245. markup,
  4246. path = element.path,
  4247. strokeWidth,
  4248. modifiedPath,
  4249. shadowWidth,
  4250. shadowElementOpacity;
  4251. // some times empty paths are not strings
  4252. if (path && typeof path.value !== 'string') {
  4253. path = 'x';
  4254. }
  4255. modifiedPath = path;
  4256. if (shadowOptions) {
  4257. shadowWidth = pick(shadowOptions.width, 3);
  4258. shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth;
  4259. for (i = 1; i <= 3; i++) {
  4260. strokeWidth = (shadowWidth * 2) + 1 - (2 * i);
  4261. // Cut off shadows for stacked column items
  4262. if (cutOff) {
  4263. modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5);
  4264. }
  4265. markup = ['<shape isShadow="true" strokeweight="', strokeWidth,
  4266. '" filled="false" path="', modifiedPath,
  4267. '" coordsize="10 10" style="', element.style.cssText, '" />'];
  4268. shadow = createElement(renderer.prepVML(markup),
  4269. null, {
  4270. left: pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1),
  4271. top: pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1)
  4272. }
  4273. );
  4274. if (cutOff) {
  4275. shadow.cutOff = strokeWidth + 1;
  4276. }
  4277. // apply the opacity
  4278. markup = ['<stroke color="', shadowOptions.color || 'black', '" opacity="', shadowElementOpacity * i, '"/>'];
  4279. createElement(renderer.prepVML(markup), null, null, shadow);
  4280. // insert it
  4281. if (group) {
  4282. group.element.appendChild(shadow);
  4283. } else {
  4284. element.parentNode.insertBefore(shadow, element);
  4285. }
  4286. // record it
  4287. shadows.push(shadow);
  4288. }
  4289. this.shadows = shadows;
  4290. }
  4291. return this;
  4292. }
  4293. };
  4294. VMLElement = extendClass(SVGElement, VMLElement);
  4295. /**
  4296. * The VML renderer
  4297. */
  4298. var VMLRendererExtension = { // inherit SVGRenderer
  4299. Element: VMLElement,
  4300. isIE8: userAgent.indexOf('MSIE 8.0') > -1,
  4301. /**
  4302. * Initialize the VMLRenderer
  4303. * @param {Object} container
  4304. * @param {Number} width
  4305. * @param {Number} height
  4306. */
  4307. init: function (container, width, height) {
  4308. var renderer = this,
  4309. boxWrapper,
  4310. box;
  4311. renderer.alignedObjects = [];
  4312. boxWrapper = renderer.createElement(DIV);
  4313. box = boxWrapper.element;
  4314. box.style.position = RELATIVE; // for freeform drawing using renderer directly
  4315. container.appendChild(boxWrapper.element);
  4316. // generate the containing box
  4317. renderer.isVML = true;
  4318. renderer.box = box;
  4319. renderer.boxWrapper = boxWrapper;
  4320. renderer.setSize(width, height, false);
  4321. // The only way to make IE6 and IE7 print is to use a global namespace. However,
  4322. // with IE8 the only way to make the dynamic shapes visible in screen and print mode
  4323. // seems to be to add the xmlns attribute and the behaviour style inline.
  4324. if (!doc.namespaces.hcv) {
  4325. doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml');
  4326. // setup default css
  4327. doc.createStyleSheet().cssText =
  4328. 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' +
  4329. '{ behavior:url(#default#VML); display: inline-block; } ';
  4330. }
  4331. },
  4332. /**
  4333. * Detect whether the renderer is hidden. This happens when one of the parent elements
  4334. * has display: none
  4335. */
  4336. isHidden: function () {
  4337. return !this.box.offsetWidth;
  4338. },
  4339. /**
  4340. * Define a clipping rectangle. In VML it is accomplished by storing the values
  4341. * for setting the CSS style to all associated members.
  4342. *
  4343. * @param {Number} x
  4344. * @param {Number} y
  4345. * @param {Number} width
  4346. * @param {Number} height
  4347. */
  4348. clipRect: function (x, y, width, height) {
  4349. // create a dummy element
  4350. var clipRect = this.createElement(),
  4351. isObj = isObject(x);
  4352. // mimic a rectangle with its style object for automatic updating in attr
  4353. return extend(clipRect, {
  4354. members: [],
  4355. left: isObj ? x.x : x,
  4356. top: isObj ? x.y : y,
  4357. width: isObj ? x.width : width,
  4358. height: isObj ? x.height : height,
  4359. getCSS: function (wrapper) {
  4360. var element = wrapper.element,
  4361. nodeName = element.nodeName,
  4362. isShape = nodeName === 'shape',
  4363. inverted = wrapper.inverted,
  4364. rect = this,
  4365. top = rect.top - (isShape ? element.offsetTop : 0),
  4366. left = rect.left,
  4367. right = left + rect.width,
  4368. bottom = top + rect.height,
  4369. ret = {
  4370. clip: 'rect(' +
  4371. mathRound(inverted ? left : top) + 'px,' +
  4372. mathRound(inverted ? bottom : right) + 'px,' +
  4373. mathRound(inverted ? right : bottom) + 'px,' +
  4374. mathRound(inverted ? top : left) + 'px)'
  4375. };
  4376. // issue 74 workaround
  4377. if (!inverted && docMode8 && nodeName === 'DIV') {
  4378. extend(ret, {
  4379. width: right + PX,
  4380. height: bottom + PX
  4381. });
  4382. }
  4383. return ret;
  4384. },
  4385. // used in attr and animation to update the clipping of all members
  4386. updateClipping: function () {
  4387. each(clipRect.members, function (member) {
  4388. member.css(clipRect.getCSS(member));
  4389. });
  4390. }
  4391. });
  4392. },
  4393. /**
  4394. * Take a color and return it if it's a string, make it a gradient if it's a
  4395. * gradient configuration object, and apply opacity.
  4396. *
  4397. * @param {Object} color The color or config object
  4398. */
  4399. color: function (color, elem, prop, wrapper) {
  4400. var renderer = this,
  4401. colorObject,
  4402. regexRgba = /^rgba/,
  4403. markup,
  4404. fillType,
  4405. ret = NONE;
  4406. // Check for linear or radial gradient
  4407. if (color && color.linearGradient) {
  4408. fillType = 'gradient';
  4409. } else if (color && color.radialGradient) {
  4410. fillType = 'pattern';
  4411. }
  4412. if (fillType) {
  4413. var stopColor,
  4414. stopOpacity,
  4415. gradient = color.linearGradient || color.radialGradient,
  4416. x1,
  4417. y1,
  4418. x2,
  4419. y2,
  4420. opacity1,
  4421. opacity2,
  4422. color1,
  4423. color2,
  4424. fillAttr = '',
  4425. stops = color.stops,
  4426. firstStop,
  4427. lastStop,
  4428. colors = [],
  4429. addFillNode = function () {
  4430. // Add the fill subnode. When colors attribute is used, the meanings of opacity and o:opacity2
  4431. // are reversed.
  4432. markup = ['<fill colors="' + colors.join(',') + '" opacity="', opacity2, '" o:opacity2="', opacity1,
  4433. '" type="', fillType, '" ', fillAttr, 'focus="100%" method="any" />'];
  4434. createElement(renderer.prepVML(markup), null, null, elem);
  4435. };
  4436. // Extend from 0 to 1
  4437. firstStop = stops[0];
  4438. lastStop = stops[stops.length - 1];
  4439. if (firstStop[0] > 0) {
  4440. stops.unshift([
  4441. 0,
  4442. firstStop[1]
  4443. ]);
  4444. }
  4445. if (lastStop[0] < 1) {
  4446. stops.push([
  4447. 1,
  4448. lastStop[1]
  4449. ]);
  4450. }
  4451. // Compute the stops
  4452. each(stops, function (stop, i) {
  4453. if (regexRgba.test(stop[1])) {
  4454. colorObject = Color(stop[1]);
  4455. stopColor = colorObject.get('rgb');
  4456. stopOpacity = colorObject.get('a');
  4457. } else {
  4458. stopColor = stop[1];
  4459. stopOpacity = 1;
  4460. }
  4461. // Build the color attribute
  4462. colors.push((stop[0] * 100) + '% ' + stopColor);
  4463. // Only start and end opacities are allowed, so we use the first and the last
  4464. if (!i) {
  4465. opacity1 = stopOpacity;
  4466. color2 = stopColor;
  4467. } else {
  4468. opacity2 = stopOpacity;
  4469. color1 = stopColor;
  4470. }
  4471. });
  4472. // Apply the gradient to fills only.
  4473. if (prop === 'fill') {
  4474. // Handle linear gradient angle
  4475. if (fillType === 'gradient') {
  4476. x1 = gradient.x1 || gradient[0] || 0;
  4477. y1 = gradient.y1 || gradient[1] || 0;
  4478. x2 = gradient.x2 || gradient[2] || 0;
  4479. y2 = gradient.y2 || gradient[3] || 0;
  4480. fillAttr = 'angle="' + (90 - math.atan(
  4481. (y2 - y1) / // y vector
  4482. (x2 - x1) // x vector
  4483. ) * 180 / mathPI) + '"';
  4484. addFillNode();
  4485. // Radial (circular) gradient
  4486. } else {
  4487. var r = gradient.r,
  4488. sizex = r * 2,
  4489. sizey = r * 2,
  4490. cx = gradient.cx,
  4491. cy = gradient.cy,
  4492. radialReference = elem.radialReference,
  4493. bBox,
  4494. applyRadialGradient = function () {
  4495. if (radialReference) {
  4496. bBox = wrapper.getBBox();
  4497. cx += (radialReference[0] - bBox.x) / bBox.width - 0.5;
  4498. cy += (radialReference[1] - bBox.y) / bBox.height - 0.5;
  4499. sizex *= radialReference[2] / bBox.width;
  4500. sizey *= radialReference[2] / bBox.height;
  4501. }
  4502. fillAttr = 'src="' + defaultOptions.global.VMLRadialGradientURL + '" ' +
  4503. 'size="' + sizex + ',' + sizey + '" ' +
  4504. 'origin="0.5,0.5" ' +
  4505. 'position="' + cx + ',' + cy + '" ' +
  4506. 'color2="' + color2 + '" ';
  4507. addFillNode();
  4508. };
  4509. // Apply radial gradient
  4510. if (wrapper.added) {
  4511. applyRadialGradient();
  4512. } else {
  4513. // We need to know the bounding box to get the size and position right
  4514. addEvent(wrapper, 'add', applyRadialGradient);
  4515. }
  4516. // The fill element's color attribute is broken in IE8 standards mode, so we
  4517. // need to set the parent shape's fillcolor attribute instead.
  4518. ret = color1;
  4519. }
  4520. // Gradients are not supported for VML stroke, return the first color. #722.
  4521. } else {
  4522. ret = stopColor;
  4523. }
  4524. // if the color is an rgba color, split it and add a fill node
  4525. // to hold the opacity component
  4526. } else if (regexRgba.test(color) && elem.tagName !== 'IMG') {
  4527. colorObject = Color(color);
  4528. markup = ['<', prop, ' opacity="', colorObject.get('a'), '"/>'];
  4529. createElement(this.prepVML(markup), null, null, elem);
  4530. ret = colorObject.get('rgb');
  4531. } else {
  4532. var propNodes = elem.getElementsByTagName(prop); // 'stroke' or 'fill' node
  4533. if (propNodes.length) {
  4534. propNodes[0].opacity = 1;
  4535. propNodes[0].type = 'solid';
  4536. }
  4537. ret = color;
  4538. }
  4539. return ret;
  4540. },
  4541. /**
  4542. * Take a VML string and prepare it for either IE8 or IE6/IE7.
  4543. * @param {Array} markup A string array of the VML markup to prepare
  4544. */
  4545. prepVML: function (markup) {
  4546. var vmlStyle = 'display:inline-block;behavior:url(#default#VML);',
  4547. isIE8 = this.isIE8;
  4548. markup = markup.join('');
  4549. if (isIE8) { // add xmlns and style inline
  4550. markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />');
  4551. if (markup.indexOf('style="') === -1) {
  4552. markup = markup.replace('/>', ' style="' + vmlStyle + '" />');
  4553. } else {
  4554. markup = markup.replace('style="', 'style="' + vmlStyle);
  4555. }
  4556. } else { // add namespace
  4557. markup = markup.replace('<', '<hcv:');
  4558. }
  4559. return markup;
  4560. },
  4561. /**
  4562. * Create rotated and aligned text
  4563. * @param {String} str
  4564. * @param {Number} x
  4565. * @param {Number} y
  4566. */
  4567. text: SVGRenderer.prototype.html,
  4568. /**
  4569. * Create and return a path element
  4570. * @param {Array} path
  4571. */
  4572. path: function (path) {
  4573. var attr = {
  4574. // subpixel precision down to 0.1 (width and height = 1px)
  4575. coordsize: '10 10'
  4576. };
  4577. if (isArray(path)) {
  4578. attr.d = path;
  4579. } else if (isObject(path)) { // attributes
  4580. extend(attr, path);
  4581. }
  4582. // create the shape
  4583. return this.createElement('shape').attr(attr);
  4584. },
  4585. /**
  4586. * Create and return a circle element. In VML circles are implemented as
  4587. * shapes, which is faster than v:oval
  4588. * @param {Number} x
  4589. * @param {Number} y
  4590. * @param {Number} r
  4591. */
  4592. circle: function (x, y, r) {
  4593. if (isObject(x)) {
  4594. r = x.r;
  4595. y = x.y;
  4596. x = x.x;
  4597. }
  4598. return this.symbol('circle').attr({ x: x - r, y: y - r, width: 2 * r, height: 2 * r });
  4599. },
  4600. /**
  4601. * Create a group using an outer div and an inner v:group to allow rotating
  4602. * and flipping. A simple v:group would have problems with positioning
  4603. * child HTML elements and CSS clip.
  4604. *
  4605. * @param {String} name The name of the group
  4606. */
  4607. g: function (name) {
  4608. var wrapper,
  4609. attribs;
  4610. // set the class name
  4611. if (name) {
  4612. attribs = { 'className': PREFIX + name, 'class': PREFIX + name };
  4613. }
  4614. // the div to hold HTML and clipping
  4615. wrapper = this.createElement(DIV).attr(attribs);
  4616. return wrapper;
  4617. },
  4618. /**
  4619. * VML override to create a regular HTML image
  4620. * @param {String} src
  4621. * @param {Number} x
  4622. * @param {Number} y
  4623. * @param {Number} width
  4624. * @param {Number} height
  4625. */
  4626. image: function (src, x, y, width, height) {
  4627. var obj = this.createElement('img')
  4628. .attr({ src: src });
  4629. if (arguments.length > 1) {
  4630. obj.attr({
  4631. x: x,
  4632. y: y,
  4633. width: width,
  4634. height: height
  4635. });
  4636. }
  4637. return obj;
  4638. },
  4639. /**
  4640. * VML uses a shape for rect to overcome bugs and rotation problems
  4641. */
  4642. rect: function (x, y, width, height, r, strokeWidth) {
  4643. if (isObject(x)) {
  4644. y = x.y;
  4645. width = x.width;
  4646. height = x.height;
  4647. strokeWidth = x.strokeWidth;
  4648. x = x.x;
  4649. }
  4650. var wrapper = this.symbol('rect');
  4651. wrapper.r = r;
  4652. return wrapper.attr(wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0)));
  4653. },
  4654. /**
  4655. * In the VML renderer, each child of an inverted div (group) is inverted
  4656. * @param {Object} element
  4657. * @param {Object} parentNode
  4658. */
  4659. invertChild: function (element, parentNode) {
  4660. var parentStyle = parentNode.style;
  4661. css(element, {
  4662. flip: 'x',
  4663. left: pInt(parentStyle.width) - 1,
  4664. top: pInt(parentStyle.height) - 1,
  4665. rotation: -90
  4666. });
  4667. },
  4668. /**
  4669. * Symbol definitions that override the parent SVG renderer's symbols
  4670. *
  4671. */
  4672. symbols: {
  4673. // VML specific arc function
  4674. arc: function (x, y, w, h, options) {
  4675. var start = options.start,
  4676. end = options.end,
  4677. radius = options.r || w || h,
  4678. innerRadius = options.innerR,
  4679. cosStart = mathCos(start),
  4680. sinStart = mathSin(start),
  4681. cosEnd = mathCos(end),
  4682. sinEnd = mathSin(end),
  4683. ret;
  4684. if (end - start === 0) { // no angle, don't show it.
  4685. return ['x'];
  4686. }
  4687. ret = [
  4688. 'wa', // clockwise arc to
  4689. x - radius, // left
  4690. y - radius, // top
  4691. x + radius, // right
  4692. y + radius, // bottom
  4693. x + radius * cosStart, // start x
  4694. y + radius * sinStart, // start y
  4695. x + radius * cosEnd, // end x
  4696. y + radius * sinEnd // end y
  4697. ];
  4698. if (options.open && !innerRadius) {
  4699. ret.push(
  4700. 'e',
  4701. M,
  4702. x,// - innerRadius,
  4703. y// - innerRadius
  4704. );
  4705. }
  4706. ret.push(
  4707. 'at', // anti clockwise arc to
  4708. x - innerRadius, // left
  4709. y - innerRadius, // top
  4710. x + innerRadius, // right
  4711. y + innerRadius, // bottom
  4712. x + innerRadius * cosEnd, // start x
  4713. y + innerRadius * sinEnd, // start y
  4714. x + innerRadius * cosStart, // end x
  4715. y + innerRadius * sinStart, // end y
  4716. 'x', // finish path
  4717. 'e' // close
  4718. );
  4719. ret.isArc = true;
  4720. return ret;
  4721. },
  4722. // Add circle symbol path. This performs significantly faster than v:oval.
  4723. circle: function (x, y, w, h) {
  4724. return [
  4725. 'wa', // clockwisearcto
  4726. x, // left
  4727. y, // top
  4728. x + w, // right
  4729. y + h, // bottom
  4730. x + w, // start x
  4731. y + h / 2, // start y
  4732. x + w, // end x
  4733. y + h / 2, // end y
  4734. //'x', // finish path
  4735. 'e' // close
  4736. ];
  4737. },
  4738. /**
  4739. * Add rectangle symbol path which eases rotation and omits arcsize problems
  4740. * compared to the built-in VML roundrect shape
  4741. *
  4742. * @param {Number} left Left position
  4743. * @param {Number} top Top position
  4744. * @param {Number} r Border radius
  4745. * @param {Object} options Width and height
  4746. */
  4747. rect: function (left, top, width, height, options) {
  4748. var right = left + width,
  4749. bottom = top + height,
  4750. ret,
  4751. r;
  4752. // No radius, return the more lightweight square
  4753. if (!defined(options) || !options.r) {
  4754. ret = SVGRenderer.prototype.symbols.square.apply(0, arguments);
  4755. // Has radius add arcs for the corners
  4756. } else {
  4757. r = mathMin(options.r, width, height);
  4758. ret = [
  4759. M,
  4760. left + r, top,
  4761. L,
  4762. right - r, top,
  4763. 'wa',
  4764. right - 2 * r, top,
  4765. right, top + 2 * r,
  4766. right - r, top,
  4767. right, top + r,
  4768. L,
  4769. right, bottom - r,
  4770. 'wa',
  4771. right - 2 * r, bottom - 2 * r,
  4772. right, bottom,
  4773. right, bottom - r,
  4774. right - r, bottom,
  4775. L,
  4776. left + r, bottom,
  4777. 'wa',
  4778. left, bottom - 2 * r,
  4779. left + 2 * r, bottom,
  4780. left + r, bottom,
  4781. left, bottom - r,
  4782. L,
  4783. left, top + r,
  4784. 'wa',
  4785. left, top,
  4786. left + 2 * r, top + 2 * r,
  4787. left, top + r,
  4788. left + r, top,
  4789. 'x',
  4790. 'e'
  4791. ];
  4792. }
  4793. return ret;
  4794. }
  4795. }
  4796. };
  4797. Highcharts.VMLRenderer = VMLRenderer = function () {
  4798. this.init.apply(this, arguments);
  4799. };
  4800. VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension);
  4801. // general renderer
  4802. Renderer = VMLRenderer;
  4803. }
  4804. /* ****************************************************************************
  4805. * *
  4806. * END OF INTERNET EXPLORER <= 8 SPECIFIC CODE *
  4807. * *
  4808. *****************************************************************************/
  4809. /* ****************************************************************************
  4810. * *
  4811. * START OF ANDROID < 3 SPECIFIC CODE. THIS CAN BE REMOVED IF YOU'RE NOT *
  4812. * TARGETING THAT SYSTEM. *
  4813. * *
  4814. *****************************************************************************/
  4815. var CanVGRenderer,
  4816. CanVGController;
  4817. if (useCanVG) {
  4818. /**
  4819. * The CanVGRenderer is empty from start to keep the source footprint small.
  4820. * When requested, the CanVGController downloads the rest of the source packaged
  4821. * together with the canvg library.
  4822. */
  4823. Highcharts.CanVGRenderer = CanVGRenderer = function () {
  4824. // Override the global SVG namespace to fake SVG/HTML that accepts CSS
  4825. SVG_NS = 'http://www.w3.org/1999/xhtml';
  4826. };
  4827. /**
  4828. * Start with an empty symbols object. This is needed when exporting is used (exporting.src.js will add a few symbols), but
  4829. * the implementation from SvgRenderer will not be merged in until first render.
  4830. */
  4831. CanVGRenderer.prototype.symbols = {};
  4832. /**
  4833. * Handles on demand download of canvg rendering support.
  4834. */
  4835. CanVGController = (function () {
  4836. // List of renderering calls
  4837. var deferredRenderCalls = [];
  4838. /**
  4839. * When downloaded, we are ready to draw deferred charts.
  4840. */
  4841. function drawDeferred() {
  4842. var callLength = deferredRenderCalls.length,
  4843. callIndex;
  4844. // Draw all pending render calls
  4845. for (callIndex = 0; callIndex < callLength; callIndex++) {
  4846. deferredRenderCalls[callIndex]();
  4847. }
  4848. // Clear the list
  4849. deferredRenderCalls = [];
  4850. }
  4851. return {
  4852. push: function (func, scriptLocation) {
  4853. // Only get the script once
  4854. if (deferredRenderCalls.length === 0) {
  4855. getScript(scriptLocation, drawDeferred);
  4856. }
  4857. // Register render call
  4858. deferredRenderCalls.push(func);
  4859. }
  4860. };
  4861. }());
  4862. Renderer = CanVGRenderer;
  4863. } // end CanVGRenderer
  4864. /* ****************************************************************************
  4865. * *
  4866. * END OF ANDROID < 3 SPECIFIC CODE *
  4867. * *
  4868. *****************************************************************************/
  4869. /**
  4870. * The Tick class
  4871. */
  4872. function Tick(axis, pos, type, noLabel) {
  4873. this.axis = axis;
  4874. this.pos = pos;
  4875. this.type = type || '';
  4876. this.isNew = true;
  4877. if (!type && !noLabel) {
  4878. this.addLabel();
  4879. }
  4880. }
  4881. Tick.prototype = {
  4882. /**
  4883. * Write the tick label
  4884. */
  4885. addLabel: function () {
  4886. var tick = this,
  4887. axis = tick.axis,
  4888. options = axis.options,
  4889. chart = axis.chart,
  4890. horiz = axis.horiz,
  4891. categories = axis.categories,
  4892. names = axis.series[0] && axis.series[0].names,
  4893. pos = tick.pos,
  4894. labelOptions = options.labels,
  4895. str,
  4896. tickPositions = axis.tickPositions,
  4897. width = (horiz && categories &&
  4898. !labelOptions.step && !labelOptions.staggerLines &&
  4899. !labelOptions.rotation &&
  4900. chart.plotWidth / tickPositions.length) ||
  4901. (!horiz && (chart.optionsMarginLeft || chart.plotWidth / 2)), // #1580
  4902. isFirst = pos === tickPositions[0],
  4903. isLast = pos === tickPositions[tickPositions.length - 1],
  4904. css,
  4905. attr,
  4906. value = categories ?
  4907. pick(categories[pos], names && names[pos], pos) :
  4908. pos,
  4909. label = tick.label,
  4910. tickPositionInfo = tickPositions.info,
  4911. dateTimeLabelFormat;
  4912. // Set the datetime label format. If a higher rank is set for this position, use that. If not,
  4913. // use the general format.
  4914. if (axis.isDatetimeAxis && tickPositionInfo) {
  4915. dateTimeLabelFormat = options.dateTimeLabelFormats[tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName];
  4916. }
  4917. // set properties for access in render method
  4918. tick.isFirst = isFirst;
  4919. tick.isLast = isLast;
  4920. // get the string
  4921. str = axis.labelFormatter.call({
  4922. axis: axis,
  4923. chart: chart,
  4924. isFirst: isFirst,
  4925. isLast: isLast,
  4926. dateTimeLabelFormat: dateTimeLabelFormat,
  4927. value: axis.isLog ? correctFloat(lin2log(value)) : value
  4928. });
  4929. // prepare CSS
  4930. css = width && { width: mathMax(1, mathRound(width - 2 * (labelOptions.padding || 10))) + PX };
  4931. css = extend(css, labelOptions.style);
  4932. // first call
  4933. if (!defined(label)) {
  4934. attr = {
  4935. align: labelOptions.align
  4936. };
  4937. if (isNumber(labelOptions.rotation)) {
  4938. attr.rotation = labelOptions.rotation;
  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. ((this.labelBBox = 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.labelBBox, // assume getLabelSize has run at this point
  4977. axis = this.axis,
  4978. options = axis.options,
  4979. labelOptions = options.labels,
  4980. width = bBox.width,
  4981. leftSide = width * { left: 0, center: 0.5, right: 1 }[labelOptions.align] - labelOptions.x;
  4982. return [-leftSide, width - leftSide];
  4983. },
  4984. /**
  4985. * Handle the label overflow by adjusting the labels to the left and right edge, or
  4986. * hide them if they collide into the neighbour label.
  4987. */
  4988. handleOverflow: function (index, xy) {
  4989. var show = true,
  4990. axis = this.axis,
  4991. chart = axis.chart,
  4992. isFirst = this.isFirst,
  4993. isLast = this.isLast,
  4994. x = xy.x,
  4995. reversed = axis.reversed,
  4996. tickPositions = axis.tickPositions;
  4997. if (isFirst || isLast) {
  4998. var sides = this.getLabelSides(),
  4999. leftSide = sides[0],
  5000. rightSide = sides[1],
  5001. plotLeft = chart.plotLeft,
  5002. plotRight = plotLeft + axis.len,
  5003. neighbour = axis.ticks[tickPositions[index + (isFirst ? 1 : -1)]],
  5004. neighbourEdge = neighbour && neighbour.label.xy && neighbour.label.xy.x + neighbour.getLabelSides()[isFirst ? 0 : 1];
  5005. if ((isFirst && !reversed) || (isLast && reversed)) {
  5006. // Is the label spilling out to the left of the plot area?
  5007. if (x + leftSide < plotLeft) {
  5008. // Align it to plot left
  5009. x = plotLeft - leftSide;
  5010. // Hide it if it now overlaps the neighbour label
  5011. if (neighbour && x + rightSide > neighbourEdge) {
  5012. show = false;
  5013. }
  5014. }
  5015. } else {
  5016. // Is the label spilling out to the right of the plot area?
  5017. if (x + rightSide > plotRight) {
  5018. // Align it to plot right
  5019. x = plotRight - rightSide;
  5020. // Hide it if it now overlaps the neighbour label
  5021. if (neighbour && x + leftSide < neighbourEdge) {
  5022. show = false;
  5023. }
  5024. }
  5025. }
  5026. // Set the modified x position of the label
  5027. xy.x = x;
  5028. }
  5029. return show;
  5030. },
  5031. /**
  5032. * Get the x and y position for ticks and labels
  5033. */
  5034. getPosition: function (horiz, pos, tickmarkOffset, old) {
  5035. var axis = this.axis,
  5036. chart = axis.chart,
  5037. cHeight = (old && chart.oldChartHeight) || chart.chartHeight;
  5038. return {
  5039. x: horiz ?
  5040. axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB :
  5041. axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0),
  5042. y: horiz ?
  5043. cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) :
  5044. cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB
  5045. };
  5046. },
  5047. /**
  5048. * Get the x, y position of the tick label
  5049. */
  5050. getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) {
  5051. var axis = this.axis,
  5052. transA = axis.transA,
  5053. reversed = axis.reversed,
  5054. staggerLines = axis.staggerLines;
  5055. x = x + labelOptions.x - (tickmarkOffset && horiz ?
  5056. tickmarkOffset * transA * (reversed ? -1 : 1) : 0);
  5057. y = y + labelOptions.y - (tickmarkOffset && !horiz ?
  5058. tickmarkOffset * transA * (reversed ? 1 : -1) : 0);
  5059. // Vertically centered
  5060. if (!defined(labelOptions.y)) {
  5061. y += pInt(label.styles.lineHeight) * 0.9 - label.getBBox().height / 2;
  5062. }
  5063. // Correct for staggered labels
  5064. if (staggerLines) {
  5065. y += (index / (step || 1) % staggerLines) * 16;
  5066. }
  5067. return {
  5068. x: x,
  5069. y: y
  5070. };
  5071. },
  5072. /**
  5073. * Extendible method to return the path of the marker
  5074. */
  5075. getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) {
  5076. return renderer.crispLine([
  5077. M,
  5078. x,
  5079. y,
  5080. L,
  5081. x + (horiz ? 0 : -tickLength),
  5082. y + (horiz ? tickLength : 0)
  5083. ], tickWidth);
  5084. },
  5085. /**
  5086. * Put everything in place
  5087. *
  5088. * @param index {Number}
  5089. * @param old {Boolean} Use old coordinates to prepare an animation into new position
  5090. */
  5091. render: function (index, old, opacity) {
  5092. var tick = this,
  5093. axis = tick.axis,
  5094. options = axis.options,
  5095. chart = axis.chart,
  5096. renderer = chart.renderer,
  5097. horiz = axis.horiz,
  5098. type = tick.type,
  5099. label = tick.label,
  5100. pos = tick.pos,
  5101. labelOptions = options.labels,
  5102. gridLine = tick.gridLine,
  5103. gridPrefix = type ? type + 'Grid' : 'grid',
  5104. tickPrefix = type ? type + 'Tick' : 'tick',
  5105. gridLineWidth = options[gridPrefix + 'LineWidth'],
  5106. gridLineColor = options[gridPrefix + 'LineColor'],
  5107. dashStyle = options[gridPrefix + 'LineDashStyle'],
  5108. tickLength = options[tickPrefix + 'Length'],
  5109. tickWidth = options[tickPrefix + 'Width'] || 0,
  5110. tickColor = options[tickPrefix + 'Color'],
  5111. tickPosition = options[tickPrefix + 'Position'],
  5112. gridLinePath,
  5113. mark = tick.mark,
  5114. markPath,
  5115. step = labelOptions.step,
  5116. attribs,
  5117. show = true,
  5118. tickmarkOffset = axis.tickmarkOffset,
  5119. xy = tick.getPosition(horiz, pos, tickmarkOffset, old),
  5120. x = xy.x,
  5121. y = xy.y,
  5122. reverseCrisp = ((horiz && x === axis.pos) || (!horiz && y === axis.pos + axis.len)) ? -1 : 1, // #1480
  5123. staggerLines = axis.staggerLines;
  5124. this.isActive = true;
  5125. // create the grid line
  5126. if (gridLineWidth) {
  5127. gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLineWidth * reverseCrisp, old, true);
  5128. if (gridLine === UNDEFINED) {
  5129. attribs = {
  5130. stroke: gridLineColor,
  5131. 'stroke-width': gridLineWidth
  5132. };
  5133. if (dashStyle) {
  5134. attribs.dashstyle = dashStyle;
  5135. }
  5136. if (!type) {
  5137. attribs.zIndex = 1;
  5138. }
  5139. if (old) {
  5140. attribs.opacity = 0;
  5141. }
  5142. tick.gridLine = gridLine =
  5143. gridLineWidth ?
  5144. renderer.path(gridLinePath)
  5145. .attr(attribs).add(axis.gridGroup) :
  5146. null;
  5147. }
  5148. // If the parameter 'old' is set, the current call will be followed
  5149. // by another call, therefore do not do any animations this time
  5150. if (!old && gridLine && gridLinePath) {
  5151. gridLine[tick.isNew ? 'attr' : 'animate']({
  5152. d: gridLinePath,
  5153. opacity: opacity
  5154. });
  5155. }
  5156. }
  5157. // create the tick mark
  5158. if (tickWidth && tickLength) {
  5159. // negate the length
  5160. if (tickPosition === 'inside') {
  5161. tickLength = -tickLength;
  5162. }
  5163. if (axis.opposite) {
  5164. tickLength = -tickLength;
  5165. }
  5166. markPath = tick.getMarkPath(x, y, tickLength, tickWidth * reverseCrisp, horiz, renderer);
  5167. if (mark) { // updating
  5168. mark.animate({
  5169. d: markPath,
  5170. opacity: opacity
  5171. });
  5172. } else { // first time
  5173. tick.mark = renderer.path(
  5174. markPath
  5175. ).attr({
  5176. stroke: tickColor,
  5177. 'stroke-width': tickWidth,
  5178. opacity: opacity
  5179. }).add(axis.axisGroup);
  5180. }
  5181. }
  5182. // the label is created on init - now move it into place
  5183. if (label && !isNaN(x)) {
  5184. label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step);
  5185. // apply show first and show last
  5186. if ((tick.isFirst && !pick(options.showFirstLabel, 1)) ||
  5187. (tick.isLast && !pick(options.showLastLabel, 1))) {
  5188. show = false;
  5189. // Handle label overflow and show or hide accordingly
  5190. } else if (!staggerLines && horiz && labelOptions.overflow === 'justify' && !tick.handleOverflow(index, xy)) {
  5191. show = false;
  5192. }
  5193. // apply step
  5194. if (step && index % step) {
  5195. // show those indices dividable by step
  5196. show = false;
  5197. }
  5198. // Set the new position, and show or hide
  5199. if (show && !isNaN(xy.y)) {
  5200. xy.opacity = opacity;
  5201. label[tick.isNew ? 'attr' : 'animate'](xy);
  5202. tick.isNew = false;
  5203. } else {
  5204. label.attr('y', -9999); // #1338
  5205. }
  5206. }
  5207. },
  5208. /**
  5209. * Destructor for the tick prototype
  5210. */
  5211. destroy: function () {
  5212. destroyObjectProperties(this, this.axis);
  5213. }
  5214. };
  5215. /**
  5216. * The object wrapper for plot lines and plot bands
  5217. * @param {Object} options
  5218. */
  5219. function PlotLineOrBand(axis, options) {
  5220. this.axis = axis;
  5221. if (options) {
  5222. this.options = options;
  5223. this.id = options.id;
  5224. }
  5225. }
  5226. PlotLineOrBand.prototype = {
  5227. /**
  5228. * Render the plot line or plot band. If it is already existing,
  5229. * move it.
  5230. */
  5231. render: function () {
  5232. var plotLine = this,
  5233. axis = plotLine.axis,
  5234. horiz = axis.horiz,
  5235. halfPointRange = (axis.pointRange || 0) / 2,
  5236. options = plotLine.options,
  5237. optionsLabel = options.label,
  5238. label = plotLine.label,
  5239. width = options.width,
  5240. to = options.to,
  5241. from = options.from,
  5242. isBand = defined(from) && defined(to),
  5243. value = options.value,
  5244. dashStyle = options.dashStyle,
  5245. svgElem = plotLine.svgElem,
  5246. path = [],
  5247. addEvent,
  5248. eventType,
  5249. xs,
  5250. ys,
  5251. x,
  5252. y,
  5253. color = options.color,
  5254. zIndex = options.zIndex,
  5255. events = options.events,
  5256. attribs,
  5257. renderer = axis.chart.renderer;
  5258. // logarithmic conversion
  5259. if (axis.isLog) {
  5260. from = log2lin(from);
  5261. to = log2lin(to);
  5262. value = log2lin(value);
  5263. }
  5264. // plot line
  5265. if (width) {
  5266. path = axis.getPlotLinePath(value, width);
  5267. attribs = {
  5268. stroke: color,
  5269. 'stroke-width': width
  5270. };
  5271. if (dashStyle) {
  5272. attribs.dashstyle = dashStyle;
  5273. }
  5274. } else if (isBand) { // plot band
  5275. // keep within plot area
  5276. from = mathMax(from, axis.min - halfPointRange);
  5277. to = mathMin(to, axis.max + halfPointRange);
  5278. path = axis.getPlotBandPath(from, to, options);
  5279. attribs = {
  5280. fill: color
  5281. };
  5282. if (options.borderWidth) {
  5283. attribs.stroke = options.borderColor;
  5284. attribs['stroke-width'] = options.borderWidth;
  5285. }
  5286. } else {
  5287. return;
  5288. }
  5289. // zIndex
  5290. if (defined(zIndex)) {
  5291. attribs.zIndex = zIndex;
  5292. }
  5293. // common for lines and bands
  5294. if (svgElem) {
  5295. if (path) {
  5296. svgElem.animate({
  5297. d: path
  5298. }, null, svgElem.onGetPath);
  5299. } else {
  5300. svgElem.hide();
  5301. svgElem.onGetPath = function () {
  5302. svgElem.show();
  5303. };
  5304. }
  5305. } else if (path && path.length) {
  5306. plotLine.svgElem = svgElem = renderer.path(path)
  5307. .attr(attribs).add();
  5308. // events
  5309. if (events) {
  5310. addEvent = function (eventType) {
  5311. svgElem.on(eventType, function (e) {
  5312. events[eventType].apply(plotLine, [e]);
  5313. });
  5314. };
  5315. for (eventType in events) {
  5316. addEvent(eventType);
  5317. }
  5318. }
  5319. }
  5320. // the plot band/line label
  5321. if (optionsLabel && defined(optionsLabel.text) && path && path.length && axis.width > 0 && axis.height > 0) {
  5322. // apply defaults
  5323. optionsLabel = merge({
  5324. align: horiz && isBand && 'center',
  5325. x: horiz ? !isBand && 4 : 10,
  5326. verticalAlign : !horiz && isBand && 'middle',
  5327. y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4,
  5328. rotation: horiz && !isBand && 90
  5329. }, optionsLabel);
  5330. // add the SVG element
  5331. if (!label) {
  5332. plotLine.label = label = renderer.text(
  5333. optionsLabel.text,
  5334. 0,
  5335. 0
  5336. )
  5337. .attr({
  5338. align: optionsLabel.textAlign || optionsLabel.align,
  5339. rotation: optionsLabel.rotation,
  5340. zIndex: zIndex
  5341. })
  5342. .css(optionsLabel.style)
  5343. .add();
  5344. }
  5345. // get the bounding box and align the label
  5346. xs = [path[1], path[4], pick(path[6], path[1])];
  5347. ys = [path[2], path[5], pick(path[7], path[2])];
  5348. x = arrayMin(xs);
  5349. y = arrayMin(ys);
  5350. label.align(optionsLabel, false, {
  5351. x: x,
  5352. y: y,
  5353. width: arrayMax(xs) - x,
  5354. height: arrayMax(ys) - y
  5355. });
  5356. label.show();
  5357. } else if (label) { // move out of sight
  5358. label.hide();
  5359. }
  5360. // chainable
  5361. return plotLine;
  5362. },
  5363. /**
  5364. * Remove the plot line or band
  5365. */
  5366. destroy: function () {
  5367. var plotLine = this,
  5368. axis = plotLine.axis;
  5369. // remove it from the lookup
  5370. erase(axis.plotLinesAndBands, plotLine);
  5371. destroyObjectProperties(plotLine, this.axis);
  5372. }
  5373. };
  5374. /**
  5375. * The class for stack items
  5376. */
  5377. function StackItem(axis, options, isNegative, x, stackOption, stacking) {
  5378. var inverted = axis.chart.inverted;
  5379. this.axis = axis;
  5380. // Tells if the stack is negative
  5381. this.isNegative = isNegative;
  5382. // Save the options to be able to style the label
  5383. this.options = options;
  5384. // Save the x value to be able to position the label later
  5385. this.x = x;
  5386. // Save the stack option on the series configuration object, and whether to treat it as percent
  5387. this.stack = stackOption;
  5388. this.percent = stacking === 'percent';
  5389. // The align options and text align varies on whether the stack is negative and
  5390. // if the chart is inverted or not.
  5391. // First test the user supplied value, then use the dynamic.
  5392. this.alignOptions = {
  5393. align: options.align || (inverted ? (isNegative ? 'left' : 'right') : 'center'),
  5394. verticalAlign: options.verticalAlign || (inverted ? 'middle' : (isNegative ? 'bottom' : 'top')),
  5395. y: pick(options.y, inverted ? 4 : (isNegative ? 14 : -6)),
  5396. x: pick(options.x, inverted ? (isNegative ? -6 : 6) : 0)
  5397. };
  5398. this.textAlign = options.textAlign || (inverted ? (isNegative ? 'right' : 'left') : 'center');
  5399. }
  5400. StackItem.prototype = {
  5401. destroy: function () {
  5402. destroyObjectProperties(this, this.axis);
  5403. },
  5404. /**
  5405. * Sets the total of this stack. Should be called when a serie is hidden or shown
  5406. * since that will affect the total of other stacks.
  5407. */
  5408. setTotal: function (total) {
  5409. this.total = total;
  5410. this.cum = total;
  5411. },
  5412. /**
  5413. * Renders the stack total label and adds it to the stack label group.
  5414. */
  5415. render: function (group) {
  5416. var options = this.options,
  5417. str = options.formatter.call(this); // format the text in the label
  5418. // Change the text to reflect the new total and set visibility to hidden in case the serie is hidden
  5419. if (this.label) {
  5420. this.label.attr({text: str, visibility: HIDDEN});
  5421. // Create new label
  5422. } else {
  5423. this.label =
  5424. this.axis.chart.renderer.text(str, 0, 0, options.useHTML) // dummy positions, actual position updated with setOffset method in columnseries
  5425. .css(options.style) // apply style
  5426. .attr({
  5427. align: this.textAlign, // fix the text-anchor
  5428. rotation: options.rotation, // rotation
  5429. visibility: HIDDEN // hidden until setOffset is called
  5430. })
  5431. .add(group); // add to the labels-group
  5432. }
  5433. },
  5434. /**
  5435. * Sets the offset that the stack has from the x value and repositions the label.
  5436. */
  5437. setOffset: function (xOffset, xWidth) {
  5438. var stackItem = this,
  5439. axis = stackItem.axis,
  5440. chart = axis.chart,
  5441. inverted = chart.inverted,
  5442. neg = this.isNegative, // special treatment is needed for negative stacks
  5443. y = axis.translate(this.percent ? 100 : this.total, 0, 0, 0, 1), // stack value translated mapped to chart coordinates
  5444. yZero = axis.translate(0), // stack origin
  5445. h = mathAbs(y - yZero), // stack height
  5446. x = chart.xAxis[0].translate(this.x) + xOffset, // stack x position
  5447. plotHeight = chart.plotHeight,
  5448. stackBox = { // this is the box for the complete stack
  5449. x: inverted ? (neg ? y : y - h) : x,
  5450. y: inverted ? plotHeight - x - xWidth : (neg ? (plotHeight - y - h) : plotHeight - y),
  5451. width: inverted ? h : xWidth,
  5452. height: inverted ? xWidth : h
  5453. },
  5454. label = this.label,
  5455. alignAttr;
  5456. if (label) {
  5457. label.align(this.alignOptions, null, stackBox); // align the label to the box
  5458. // Set visibility (#678)
  5459. alignAttr = label.alignAttr;
  5460. label.attr({
  5461. visibility: this.options.crop === false || chart.isInsidePlot(alignAttr.x, alignAttr.y) ?
  5462. (hasSVG ? 'inherit' : VISIBLE) :
  5463. HIDDEN
  5464. });
  5465. }
  5466. }
  5467. };
  5468. /**
  5469. * Create a new axis object
  5470. * @param {Object} chart
  5471. * @param {Object} options
  5472. */
  5473. function Axis() {
  5474. this.init.apply(this, arguments);
  5475. }
  5476. Axis.prototype = {
  5477. /**
  5478. * Default options for the X axis - the Y axis has extended defaults
  5479. */
  5480. defaultOptions: {
  5481. // allowDecimals: null,
  5482. // alternateGridColor: null,
  5483. // categories: [],
  5484. dateTimeLabelFormats: {
  5485. millisecond: '%H:%M:%S.%L',
  5486. second: '%H:%M:%S',
  5487. minute: '%H:%M',
  5488. hour: '%H:%M',
  5489. day: '%e. %b',
  5490. week: '%e. %b',
  5491. month: '%b \'%y',
  5492. year: '%Y'
  5493. },
  5494. endOnTick: false,
  5495. gridLineColor: '#C0C0C0',
  5496. // gridLineDashStyle: 'solid',
  5497. // gridLineWidth: 0,
  5498. // reversed: false,
  5499. labels: defaultLabelOptions,
  5500. // { step: null },
  5501. lineColor: '#C0D0E0',
  5502. lineWidth: 1,
  5503. //linkedTo: null,
  5504. //max: undefined,
  5505. //min: undefined,
  5506. minPadding: 0.01,
  5507. maxPadding: 0.01,
  5508. //minRange: null,
  5509. minorGridLineColor: '#E0E0E0',
  5510. // minorGridLineDashStyle: null,
  5511. minorGridLineWidth: 1,
  5512. minorTickColor: '#A0A0A0',
  5513. //minorTickInterval: null,
  5514. minorTickLength: 2,
  5515. minorTickPosition: 'outside', // inside or outside
  5516. //minorTickWidth: 0,
  5517. //opposite: false,
  5518. //offset: 0,
  5519. //plotBands: [{
  5520. // events: {},
  5521. // zIndex: 1,
  5522. // labels: { align, x, verticalAlign, y, style, rotation, textAlign }
  5523. //}],
  5524. //plotLines: [{
  5525. // events: {}
  5526. // dashStyle: {}
  5527. // zIndex:
  5528. // labels: { align, x, verticalAlign, y, style, rotation, textAlign }
  5529. //}],
  5530. //reversed: false,
  5531. // showFirstLabel: true,
  5532. // showLastLabel: true,
  5533. startOfWeek: 1,
  5534. startOnTick: false,
  5535. tickColor: '#C0D0E0',
  5536. //tickInterval: null,
  5537. tickLength: 5,
  5538. tickmarkPlacement: 'between', // on or between
  5539. tickPixelInterval: 100,
  5540. tickPosition: 'outside',
  5541. tickWidth: 1,
  5542. title: {
  5543. //text: null,
  5544. align: 'middle', // low, middle or high
  5545. //margin: 0 for horizontal, 10 for vertical axes,
  5546. //rotation: 0,
  5547. //side: 'outside',
  5548. style: {
  5549. color: '#4d759e',
  5550. //font: defaultFont.replace('normal', 'bold')
  5551. fontWeight: 'bold'
  5552. }
  5553. //x: 0,
  5554. //y: 0
  5555. },
  5556. type: 'linear' // linear, logarithmic or datetime
  5557. },
  5558. /**
  5559. * This options set extends the defaultOptions for Y axes
  5560. */
  5561. defaultYAxisOptions: {
  5562. endOnTick: true,
  5563. gridLineWidth: 1,
  5564. tickPixelInterval: 72,
  5565. showLastLabel: true,
  5566. labels: {
  5567. align: 'right',
  5568. x: -8,
  5569. y: 3
  5570. },
  5571. lineWidth: 0,
  5572. maxPadding: 0.05,
  5573. minPadding: 0.05,
  5574. startOnTick: true,
  5575. tickWidth: 0,
  5576. title: {
  5577. rotation: 270,
  5578. text: 'Values'
  5579. },
  5580. stackLabels: {
  5581. enabled: false,
  5582. //align: dynamic,
  5583. //y: dynamic,
  5584. //x: dynamic,
  5585. //verticalAlign: dynamic,
  5586. //textAlign: dynamic,
  5587. //rotation: 0,
  5588. formatter: function () {
  5589. return this.total;
  5590. },
  5591. style: defaultLabelOptions.style
  5592. }
  5593. },
  5594. /**
  5595. * These options extend the defaultOptions for left axes
  5596. */
  5597. defaultLeftAxisOptions: {
  5598. labels: {
  5599. align: 'right',
  5600. x: -8,
  5601. y: null
  5602. },
  5603. title: {
  5604. rotation: 270
  5605. }
  5606. },
  5607. /**
  5608. * These options extend the defaultOptions for right axes
  5609. */
  5610. defaultRightAxisOptions: {
  5611. labels: {
  5612. align: 'left',
  5613. x: 8,
  5614. y: null
  5615. },
  5616. title: {
  5617. rotation: 90
  5618. }
  5619. },
  5620. /**
  5621. * These options extend the defaultOptions for bottom axes
  5622. */
  5623. defaultBottomAxisOptions: {
  5624. labels: {
  5625. align: 'center',
  5626. x: 0,
  5627. y: 14
  5628. // overflow: undefined,
  5629. // staggerLines: null
  5630. },
  5631. title: {
  5632. rotation: 0
  5633. }
  5634. },
  5635. /**
  5636. * These options extend the defaultOptions for left axes
  5637. */
  5638. defaultTopAxisOptions: {
  5639. labels: {
  5640. align: 'center',
  5641. x: 0,
  5642. y: -5
  5643. // overflow: undefined
  5644. // staggerLines: null
  5645. },
  5646. title: {
  5647. rotation: 0
  5648. }
  5649. },
  5650. /**
  5651. * Initialize the axis
  5652. */
  5653. init: function (chart, userOptions) {
  5654. var isXAxis = userOptions.isX,
  5655. axis = this;
  5656. // Flag, is the axis horizontal
  5657. axis.horiz = chart.inverted ? !isXAxis : isXAxis;
  5658. // Flag, isXAxis
  5659. axis.isXAxis = isXAxis;
  5660. axis.xOrY = isXAxis ? 'x' : 'y';
  5661. axis.opposite = userOptions.opposite; // needed in setOptions
  5662. axis.side = axis.horiz ?
  5663. (axis.opposite ? 0 : 2) : // top : bottom
  5664. (axis.opposite ? 1 : 3); // right : left
  5665. axis.setOptions(userOptions);
  5666. var options = this.options,
  5667. type = options.type,
  5668. isDatetimeAxis = type === 'datetime';
  5669. axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format
  5670. // Flag, stagger lines or not
  5671. axis.staggerLines = axis.horiz && options.labels.staggerLines;
  5672. axis.userOptions = userOptions;
  5673. //axis.axisTitleMargin = UNDEFINED,// = options.title.margin,
  5674. axis.minPixelPadding = 0;
  5675. //axis.ignoreMinPadding = UNDEFINED; // can be set to true by a column or bar series
  5676. //axis.ignoreMaxPadding = UNDEFINED;
  5677. axis.chart = chart;
  5678. axis.reversed = options.reversed;
  5679. axis.zoomEnabled = options.zoomEnabled !== false;
  5680. // Initial categories
  5681. axis.categories = options.categories || type === 'category';
  5682. // Elements
  5683. //axis.axisGroup = UNDEFINED;
  5684. //axis.gridGroup = UNDEFINED;
  5685. //axis.axisTitle = UNDEFINED;
  5686. //axis.axisLine = UNDEFINED;
  5687. // Shorthand types
  5688. axis.isLog = type === 'logarithmic';
  5689. axis.isDatetimeAxis = isDatetimeAxis;
  5690. // Flag, if axis is linked to another axis
  5691. axis.isLinked = defined(options.linkedTo);
  5692. // Linked axis.
  5693. //axis.linkedParent = UNDEFINED;
  5694. // Flag if percentage mode
  5695. //axis.usePercentage = UNDEFINED;
  5696. // Tick positions
  5697. //axis.tickPositions = UNDEFINED; // array containing predefined positions
  5698. // Tick intervals
  5699. //axis.tickInterval = UNDEFINED;
  5700. //axis.minorTickInterval = UNDEFINED;
  5701. axis.tickmarkOffset = (axis.categories && options.tickmarkPlacement === 'between') ? 0.5 : 0;
  5702. // Major ticks
  5703. axis.ticks = {};
  5704. // Minor ticks
  5705. axis.minorTicks = {};
  5706. //axis.tickAmount = UNDEFINED;
  5707. // List of plotLines/Bands
  5708. axis.plotLinesAndBands = [];
  5709. // Alternate bands
  5710. axis.alternateBands = {};
  5711. // Axis metrics
  5712. //axis.left = UNDEFINED;
  5713. //axis.top = UNDEFINED;
  5714. //axis.width = UNDEFINED;
  5715. //axis.height = UNDEFINED;
  5716. //axis.bottom = UNDEFINED;
  5717. //axis.right = UNDEFINED;
  5718. //axis.transA = UNDEFINED;
  5719. //axis.transB = UNDEFINED;
  5720. //axis.oldTransA = UNDEFINED;
  5721. axis.len = 0;
  5722. //axis.oldMin = UNDEFINED;
  5723. //axis.oldMax = UNDEFINED;
  5724. //axis.oldUserMin = UNDEFINED;
  5725. //axis.oldUserMax = UNDEFINED;
  5726. //axis.oldAxisLength = UNDEFINED;
  5727. axis.minRange = axis.userMinRange = options.minRange || options.maxZoom;
  5728. axis.range = options.range;
  5729. axis.offset = options.offset || 0;
  5730. // Dictionary for stacks
  5731. axis.stacks = {};
  5732. axis._stacksTouched = 0;
  5733. // Min and max in the data
  5734. //axis.dataMin = UNDEFINED,
  5735. //axis.dataMax = UNDEFINED,
  5736. // The axis range
  5737. axis.max = null;
  5738. axis.min = null;
  5739. // User set min and max
  5740. //axis.userMin = UNDEFINED,
  5741. //axis.userMax = UNDEFINED,
  5742. // Run Axis
  5743. var eventType,
  5744. events = axis.options.events;
  5745. // Register
  5746. if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update()
  5747. chart.axes.push(axis);
  5748. chart[isXAxis ? 'xAxis' : 'yAxis'].push(axis);
  5749. }
  5750. axis.series = axis.series || []; // populated by Series
  5751. // inverted charts have reversed xAxes as default
  5752. if (chart.inverted && isXAxis && axis.reversed === UNDEFINED) {
  5753. axis.reversed = true;
  5754. }
  5755. axis.removePlotBand = axis.removePlotBandOrLine;
  5756. axis.removePlotLine = axis.removePlotBandOrLine;
  5757. // register event listeners
  5758. for (eventType in events) {
  5759. addEvent(axis, eventType, events[eventType]);
  5760. }
  5761. // extend logarithmic axis
  5762. if (axis.isLog) {
  5763. axis.val2lin = log2lin;
  5764. axis.lin2val = lin2log;
  5765. }
  5766. },
  5767. /**
  5768. * Merge and set options
  5769. */
  5770. setOptions: function (userOptions) {
  5771. this.options = merge(
  5772. this.defaultOptions,
  5773. this.isXAxis ? {} : this.defaultYAxisOptions,
  5774. [this.defaultTopAxisOptions, this.defaultRightAxisOptions,
  5775. this.defaultBottomAxisOptions, this.defaultLeftAxisOptions][this.side],
  5776. merge(
  5777. defaultOptions[this.isXAxis ? 'xAxis' : 'yAxis'], // if set in setOptions (#1053)
  5778. userOptions
  5779. )
  5780. );
  5781. },
  5782. /**
  5783. * Update the axis with a new options structure
  5784. */
  5785. update: function (newOptions, redraw) {
  5786. var chart = this.chart;
  5787. newOptions = chart.options[this.xOrY + 'Axis'][this.options.index] = merge(this.userOptions, newOptions);
  5788. this.destroy();
  5789. this._addedPlotLB = false; // #1611
  5790. this.init(chart, newOptions);
  5791. chart.isDirtyBox = true;
  5792. if (pick(redraw, true)) {
  5793. chart.redraw();
  5794. }
  5795. },
  5796. /**
  5797. * Remove the axis from the chart
  5798. */
  5799. remove: function (redraw) {
  5800. var chart = this.chart,
  5801. key = this.xOrY + 'Axis'; // xAxis or yAxis
  5802. // Remove associated series
  5803. each(this.series, function (series) {
  5804. series.remove(false);
  5805. });
  5806. // Remove the axis
  5807. erase(chart.axes, this);
  5808. erase(chart[key], this);
  5809. chart.options[key].splice(this.options.index, 1);
  5810. this.destroy();
  5811. chart.isDirtyBox = true;
  5812. if (pick(redraw, true)) {
  5813. chart.redraw();
  5814. }
  5815. },
  5816. /**
  5817. * The default label formatter. The context is a special config object for the label.
  5818. */
  5819. defaultLabelFormatter: function () {
  5820. var axis = this.axis,
  5821. value = this.value,
  5822. categories = axis.categories,
  5823. dateTimeLabelFormat = this.dateTimeLabelFormat,
  5824. numericSymbols = defaultOptions.lang.numericSymbols,
  5825. i = numericSymbols && numericSymbols.length,
  5826. multi,
  5827. ret,
  5828. formatOption = axis.options.labels.format,
  5829. // make sure the same symbol is added for all labels on a linear axis
  5830. numericSymbolDetector = axis.isLog ? value : axis.tickInterval;
  5831. if (formatOption) {
  5832. ret = format(formatOption, this);
  5833. } else if (categories) {
  5834. ret = value;
  5835. } else if (dateTimeLabelFormat) { // datetime axis
  5836. ret = dateFormat(dateTimeLabelFormat, value);
  5837. } else if (i && numericSymbolDetector >= 1000) {
  5838. // Decide whether we should add a numeric symbol like k (thousands) or M (millions).
  5839. // If we are to enable this in tooltip or other places as well, we can move this
  5840. // logic to the numberFormatter and enable it by a parameter.
  5841. while (i-- && ret === UNDEFINED) {
  5842. multi = Math.pow(1000, i + 1);
  5843. if (numericSymbolDetector >= multi && numericSymbols[i] !== null) {
  5844. ret = numberFormat(value / multi, -1) + numericSymbols[i];
  5845. }
  5846. }
  5847. }
  5848. if (ret === UNDEFINED) {
  5849. if (value >= 1000) { // add thousands separators
  5850. ret = numberFormat(value, 0);
  5851. } else { // small numbers
  5852. ret = numberFormat(value, -1);
  5853. }
  5854. }
  5855. return ret;
  5856. },
  5857. /**
  5858. * Get the minimum and maximum for the series of each axis
  5859. */
  5860. getSeriesExtremes: function () {
  5861. var axis = this,
  5862. chart = axis.chart,
  5863. stacks = axis.stacks,
  5864. posStack = [],
  5865. negStack = [],
  5866. stacksTouched = axis._stacksTouched = axis._stacksTouched + 1,
  5867. type,
  5868. i;
  5869. axis.hasVisibleSeries = false;
  5870. // reset dataMin and dataMax in case we're redrawing
  5871. axis.dataMin = axis.dataMax = null;
  5872. // loop through this axis' series
  5873. each(axis.series, function (series) {
  5874. if (series.visible || !chart.options.chart.ignoreHiddenSeries) {
  5875. var seriesOptions = series.options,
  5876. stacking,
  5877. posPointStack,
  5878. negPointStack,
  5879. stackKey,
  5880. stackOption,
  5881. negKey,
  5882. xData,
  5883. yData,
  5884. x,
  5885. y,
  5886. threshold = seriesOptions.threshold,
  5887. yDataLength,
  5888. activeYData = [],
  5889. seriesDataMin,
  5890. seriesDataMax,
  5891. activeCounter = 0;
  5892. axis.hasVisibleSeries = true;
  5893. // Validate threshold in logarithmic axes
  5894. if (axis.isLog && threshold <= 0) {
  5895. threshold = seriesOptions.threshold = null;
  5896. }
  5897. // Get dataMin and dataMax for X axes
  5898. if (axis.isXAxis) {
  5899. xData = series.xData;
  5900. if (xData.length) {
  5901. axis.dataMin = mathMin(pick(axis.dataMin, xData[0]), arrayMin(xData));
  5902. axis.dataMax = mathMax(pick(axis.dataMax, xData[0]), arrayMax(xData));
  5903. }
  5904. // Get dataMin and dataMax for Y axes, as well as handle stacking and processed data
  5905. } else {
  5906. var isNegative,
  5907. pointStack,
  5908. key,
  5909. cropped = series.cropped,
  5910. xExtremes = series.xAxis.getExtremes(),
  5911. //findPointRange,
  5912. //pointRange,
  5913. j,
  5914. hasModifyValue = !!series.modifyValue;
  5915. // Handle stacking
  5916. stacking = seriesOptions.stacking;
  5917. axis.usePercentage = stacking === 'percent';
  5918. // create a stack for this particular series type
  5919. if (stacking) {
  5920. stackOption = seriesOptions.stack;
  5921. stackKey = series.type + pick(stackOption, '');
  5922. negKey = '-' + stackKey;
  5923. series.stackKey = stackKey; // used in translate
  5924. posPointStack = posStack[stackKey] || []; // contains the total values for each x
  5925. posStack[stackKey] = posPointStack;
  5926. negPointStack = negStack[negKey] || [];
  5927. negStack[negKey] = negPointStack;
  5928. }
  5929. if (axis.usePercentage) {
  5930. axis.dataMin = 0;
  5931. axis.dataMax = 99;
  5932. }
  5933. // processData can alter series.pointRange, so this goes after
  5934. //findPointRange = series.pointRange === null;
  5935. xData = series.processedXData;
  5936. yData = series.processedYData;
  5937. yDataLength = yData.length;
  5938. // loop over the non-null y values and read them into a local array
  5939. for (i = 0; i < yDataLength; i++) {
  5940. x = xData[i];
  5941. y = yData[i];
  5942. // Read stacked values into a stack based on the x value,
  5943. // the sign of y and the stack key. Stacking is also handled for null values (#739)
  5944. if (stacking) {
  5945. isNegative = y < threshold;
  5946. pointStack = isNegative ? negPointStack : posPointStack;
  5947. key = isNegative ? negKey : stackKey;
  5948. // Set the stack value and y for extremes
  5949. if (defined(pointStack[x])) { // we're adding to the stack
  5950. pointStack[x] = correctFloat(pointStack[x] + y);
  5951. y = [y, pointStack[x]]; // consider both the actual value and the stack (#1376)
  5952. } else { // it's the first point in the stack
  5953. pointStack[x] = y;
  5954. }
  5955. // add the series
  5956. if (!stacks[key]) {
  5957. stacks[key] = {};
  5958. }
  5959. // If the StackItem is there, just update the values,
  5960. // if not, create one first
  5961. if (!stacks[key][x]) {
  5962. stacks[key][x] = new StackItem(axis, axis.options.stackLabels, isNegative, x, stackOption, stacking);
  5963. }
  5964. stacks[key][x].setTotal(pointStack[x]);
  5965. stacks[key][x].touched = stacksTouched;
  5966. }
  5967. // Handle non null values
  5968. if (y !== null && y !== UNDEFINED && (!axis.isLog || (y.length || y > 0))) {
  5969. // general hook, used for Highstock compare values feature
  5970. if (hasModifyValue) {
  5971. y = series.modifyValue(y);
  5972. }
  5973. // For points within the visible range, including the first point outside the
  5974. // visible range, consider y extremes
  5975. if (series.getExtremesFromAll || cropped || ((xData[i + 1] || x) >= xExtremes.min &&
  5976. (xData[i - 1] || x) <= xExtremes.max)) {
  5977. j = y.length;
  5978. if (j) { // array, like ohlc or range data
  5979. while (j--) {
  5980. if (y[j] !== null) {
  5981. activeYData[activeCounter++] = y[j];
  5982. }
  5983. }
  5984. } else {
  5985. activeYData[activeCounter++] = y;
  5986. }
  5987. }
  5988. }
  5989. }
  5990. // Get the dataMin and dataMax so far. If percentage is used, the min and max are
  5991. // always 0 and 100. If the length of activeYData is 0, continue with null values.
  5992. if (!axis.usePercentage && activeYData.length) {
  5993. series.dataMin = seriesDataMin = arrayMin(activeYData);
  5994. series.dataMax = seriesDataMax = arrayMax(activeYData);
  5995. axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin);
  5996. axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax);
  5997. }
  5998. // Adjust to threshold
  5999. if (defined(threshold)) {
  6000. if (axis.dataMin >= threshold) {
  6001. axis.dataMin = threshold;
  6002. axis.ignoreMinPadding = true;
  6003. } else if (axis.dataMax < threshold) {
  6004. axis.dataMax = threshold;
  6005. axis.ignoreMaxPadding = true;
  6006. }
  6007. }
  6008. }
  6009. }
  6010. });
  6011. // Destroy unused stacks (#1044)
  6012. for (type in stacks) {
  6013. for (i in stacks[type]) {
  6014. if (stacks[type][i].touched < stacksTouched) {
  6015. stacks[type][i].destroy();
  6016. delete stacks[type][i];
  6017. }
  6018. }
  6019. }
  6020. },
  6021. /**
  6022. * Translate from axis value to pixel position on the chart, or back
  6023. *
  6024. */
  6025. translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacementBetween) {
  6026. var axis = this,
  6027. axisLength = axis.len,
  6028. sign = 1,
  6029. cvsOffset = 0,
  6030. localA = old ? axis.oldTransA : axis.transA,
  6031. localMin = old ? axis.oldMin : axis.min,
  6032. returnValue,
  6033. minPixelPadding = axis.minPixelPadding,
  6034. postTranslate = (axis.options.ordinal || (axis.isLog && handleLog)) && axis.lin2val;
  6035. if (!localA) {
  6036. localA = axis.transA;
  6037. }
  6038. // In vertical axes, the canvas coordinates start from 0 at the top like in
  6039. // SVG.
  6040. if (cvsCoord) {
  6041. sign *= -1; // canvas coordinates inverts the value
  6042. cvsOffset = axisLength;
  6043. }
  6044. // Handle reversed axis
  6045. if (axis.reversed) {
  6046. sign *= -1;
  6047. cvsOffset -= sign * axisLength;
  6048. }
  6049. // From pixels to value
  6050. if (backwards) { // reverse translation
  6051. val = val * sign + cvsOffset;
  6052. val -= minPixelPadding;
  6053. returnValue = val / localA + localMin; // from chart pixel to value
  6054. if (postTranslate) { // log and ordinal axes
  6055. returnValue = axis.lin2val(returnValue);
  6056. }
  6057. // From value to pixels
  6058. } else {
  6059. if (postTranslate) { // log and ordinal axes
  6060. val = axis.val2lin(val);
  6061. }
  6062. returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) +
  6063. (pointPlacementBetween ? localA * axis.pointRange / 2 : 0);
  6064. }
  6065. return returnValue;
  6066. },
  6067. /**
  6068. * Utility method to translate an axis value to pixel position.
  6069. * @param {Number} value A value in terms of axis units
  6070. * @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart
  6071. * or just the axis/pane itself.
  6072. */
  6073. toPixels: function (value, paneCoordinates) {
  6074. return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos);
  6075. },
  6076. /*
  6077. * Utility method to translate a pixel position in to an axis value
  6078. * @param {Number} pixel The pixel value coordinate
  6079. * @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the
  6080. * axis/pane itself.
  6081. */
  6082. toValue: function (pixel, paneCoordinates) {
  6083. return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true);
  6084. },
  6085. /**
  6086. * Create the path for a plot line that goes from the given value on
  6087. * this axis, across the plot to the opposite side
  6088. * @param {Number} value
  6089. * @param {Number} lineWidth Used for calculation crisp line
  6090. * @param {Number] old Use old coordinates (for resizing and rescaling)
  6091. */
  6092. getPlotLinePath: function (value, lineWidth, old, force) {
  6093. var axis = this,
  6094. chart = axis.chart,
  6095. axisLeft = axis.left,
  6096. axisTop = axis.top,
  6097. x1,
  6098. y1,
  6099. x2,
  6100. y2,
  6101. translatedValue = axis.translate(value, null, null, old),
  6102. cHeight = (old && chart.oldChartHeight) || chart.chartHeight,
  6103. cWidth = (old && chart.oldChartWidth) || chart.chartWidth,
  6104. skip,
  6105. transB = axis.transB;
  6106. x1 = x2 = mathRound(translatedValue + transB);
  6107. y1 = y2 = mathRound(cHeight - translatedValue - transB);
  6108. if (isNaN(translatedValue)) { // no min or max
  6109. skip = true;
  6110. } else if (axis.horiz) {
  6111. y1 = axisTop;
  6112. y2 = cHeight - axis.bottom;
  6113. if (x1 < axisLeft || x1 > axisLeft + axis.width) {
  6114. skip = true;
  6115. }
  6116. } else {
  6117. x1 = axisLeft;
  6118. x2 = cWidth - axis.right;
  6119. if (y1 < axisTop || y1 > axisTop + axis.height) {
  6120. skip = true;
  6121. }
  6122. }
  6123. return skip && !force ?
  6124. null :
  6125. chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 0);
  6126. },
  6127. /**
  6128. * Create the path for a plot band
  6129. */
  6130. getPlotBandPath: function (from, to) {
  6131. var toPath = this.getPlotLinePath(to),
  6132. path = this.getPlotLinePath(from);
  6133. if (path && toPath) {
  6134. path.push(
  6135. toPath[4],
  6136. toPath[5],
  6137. toPath[1],
  6138. toPath[2]
  6139. );
  6140. } else { // outside the axis area
  6141. path = null;
  6142. }
  6143. return path;
  6144. },
  6145. /**
  6146. * Set the tick positions of a linear axis to round values like whole tens or every five.
  6147. */
  6148. getLinearTickPositions: function (tickInterval, min, max) {
  6149. var pos,
  6150. lastPos,
  6151. roundedMin = correctFloat(mathFloor(min / tickInterval) * tickInterval),
  6152. roundedMax = correctFloat(mathCeil(max / tickInterval) * tickInterval),
  6153. tickPositions = [];
  6154. // Populate the intermediate values
  6155. pos = roundedMin;
  6156. while (pos <= roundedMax) {
  6157. // Place the tick on the rounded value
  6158. tickPositions.push(pos);
  6159. // Always add the raw tickInterval, not the corrected one.
  6160. pos = correctFloat(pos + tickInterval);
  6161. // If the interval is not big enough in the current min - max range to actually increase
  6162. // the loop variable, we need to break out to prevent endless loop. Issue #619
  6163. if (pos === lastPos) {
  6164. break;
  6165. }
  6166. // Record the last value
  6167. lastPos = pos;
  6168. }
  6169. return tickPositions;
  6170. },
  6171. /**
  6172. * Set the tick positions of a logarithmic axis
  6173. */
  6174. getLogTickPositions: function (interval, min, max, minor) {
  6175. var axis = this,
  6176. options = axis.options,
  6177. axisLength = axis.len,
  6178. // Since we use this method for both major and minor ticks,
  6179. // use a local variable and return the result
  6180. positions = [];
  6181. // Reset
  6182. if (!minor) {
  6183. axis._minorAutoInterval = null;
  6184. }
  6185. // First case: All ticks fall on whole logarithms: 1, 10, 100 etc.
  6186. if (interval >= 0.5) {
  6187. interval = mathRound(interval);
  6188. positions = axis.getLinearTickPositions(interval, min, max);
  6189. // Second case: We need intermediary ticks. For example
  6190. // 1, 2, 4, 6, 8, 10, 20, 40 etc.
  6191. } else if (interval >= 0.08) {
  6192. var roundedMin = mathFloor(min),
  6193. intermediate,
  6194. i,
  6195. j,
  6196. len,
  6197. pos,
  6198. lastPos,
  6199. break2;
  6200. if (interval > 0.3) {
  6201. intermediate = [1, 2, 4];
  6202. } else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc
  6203. intermediate = [1, 2, 4, 6, 8];
  6204. } else { // 0.1 equals ten minor ticks per 1, 10, 100 etc
  6205. intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  6206. }
  6207. for (i = roundedMin; i < max + 1 && !break2; i++) {
  6208. len = intermediate.length;
  6209. for (j = 0; j < len && !break2; j++) {
  6210. pos = log2lin(lin2log(i) * intermediate[j]);
  6211. if (pos > min && (!minor || lastPos <= max)) { // #1670
  6212. positions.push(lastPos);
  6213. }
  6214. if (lastPos > max) {
  6215. break2 = true;
  6216. }
  6217. lastPos = pos;
  6218. }
  6219. }
  6220. // Third case: We are so deep in between whole logarithmic values that
  6221. // we might as well handle the tick positions like a linear axis. For
  6222. // example 1.01, 1.02, 1.03, 1.04.
  6223. } else {
  6224. var realMin = lin2log(min),
  6225. realMax = lin2log(max),
  6226. tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'],
  6227. filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption,
  6228. tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1),
  6229. totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength;
  6230. interval = pick(
  6231. filteredTickIntervalOption,
  6232. axis._minorAutoInterval,
  6233. (realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1)
  6234. );
  6235. interval = normalizeTickInterval(
  6236. interval,
  6237. null,
  6238. math.pow(10, mathFloor(math.log(interval) / math.LN10))
  6239. );
  6240. positions = map(axis.getLinearTickPositions(
  6241. interval,
  6242. realMin,
  6243. realMax
  6244. ), log2lin);
  6245. if (!minor) {
  6246. axis._minorAutoInterval = interval / 5;
  6247. }
  6248. }
  6249. // Set the axis-level tickInterval variable
  6250. if (!minor) {
  6251. axis.tickInterval = interval;
  6252. }
  6253. return positions;
  6254. },
  6255. /**
  6256. * Return the minor tick positions. For logarithmic axes, reuse the same logic
  6257. * as for major ticks.
  6258. */
  6259. getMinorTickPositions: function () {
  6260. var axis = this,
  6261. options = axis.options,
  6262. tickPositions = axis.tickPositions,
  6263. minorTickInterval = axis.minorTickInterval,
  6264. minorTickPositions = [],
  6265. pos,
  6266. i,
  6267. len;
  6268. if (axis.isLog) {
  6269. len = tickPositions.length;
  6270. for (i = 1; i < len; i++) {
  6271. minorTickPositions = minorTickPositions.concat(
  6272. axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true)
  6273. );
  6274. }
  6275. } else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314
  6276. minorTickPositions = minorTickPositions.concat(
  6277. getTimeTicks(
  6278. normalizeTimeTickInterval(minorTickInterval),
  6279. axis.min,
  6280. axis.max,
  6281. options.startOfWeek
  6282. )
  6283. );
  6284. if (minorTickPositions[0] < axis.min) {
  6285. minorTickPositions.shift();
  6286. }
  6287. } else {
  6288. for (pos = axis.min + (tickPositions[0] - axis.min) % minorTickInterval; pos <= axis.max; pos += minorTickInterval) {
  6289. minorTickPositions.push(pos);
  6290. }
  6291. }
  6292. return minorTickPositions;
  6293. },
  6294. /**
  6295. * Adjust the min and max for the minimum range. Keep in mind that the series data is
  6296. * not yet processed, so we don't have information on data cropping and grouping, or
  6297. * updated axis.pointRange or series.pointRange. The data can't be processed until
  6298. * we have finally established min and max.
  6299. */
  6300. adjustForMinRange: function () {
  6301. var axis = this,
  6302. options = axis.options,
  6303. min = axis.min,
  6304. max = axis.max,
  6305. zoomOffset,
  6306. spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange,
  6307. closestDataRange,
  6308. i,
  6309. distance,
  6310. xData,
  6311. loopLength,
  6312. minArgs,
  6313. maxArgs;
  6314. // Set the automatic minimum range based on the closest point distance
  6315. if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) {
  6316. if (defined(options.min) || defined(options.max)) {
  6317. axis.minRange = null; // don't do this again
  6318. } else {
  6319. // Find the closest distance between raw data points, as opposed to
  6320. // closestPointRange that applies to processed points (cropped and grouped)
  6321. each(axis.series, function (series) {
  6322. xData = series.xData;
  6323. loopLength = series.xIncrement ? 1 : xData.length - 1;
  6324. for (i = loopLength; i > 0; i--) {
  6325. distance = xData[i] - xData[i - 1];
  6326. if (closestDataRange === UNDEFINED || distance < closestDataRange) {
  6327. closestDataRange = distance;
  6328. }
  6329. }
  6330. });
  6331. axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin);
  6332. }
  6333. }
  6334. // if minRange is exceeded, adjust
  6335. if (max - min < axis.minRange) {
  6336. var minRange = axis.minRange;
  6337. zoomOffset = (minRange - max + min) / 2;
  6338. // if min and max options have been set, don't go beyond it
  6339. minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)];
  6340. if (spaceAvailable) { // if space is available, stay within the data range
  6341. minArgs[2] = axis.dataMin;
  6342. }
  6343. min = arrayMax(minArgs);
  6344. maxArgs = [min + minRange, pick(options.max, min + minRange)];
  6345. if (spaceAvailable) { // if space is availabe, stay within the data range
  6346. maxArgs[2] = axis.dataMax;
  6347. }
  6348. max = arrayMin(maxArgs);
  6349. // now if the max is adjusted, adjust the min back
  6350. if (max - min < minRange) {
  6351. minArgs[0] = max - minRange;
  6352. minArgs[1] = pick(options.min, max - minRange);
  6353. min = arrayMax(minArgs);
  6354. }
  6355. }
  6356. // Record modified extremes
  6357. axis.min = min;
  6358. axis.max = max;
  6359. },
  6360. /**
  6361. * Update translation information
  6362. */
  6363. setAxisTranslation: function (saveOld) {
  6364. var axis = this,
  6365. range = axis.max - axis.min,
  6366. pointRange = 0,
  6367. closestPointRange,
  6368. minPointOffset = 0,
  6369. pointRangePadding = 0,
  6370. linkedParent = axis.linkedParent,
  6371. ordinalCorrection,
  6372. transA = axis.transA;
  6373. // adjust translation for padding
  6374. if (axis.isXAxis) {
  6375. if (linkedParent) {
  6376. minPointOffset = linkedParent.minPointOffset;
  6377. pointRangePadding = linkedParent.pointRangePadding;
  6378. } else {
  6379. each(axis.series, function (series) {
  6380. var seriesPointRange = series.pointRange,
  6381. pointPlacement = series.options.pointPlacement,
  6382. seriesClosestPointRange = series.closestPointRange;
  6383. if (seriesPointRange > range) { // #1446
  6384. seriesPointRange = 0;
  6385. }
  6386. pointRange = mathMax(pointRange, seriesPointRange);
  6387. // minPointOffset is the value padding to the left of the axis in order to make
  6388. // room for points with a pointRange, typically columns. When the pointPlacement option
  6389. // is 'between' or 'on', this padding does not apply.
  6390. minPointOffset = mathMax(
  6391. minPointOffset,
  6392. pointPlacement ? 0 : seriesPointRange / 2
  6393. );
  6394. // Determine the total padding needed to the length of the axis to make room for the
  6395. // pointRange. If the series' pointPlacement is 'on', no padding is added.
  6396. pointRangePadding = mathMax(
  6397. pointRangePadding,
  6398. pointPlacement === 'on' ? 0 : seriesPointRange
  6399. );
  6400. // Set the closestPointRange
  6401. if (!series.noSharedTooltip && defined(seriesClosestPointRange)) {
  6402. closestPointRange = defined(closestPointRange) ?
  6403. mathMin(closestPointRange, seriesClosestPointRange) :
  6404. seriesClosestPointRange;
  6405. }
  6406. });
  6407. }
  6408. // Record minPointOffset and pointRangePadding
  6409. ordinalCorrection = axis.ordinalSlope ? axis.ordinalSlope / closestPointRange : 1; // #988
  6410. axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection;
  6411. axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection;
  6412. // pointRange means the width reserved for each point, like in a column chart
  6413. axis.pointRange = mathMin(pointRange, range);
  6414. // closestPointRange means the closest distance between points. In columns
  6415. // it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange
  6416. // is some other value
  6417. axis.closestPointRange = closestPointRange;
  6418. }
  6419. // Secondary values
  6420. if (saveOld) {
  6421. axis.oldTransA = transA;
  6422. }
  6423. axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1);
  6424. axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend
  6425. axis.minPixelPadding = transA * minPointOffset;
  6426. },
  6427. /**
  6428. * Set the tick positions to round values and optionally extend the extremes
  6429. * to the nearest tick
  6430. */
  6431. setTickPositions: function (secondPass) {
  6432. var axis = this,
  6433. chart = axis.chart,
  6434. options = axis.options,
  6435. isLog = axis.isLog,
  6436. isDatetimeAxis = axis.isDatetimeAxis,
  6437. isXAxis = axis.isXAxis,
  6438. isLinked = axis.isLinked,
  6439. tickPositioner = axis.options.tickPositioner,
  6440. magnitude,
  6441. maxPadding = options.maxPadding,
  6442. minPadding = options.minPadding,
  6443. length,
  6444. linkedParentExtremes,
  6445. tickIntervalOption = options.tickInterval,
  6446. minTickIntervalOption = options.minTickInterval,
  6447. tickPixelIntervalOption = options.tickPixelInterval,
  6448. tickPositions,
  6449. categories = axis.categories;
  6450. // linked axis gets the extremes from the parent axis
  6451. if (isLinked) {
  6452. axis.linkedParent = chart[isXAxis ? 'xAxis' : 'yAxis'][options.linkedTo];
  6453. linkedParentExtremes = axis.linkedParent.getExtremes();
  6454. axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin);
  6455. axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax);
  6456. if (options.type !== axis.linkedParent.options.type) {
  6457. error(11, 1); // Can't link axes of different type
  6458. }
  6459. } else { // initial min and max from the extreme data values
  6460. axis.min = pick(axis.userMin, options.min, axis.dataMin);
  6461. axis.max = pick(axis.userMax, options.max, axis.dataMax);
  6462. }
  6463. if (isLog) {
  6464. if (!secondPass && mathMin(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978
  6465. error(10, 1); // Can't plot negative values on log axis
  6466. }
  6467. axis.min = correctFloat(log2lin(axis.min)); // correctFloat cures #934
  6468. axis.max = correctFloat(log2lin(axis.max));
  6469. }
  6470. // handle zoomed range
  6471. if (axis.range) {
  6472. axis.userMin = axis.min = mathMax(axis.min, axis.max - axis.range); // #618
  6473. axis.userMax = axis.max;
  6474. if (secondPass) {
  6475. axis.range = null; // don't use it when running setExtremes
  6476. }
  6477. }
  6478. // Hook for adjusting this.min and this.max. Used by bubble series.
  6479. if (axis.beforePadding) {
  6480. axis.beforePadding();
  6481. }
  6482. // adjust min and max for the minimum range
  6483. axis.adjustForMinRange();
  6484. // Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding
  6485. // into account, we do this after computing tick interval (#1337).
  6486. if (!categories && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) {
  6487. length = axis.max - axis.min;
  6488. if (length) {
  6489. if (!defined(options.min) && !defined(axis.userMin) && minPadding && (axis.dataMin < 0 || !axis.ignoreMinPadding)) {
  6490. axis.min -= length * minPadding;
  6491. }
  6492. if (!defined(options.max) && !defined(axis.userMax) && maxPadding && (axis.dataMax > 0 || !axis.ignoreMaxPadding)) {
  6493. axis.max += length * maxPadding;
  6494. }
  6495. }
  6496. }
  6497. // get tickInterval
  6498. if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) {
  6499. axis.tickInterval = 1;
  6500. } else if (isLinked && !tickIntervalOption &&
  6501. tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) {
  6502. axis.tickInterval = axis.linkedParent.tickInterval;
  6503. } else {
  6504. axis.tickInterval = pick(
  6505. tickIntervalOption,
  6506. categories ? // for categoried axis, 1 is default, for linear axis use tickPix
  6507. 1 :
  6508. (axis.max - axis.min) * tickPixelIntervalOption / (axis.len || 1)
  6509. );
  6510. }
  6511. // Now we're finished detecting min and max, crop and group series data. This
  6512. // is in turn needed in order to find tick positions in ordinal axes.
  6513. if (isXAxis && !secondPass) {
  6514. each(axis.series, function (series) {
  6515. series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax);
  6516. });
  6517. }
  6518. // set the translation factor used in translate function
  6519. axis.setAxisTranslation(true);
  6520. // hook for ordinal axes and radial axes
  6521. if (axis.beforeSetTickPositions) {
  6522. axis.beforeSetTickPositions();
  6523. }
  6524. // hook for extensions, used in Highstock ordinal axes
  6525. if (axis.postProcessTickInterval) {
  6526. axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval);
  6527. }
  6528. // Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined.
  6529. if (!tickIntervalOption && axis.tickInterval < minTickIntervalOption) {
  6530. axis.tickInterval = minTickIntervalOption;
  6531. }
  6532. // for linear axes, get magnitude and normalize the interval
  6533. if (!isDatetimeAxis && !isLog) { // linear
  6534. magnitude = math.pow(10, mathFloor(math.log(axis.tickInterval) / math.LN10));
  6535. if (!tickIntervalOption) {
  6536. axis.tickInterval = normalizeTickInterval(axis.tickInterval, null, magnitude, options);
  6537. }
  6538. }
  6539. // get minorTickInterval
  6540. axis.minorTickInterval = options.minorTickInterval === 'auto' && axis.tickInterval ?
  6541. axis.tickInterval / 5 : options.minorTickInterval;
  6542. // find the tick positions
  6543. axis.tickPositions = tickPositions = options.tickPositions ?
  6544. [].concat(options.tickPositions) : // Work on a copy (#1565)
  6545. (tickPositioner && tickPositioner.apply(axis, [axis.min, axis.max]));
  6546. if (!tickPositions) {
  6547. if (isDatetimeAxis) {
  6548. tickPositions = (axis.getNonLinearTimeTicks || getTimeTicks)(
  6549. normalizeTimeTickInterval(axis.tickInterval, options.units),
  6550. axis.min,
  6551. axis.max,
  6552. options.startOfWeek,
  6553. axis.ordinalPositions,
  6554. axis.closestPointRange,
  6555. true
  6556. );
  6557. } else if (isLog) {
  6558. tickPositions = axis.getLogTickPositions(axis.tickInterval, axis.min, axis.max);
  6559. } else {
  6560. tickPositions = axis.getLinearTickPositions(axis.tickInterval, axis.min, axis.max);
  6561. }
  6562. axis.tickPositions = tickPositions;
  6563. }
  6564. if (!isLinked) {
  6565. // reset min/max or remove extremes based on start/end on tick
  6566. var roundedMin = tickPositions[0],
  6567. roundedMax = tickPositions[tickPositions.length - 1],
  6568. minPointOffset = axis.minPointOffset || 0,
  6569. singlePad;
  6570. if (options.startOnTick) {
  6571. axis.min = roundedMin;
  6572. } else if (axis.min - minPointOffset > roundedMin) {
  6573. tickPositions.shift();
  6574. }
  6575. if (options.endOnTick) {
  6576. axis.max = roundedMax;
  6577. } else if (axis.max + minPointOffset < roundedMax) {
  6578. tickPositions.pop();
  6579. }
  6580. // When there is only one point, or all points have the same value on this axis, then min
  6581. // and max are equal and tickPositions.length is 1. In this case, add some padding
  6582. // in order to center the point, but leave it with one tick. #1337.
  6583. if (tickPositions.length === 1) {
  6584. singlePad = 0.001; // The lowest possible number to avoid extra padding on columns
  6585. axis.min -= singlePad;
  6586. axis.max += singlePad;
  6587. }
  6588. }
  6589. },
  6590. /**
  6591. * Set the max ticks of either the x and y axis collection
  6592. */
  6593. setMaxTicks: function () {
  6594. var chart = this.chart,
  6595. maxTicks = chart.maxTicks || {},
  6596. tickPositions = this.tickPositions,
  6597. key = this._maxTicksKey = [this.xOrY, this.pos, this.len].join('-');
  6598. if (!this.isLinked && !this.isDatetimeAxis && tickPositions && tickPositions.length > (maxTicks[key] || 0) && this.options.alignTicks !== false) {
  6599. maxTicks[key] = tickPositions.length;
  6600. }
  6601. chart.maxTicks = maxTicks;
  6602. },
  6603. /**
  6604. * When using multiple axes, adjust the number of ticks to match the highest
  6605. * number of ticks in that group
  6606. */
  6607. adjustTickAmount: function () {
  6608. var axis = this,
  6609. chart = axis.chart,
  6610. key = axis._maxTicksKey,
  6611. tickPositions = axis.tickPositions,
  6612. maxTicks = chart.maxTicks;
  6613. if (maxTicks && maxTicks[key] && !axis.isDatetimeAxis && !axis.categories && !axis.isLinked && axis.options.alignTicks !== false) { // only apply to linear scale
  6614. var oldTickAmount = axis.tickAmount,
  6615. calculatedTickAmount = tickPositions.length,
  6616. tickAmount;
  6617. // set the axis-level tickAmount to use below
  6618. axis.tickAmount = tickAmount = maxTicks[key];
  6619. if (calculatedTickAmount < tickAmount) {
  6620. while (tickPositions.length < tickAmount) {
  6621. tickPositions.push(correctFloat(
  6622. tickPositions[tickPositions.length - 1] + axis.tickInterval
  6623. ));
  6624. }
  6625. axis.transA *= (calculatedTickAmount - 1) / (tickAmount - 1);
  6626. axis.max = tickPositions[tickPositions.length - 1];
  6627. }
  6628. if (defined(oldTickAmount) && tickAmount !== oldTickAmount) {
  6629. axis.isDirty = true;
  6630. }
  6631. }
  6632. },
  6633. /**
  6634. * Set the scale based on data min and max, user set min and max or options
  6635. *
  6636. */
  6637. setScale: function () {
  6638. var axis = this,
  6639. stacks = axis.stacks,
  6640. type,
  6641. i,
  6642. isDirtyData,
  6643. isDirtyAxisLength;
  6644. axis.oldMin = axis.min;
  6645. axis.oldMax = axis.max;
  6646. axis.oldAxisLength = axis.len;
  6647. // set the new axisLength
  6648. axis.setAxisSize();
  6649. //axisLength = horiz ? axisWidth : axisHeight;
  6650. isDirtyAxisLength = axis.len !== axis.oldAxisLength;
  6651. // is there new data?
  6652. each(axis.series, function (series) {
  6653. if (series.isDirtyData || series.isDirty ||
  6654. series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well
  6655. isDirtyData = true;
  6656. }
  6657. });
  6658. // do we really need to go through all this?
  6659. if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw ||
  6660. axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax) {
  6661. axis.forceRedraw = false;
  6662. // get data extremes if needed
  6663. axis.getSeriesExtremes();
  6664. // get fixed positions based on tickInterval
  6665. axis.setTickPositions();
  6666. // record old values to decide whether a rescale is necessary later on (#540)
  6667. axis.oldUserMin = axis.userMin;
  6668. axis.oldUserMax = axis.userMax;
  6669. // Mark as dirty if it is not already set to dirty and extremes have changed. #595.
  6670. if (!axis.isDirty) {
  6671. axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax;
  6672. }
  6673. }
  6674. // reset stacks
  6675. if (!axis.isXAxis) {
  6676. for (type in stacks) {
  6677. for (i in stacks[type]) {
  6678. stacks[type][i].cum = stacks[type][i].total;
  6679. }
  6680. }
  6681. }
  6682. // Set the maximum tick amount
  6683. axis.setMaxTicks();
  6684. },
  6685. /**
  6686. * Set the extremes and optionally redraw
  6687. * @param {Number} newMin
  6688. * @param {Number} newMax
  6689. * @param {Boolean} redraw
  6690. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  6691. * configuration
  6692. * @param {Object} eventArguments
  6693. *
  6694. */
  6695. setExtremes: function (newMin, newMax, redraw, animation, eventArguments) {
  6696. var axis = this,
  6697. chart = axis.chart;
  6698. redraw = pick(redraw, true); // defaults to true
  6699. // Extend the arguments with min and max
  6700. eventArguments = extend(eventArguments, {
  6701. min: newMin,
  6702. max: newMax
  6703. });
  6704. // Fire the event
  6705. fireEvent(axis, 'setExtremes', eventArguments, function () { // the default event handler
  6706. axis.userMin = newMin;
  6707. axis.userMax = newMax;
  6708. // Mark for running afterSetExtremes
  6709. axis.isDirtyExtremes = true;
  6710. // redraw
  6711. if (redraw) {
  6712. chart.redraw(animation);
  6713. }
  6714. });
  6715. },
  6716. /**
  6717. * Overridable method for zooming chart. Pulled out in a separate method to allow overriding
  6718. * in stock charts.
  6719. */
  6720. zoom: function (newMin, newMax) {
  6721. // Prevent pinch zooming out of range
  6722. if (!this.allowZoomOutside) {
  6723. if (newMin <= this.dataMin) {
  6724. newMin = UNDEFINED;
  6725. }
  6726. if (newMax >= this.dataMax) {
  6727. newMax = UNDEFINED;
  6728. }
  6729. }
  6730. // In full view, displaying the reset zoom button is not required
  6731. this.displayBtn = newMin !== UNDEFINED || newMax !== UNDEFINED;
  6732. // Do it
  6733. this.setExtremes(
  6734. newMin,
  6735. newMax,
  6736. false,
  6737. UNDEFINED,
  6738. { trigger: 'zoom' }
  6739. );
  6740. return true;
  6741. },
  6742. /**
  6743. * Update the axis metrics
  6744. */
  6745. setAxisSize: function () {
  6746. var chart = this.chart,
  6747. options = this.options,
  6748. offsetLeft = options.offsetLeft || 0,
  6749. offsetRight = options.offsetRight || 0,
  6750. horiz = this.horiz,
  6751. width,
  6752. height,
  6753. top,
  6754. left;
  6755. // Expose basic values to use in Series object and navigator
  6756. this.left = left = pick(options.left, chart.plotLeft + offsetLeft);
  6757. this.top = top = pick(options.top, chart.plotTop);
  6758. this.width = width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight);
  6759. this.height = height = pick(options.height, chart.plotHeight);
  6760. this.bottom = chart.chartHeight - height - top;
  6761. this.right = chart.chartWidth - width - left;
  6762. // Direction agnostic properties
  6763. this.len = mathMax(horiz ? width : height, 0); // mathMax fixes #905
  6764. this.pos = horiz ? left : top; // distance from SVG origin
  6765. },
  6766. /**
  6767. * Get the actual axis extremes
  6768. */
  6769. getExtremes: function () {
  6770. var axis = this,
  6771. isLog = axis.isLog;
  6772. return {
  6773. min: isLog ? correctFloat(lin2log(axis.min)) : axis.min,
  6774. max: isLog ? correctFloat(lin2log(axis.max)) : axis.max,
  6775. dataMin: axis.dataMin,
  6776. dataMax: axis.dataMax,
  6777. userMin: axis.userMin,
  6778. userMax: axis.userMax
  6779. };
  6780. },
  6781. /**
  6782. * Get the zero plane either based on zero or on the min or max value.
  6783. * Used in bar and area plots
  6784. */
  6785. getThreshold: function (threshold) {
  6786. var axis = this,
  6787. isLog = axis.isLog;
  6788. var realMin = isLog ? lin2log(axis.min) : axis.min,
  6789. realMax = isLog ? lin2log(axis.max) : axis.max;
  6790. if (realMin > threshold || threshold === null) {
  6791. threshold = realMin;
  6792. } else if (realMax < threshold) {
  6793. threshold = realMax;
  6794. }
  6795. return axis.translate(threshold, 0, 1, 0, 1);
  6796. },
  6797. addPlotBand: function (options) {
  6798. this.addPlotBandOrLine(options, 'plotBands');
  6799. },
  6800. addPlotLine: function (options) {
  6801. this.addPlotBandOrLine(options, 'plotLines');
  6802. },
  6803. /**
  6804. * Add a plot band or plot line after render time
  6805. *
  6806. * @param options {Object} The plotBand or plotLine configuration object
  6807. */
  6808. addPlotBandOrLine: function (options, coll) {
  6809. var obj = new PlotLineOrBand(this, options).render(),
  6810. userOptions = this.userOptions;
  6811. // Add it to the user options for exporting and Axis.update
  6812. if (coll) {
  6813. userOptions[coll] = userOptions[coll] || [];
  6814. userOptions[coll].push(options);
  6815. }
  6816. this.plotLinesAndBands.push(obj);
  6817. return obj;
  6818. },
  6819. /**
  6820. * Render the tick labels to a preliminary position to get their sizes
  6821. */
  6822. getOffset: function () {
  6823. var axis = this,
  6824. chart = axis.chart,
  6825. renderer = chart.renderer,
  6826. options = axis.options,
  6827. tickPositions = axis.tickPositions,
  6828. ticks = axis.ticks,
  6829. horiz = axis.horiz,
  6830. side = axis.side,
  6831. invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side,
  6832. hasData,
  6833. showAxis,
  6834. titleOffset = 0,
  6835. titleOffsetOption,
  6836. titleMargin = 0,
  6837. axisTitleOptions = options.title,
  6838. labelOptions = options.labels,
  6839. labelOffset = 0, // reset
  6840. axisOffset = chart.axisOffset,
  6841. clipOffset = chart.clipOffset,
  6842. directionFactor = [-1, 1, 1, -1][side],
  6843. n;
  6844. // For reuse in Axis.render
  6845. axis.hasData = hasData = (axis.hasVisibleSeries || (defined(axis.min) && defined(axis.max) && !!tickPositions));
  6846. axis.showAxis = showAxis = hasData || pick(options.showEmpty, true);
  6847. // Create the axisGroup and gridGroup elements on first iteration
  6848. if (!axis.axisGroup) {
  6849. axis.gridGroup = renderer.g('grid')
  6850. .attr({ zIndex: options.gridZIndex || 1 })
  6851. .add();
  6852. axis.axisGroup = renderer.g('axis')
  6853. .attr({ zIndex: options.zIndex || 2 })
  6854. .add();
  6855. axis.labelGroup = renderer.g('axis-labels')
  6856. .attr({ zIndex: labelOptions.zIndex || 7 })
  6857. .add();
  6858. }
  6859. if (hasData || axis.isLinked) {
  6860. each(tickPositions, function (pos) {
  6861. if (!ticks[pos]) {
  6862. ticks[pos] = new Tick(axis, pos);
  6863. } else {
  6864. ticks[pos].addLabel(); // update labels depending on tick interval
  6865. }
  6866. });
  6867. each(tickPositions, function (pos) {
  6868. // left side must be align: right and right side must have align: left for labels
  6869. if (side === 0 || side === 2 || { 1: 'left', 3: 'right' }[side] === labelOptions.align) {
  6870. // get the highest offset
  6871. labelOffset = mathMax(
  6872. ticks[pos].getLabelSize(),
  6873. labelOffset
  6874. );
  6875. }
  6876. });
  6877. if (axis.staggerLines) {
  6878. labelOffset += (axis.staggerLines - 1) * 16;
  6879. }
  6880. } else { // doesn't have data
  6881. for (n in ticks) {
  6882. ticks[n].destroy();
  6883. delete ticks[n];
  6884. }
  6885. }
  6886. if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) {
  6887. if (!axis.axisTitle) {
  6888. axis.axisTitle = renderer.text(
  6889. axisTitleOptions.text,
  6890. 0,
  6891. 0,
  6892. axisTitleOptions.useHTML
  6893. )
  6894. .attr({
  6895. zIndex: 7,
  6896. rotation: axisTitleOptions.rotation || 0,
  6897. align:
  6898. axisTitleOptions.textAlign ||
  6899. { low: 'left', middle: 'center', high: 'right' }[axisTitleOptions.align]
  6900. })
  6901. .css(axisTitleOptions.style)
  6902. .add(axis.axisGroup);
  6903. axis.axisTitle.isNew = true;
  6904. }
  6905. if (showAxis) {
  6906. titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width'];
  6907. titleMargin = pick(axisTitleOptions.margin, horiz ? 5 : 10);
  6908. titleOffsetOption = axisTitleOptions.offset;
  6909. }
  6910. // hide or show the title depending on whether showEmpty is set
  6911. axis.axisTitle[showAxis ? 'show' : 'hide']();
  6912. }
  6913. // handle automatic or user set offset
  6914. axis.offset = directionFactor * pick(options.offset, axisOffset[side]);
  6915. axis.axisTitleMargin =
  6916. pick(titleOffsetOption,
  6917. labelOffset + titleMargin +
  6918. (side !== 2 && labelOffset && directionFactor * options.labels[horiz ? 'y' : 'x'])
  6919. );
  6920. axisOffset[side] = mathMax(
  6921. axisOffset[side],
  6922. axis.axisTitleMargin + titleOffset + directionFactor * axis.offset
  6923. );
  6924. clipOffset[invertedSide] = mathMax(clipOffset[invertedSide], options.lineWidth);
  6925. },
  6926. /**
  6927. * Get the path for the axis line
  6928. */
  6929. getLinePath: function (lineWidth) {
  6930. var chart = this.chart,
  6931. opposite = this.opposite,
  6932. offset = this.offset,
  6933. horiz = this.horiz,
  6934. lineLeft = this.left + (opposite ? this.width : 0) + offset,
  6935. lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset;
  6936. this.lineTop = lineTop; // used by flag series
  6937. if (!opposite) {
  6938. lineWidth *= -1; // crispify the other way - #1480
  6939. }
  6940. return chart.renderer.crispLine([
  6941. M,
  6942. horiz ?
  6943. this.left :
  6944. lineLeft,
  6945. horiz ?
  6946. lineTop :
  6947. this.top,
  6948. L,
  6949. horiz ?
  6950. chart.chartWidth - this.right :
  6951. lineLeft,
  6952. horiz ?
  6953. lineTop :
  6954. chart.chartHeight - this.bottom
  6955. ], lineWidth);
  6956. },
  6957. /**
  6958. * Position the title
  6959. */
  6960. getTitlePosition: function () {
  6961. // compute anchor points for each of the title align options
  6962. var horiz = this.horiz,
  6963. axisLeft = this.left,
  6964. axisTop = this.top,
  6965. axisLength = this.len,
  6966. axisTitleOptions = this.options.title,
  6967. margin = horiz ? axisLeft : axisTop,
  6968. opposite = this.opposite,
  6969. offset = this.offset,
  6970. fontSize = pInt(axisTitleOptions.style.fontSize || 12),
  6971. // the position in the length direction of the axis
  6972. alongAxis = {
  6973. low: margin + (horiz ? 0 : axisLength),
  6974. middle: margin + axisLength / 2,
  6975. high: margin + (horiz ? axisLength : 0)
  6976. }[axisTitleOptions.align],
  6977. // the position in the perpendicular direction of the axis
  6978. offAxis = (horiz ? axisTop + this.height : axisLeft) +
  6979. (horiz ? 1 : -1) * // horizontal axis reverses the margin
  6980. (opposite ? -1 : 1) * // so does opposite axes
  6981. this.axisTitleMargin +
  6982. (this.side === 2 ? fontSize : 0);
  6983. return {
  6984. x: horiz ?
  6985. alongAxis :
  6986. offAxis + (opposite ? this.width : 0) + offset +
  6987. (axisTitleOptions.x || 0), // x
  6988. y: horiz ?
  6989. offAxis - (opposite ? this.height : 0) + offset :
  6990. alongAxis + (axisTitleOptions.y || 0) // y
  6991. };
  6992. },
  6993. /**
  6994. * Render the axis
  6995. */
  6996. render: function () {
  6997. var axis = this,
  6998. chart = axis.chart,
  6999. renderer = chart.renderer,
  7000. options = axis.options,
  7001. isLog = axis.isLog,
  7002. isLinked = axis.isLinked,
  7003. tickPositions = axis.tickPositions,
  7004. axisTitle = axis.axisTitle,
  7005. stacks = axis.stacks,
  7006. ticks = axis.ticks,
  7007. minorTicks = axis.minorTicks,
  7008. alternateBands = axis.alternateBands,
  7009. stackLabelOptions = options.stackLabels,
  7010. alternateGridColor = options.alternateGridColor,
  7011. tickmarkOffset = axis.tickmarkOffset,
  7012. lineWidth = options.lineWidth,
  7013. linePath,
  7014. hasRendered = chart.hasRendered,
  7015. slideInTicks = hasRendered && defined(axis.oldMin) && !isNaN(axis.oldMin),
  7016. hasData = axis.hasData,
  7017. showAxis = axis.showAxis,
  7018. from,
  7019. to;
  7020. // Mark all elements inActive before we go over and mark the active ones
  7021. each([ticks, minorTicks, alternateBands], function (coll) {
  7022. var pos;
  7023. for (pos in coll) {
  7024. coll[pos].isActive = false;
  7025. }
  7026. });
  7027. // If the series has data draw the ticks. Else only the line and title
  7028. if (hasData || isLinked) {
  7029. // minor ticks
  7030. if (axis.minorTickInterval && !axis.categories) {
  7031. each(axis.getMinorTickPositions(), function (pos) {
  7032. if (!minorTicks[pos]) {
  7033. minorTicks[pos] = new Tick(axis, pos, 'minor');
  7034. }
  7035. // render new ticks in old position
  7036. if (slideInTicks && minorTicks[pos].isNew) {
  7037. minorTicks[pos].render(null, true);
  7038. }
  7039. minorTicks[pos].render(null, false, 1);
  7040. });
  7041. }
  7042. // Major ticks. Pull out the first item and render it last so that
  7043. // we can get the position of the neighbour label. #808.
  7044. if (tickPositions.length) { // #1300
  7045. each(tickPositions.slice(1).concat([tickPositions[0]]), function (pos, i) {
  7046. // Reorganize the indices
  7047. i = (i === tickPositions.length - 1) ? 0 : i + 1;
  7048. // linked axes need an extra check to find out if
  7049. if (!isLinked || (pos >= axis.min && pos <= axis.max)) {
  7050. if (!ticks[pos]) {
  7051. ticks[pos] = new Tick(axis, pos);
  7052. }
  7053. // render new ticks in old position
  7054. if (slideInTicks && ticks[pos].isNew) {
  7055. ticks[pos].render(i, true);
  7056. }
  7057. ticks[pos].render(i, false, 1);
  7058. }
  7059. });
  7060. // In a categorized axis, the tick marks are displayed between labels. So
  7061. // we need to add a tick mark and grid line at the left edge of the X axis.
  7062. if (tickmarkOffset && axis.min === 0) {
  7063. if (!ticks[-1]) {
  7064. ticks[-1] = new Tick(axis, -1, null, true);
  7065. }
  7066. ticks[-1].render(-1);
  7067. }
  7068. }
  7069. // alternate grid color
  7070. if (alternateGridColor) {
  7071. each(tickPositions, function (pos, i) {
  7072. if (i % 2 === 0 && pos < axis.max) {
  7073. if (!alternateBands[pos]) {
  7074. alternateBands[pos] = new PlotLineOrBand(axis);
  7075. }
  7076. from = pos + tickmarkOffset; // #949
  7077. to = tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] + tickmarkOffset : axis.max;
  7078. alternateBands[pos].options = {
  7079. from: isLog ? lin2log(from) : from,
  7080. to: isLog ? lin2log(to) : to,
  7081. color: alternateGridColor
  7082. };
  7083. alternateBands[pos].render();
  7084. alternateBands[pos].isActive = true;
  7085. }
  7086. });
  7087. }
  7088. // custom plot lines and bands
  7089. if (!axis._addedPlotLB) { // only first time
  7090. each((options.plotLines || []).concat(options.plotBands || []), function (plotLineOptions) {
  7091. axis.addPlotBandOrLine(plotLineOptions);
  7092. });
  7093. axis._addedPlotLB = true;
  7094. }
  7095. } // end if hasData
  7096. // Remove inactive ticks
  7097. each([ticks, minorTicks, alternateBands], function (coll) {
  7098. var pos,
  7099. i,
  7100. forDestruction = [],
  7101. delay = globalAnimation ? globalAnimation.duration || 500 : 0,
  7102. destroyInactiveItems = function () {
  7103. i = forDestruction.length;
  7104. while (i--) {
  7105. // When resizing rapidly, the same items may be destroyed in different timeouts,
  7106. // or the may be reactivated
  7107. if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) {
  7108. coll[forDestruction[i]].destroy();
  7109. delete coll[forDestruction[i]];
  7110. }
  7111. }
  7112. };
  7113. for (pos in coll) {
  7114. if (!coll[pos].isActive) {
  7115. // Render to zero opacity
  7116. coll[pos].render(pos, false, 0);
  7117. coll[pos].isActive = false;
  7118. forDestruction.push(pos);
  7119. }
  7120. }
  7121. // When the objects are finished fading out, destroy them
  7122. if (coll === alternateBands || !chart.hasRendered || !delay) {
  7123. destroyInactiveItems();
  7124. } else if (delay) {
  7125. setTimeout(destroyInactiveItems, delay);
  7126. }
  7127. });
  7128. // Static items. As the axis group is cleared on subsequent calls
  7129. // to render, these items are added outside the group.
  7130. // axis line
  7131. if (lineWidth) {
  7132. linePath = axis.getLinePath(lineWidth);
  7133. if (!axis.axisLine) {
  7134. axis.axisLine = renderer.path(linePath)
  7135. .attr({
  7136. stroke: options.lineColor,
  7137. 'stroke-width': lineWidth,
  7138. zIndex: 7
  7139. })
  7140. .add(axis.axisGroup);
  7141. } else {
  7142. axis.axisLine.animate({ d: linePath });
  7143. }
  7144. // show or hide the line depending on options.showEmpty
  7145. axis.axisLine[showAxis ? 'show' : 'hide']();
  7146. }
  7147. if (axisTitle && showAxis) {
  7148. axisTitle[axisTitle.isNew ? 'attr' : 'animate'](
  7149. axis.getTitlePosition()
  7150. );
  7151. axisTitle.isNew = false;
  7152. }
  7153. // Stacked totals:
  7154. if (stackLabelOptions && stackLabelOptions.enabled) {
  7155. var stackKey, oneStack, stackCategory,
  7156. stackTotalGroup = axis.stackTotalGroup;
  7157. // Create a separate group for the stack total labels
  7158. if (!stackTotalGroup) {
  7159. axis.stackTotalGroup = stackTotalGroup =
  7160. renderer.g('stack-labels')
  7161. .attr({
  7162. visibility: VISIBLE,
  7163. zIndex: 6
  7164. })
  7165. .add();
  7166. }
  7167. // plotLeft/Top will change when y axis gets wider so we need to translate the
  7168. // stackTotalGroup at every render call. See bug #506 and #516
  7169. stackTotalGroup.translate(chart.plotLeft, chart.plotTop);
  7170. // Render each stack total
  7171. for (stackKey in stacks) {
  7172. oneStack = stacks[stackKey];
  7173. for (stackCategory in oneStack) {
  7174. oneStack[stackCategory].render(stackTotalGroup);
  7175. }
  7176. }
  7177. }
  7178. // End stacked totals
  7179. axis.isDirty = false;
  7180. },
  7181. /**
  7182. * Remove a plot band or plot line from the chart by id
  7183. * @param {Object} id
  7184. */
  7185. removePlotBandOrLine: function (id) {
  7186. var plotLinesAndBands = this.plotLinesAndBands,
  7187. i = plotLinesAndBands.length;
  7188. while (i--) {
  7189. if (plotLinesAndBands[i].id === id) {
  7190. plotLinesAndBands[i].destroy();
  7191. }
  7192. }
  7193. },
  7194. /**
  7195. * Update the axis title by options
  7196. */
  7197. setTitle: function (newTitleOptions, redraw) {
  7198. this.update({ title: newTitleOptions }, redraw);
  7199. },
  7200. /**
  7201. * Redraw the axis to reflect changes in the data or axis extremes
  7202. */
  7203. redraw: function () {
  7204. var axis = this,
  7205. chart = axis.chart,
  7206. pointer = chart.pointer;
  7207. // hide tooltip and hover states
  7208. if (pointer.reset) {
  7209. pointer.reset(true);
  7210. }
  7211. // render the axis
  7212. axis.render();
  7213. // move plot lines and bands
  7214. each(axis.plotLinesAndBands, function (plotLine) {
  7215. plotLine.render();
  7216. });
  7217. // mark associated series as dirty and ready for redraw
  7218. each(axis.series, function (series) {
  7219. series.isDirty = true;
  7220. });
  7221. },
  7222. /**
  7223. * Set new axis categories and optionally redraw
  7224. * @param {Array} categories
  7225. * @param {Boolean} redraw
  7226. */
  7227. setCategories: function (categories, redraw) {
  7228. this.update({ categories: categories }, redraw);
  7229. },
  7230. /**
  7231. * Destroys an Axis instance.
  7232. */
  7233. destroy: function () {
  7234. var axis = this,
  7235. stacks = axis.stacks,
  7236. stackKey;
  7237. // Remove the events
  7238. removeEvent(axis);
  7239. // Destroy each stack total
  7240. for (stackKey in stacks) {
  7241. destroyObjectProperties(stacks[stackKey]);
  7242. stacks[stackKey] = null;
  7243. }
  7244. // Destroy collections
  7245. each([axis.ticks, axis.minorTicks, axis.alternateBands, axis.plotLinesAndBands], function (coll) {
  7246. destroyObjectProperties(coll);
  7247. });
  7248. // Destroy local variables
  7249. each(['stackTotalGroup', 'axisLine', 'axisGroup', 'gridGroup', 'labelGroup', 'axisTitle'], function (prop) {
  7250. if (axis[prop]) {
  7251. axis[prop] = axis[prop].destroy();
  7252. }
  7253. });
  7254. }
  7255. }; // end Axis
  7256. /**
  7257. * The tooltip object
  7258. * @param {Object} chart The chart instance
  7259. * @param {Object} options Tooltip options
  7260. */
  7261. function Tooltip() {
  7262. this.init.apply(this, arguments);
  7263. }
  7264. Tooltip.prototype = {
  7265. init: function (chart, options) {
  7266. var borderWidth = options.borderWidth,
  7267. style = options.style,
  7268. padding = pInt(style.padding);
  7269. // Save the chart and options
  7270. this.chart = chart;
  7271. this.options = options;
  7272. // Keep track of the current series
  7273. //this.currentSeries = UNDEFINED;
  7274. // List of crosshairs
  7275. this.crosshairs = [];
  7276. // Current values of x and y when animating
  7277. this.now = { x: 0, y: 0 };
  7278. // The tooltip is initially hidden
  7279. this.isHidden = true;
  7280. // create the label
  7281. this.label = chart.renderer.label('', 0, 0, options.shape, null, null, options.useHTML, null, 'tooltip')
  7282. .attr({
  7283. padding: padding,
  7284. fill: options.backgroundColor,
  7285. 'stroke-width': borderWidth,
  7286. r: options.borderRadius,
  7287. zIndex: 8
  7288. })
  7289. .css(style)
  7290. .css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117)
  7291. .hide()
  7292. .add();
  7293. // When using canVG the shadow shows up as a gray circle
  7294. // even if the tooltip is hidden.
  7295. if (!useCanVG) {
  7296. this.label.shadow(options.shadow);
  7297. }
  7298. // Public property for getting the shared state.
  7299. this.shared = options.shared;
  7300. },
  7301. /**
  7302. * Destroy the tooltip and its elements.
  7303. */
  7304. destroy: function () {
  7305. each(this.crosshairs, function (crosshair) {
  7306. if (crosshair) {
  7307. crosshair.destroy();
  7308. }
  7309. });
  7310. // Destroy and clear local variables
  7311. if (this.label) {
  7312. this.label = this.label.destroy();
  7313. }
  7314. },
  7315. /**
  7316. * Provide a soft movement for the tooltip
  7317. *
  7318. * @param {Number} x
  7319. * @param {Number} y
  7320. * @private
  7321. */
  7322. move: function (x, y, anchorX, anchorY) {
  7323. var tooltip = this,
  7324. now = tooltip.now,
  7325. animate = tooltip.options.animation !== false && !tooltip.isHidden;
  7326. // get intermediate values for animation
  7327. extend(now, {
  7328. x: animate ? (2 * now.x + x) / 3 : x,
  7329. y: animate ? (now.y + y) / 2 : y,
  7330. anchorX: animate ? (2 * now.anchorX + anchorX) / 3 : anchorX,
  7331. anchorY: animate ? (now.anchorY + anchorY) / 2 : anchorY
  7332. });
  7333. // move to the intermediate value
  7334. tooltip.label.attr(now);
  7335. // run on next tick of the mouse tracker
  7336. if (animate && (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1)) {
  7337. // never allow two timeouts
  7338. clearTimeout(this.tooltipTimeout);
  7339. // set the fixed interval ticking for the smooth tooltip
  7340. this.tooltipTimeout = setTimeout(function () {
  7341. // The interval function may still be running during destroy, so check that the chart is really there before calling.
  7342. if (tooltip) {
  7343. tooltip.move(x, y, anchorX, anchorY);
  7344. }
  7345. }, 32);
  7346. }
  7347. },
  7348. /**
  7349. * Hide the tooltip
  7350. */
  7351. hide: function () {
  7352. var tooltip = this,
  7353. hoverPoints;
  7354. if (!this.isHidden) {
  7355. hoverPoints = this.chart.hoverPoints;
  7356. this.hideTimer = setTimeout(function () {
  7357. tooltip.label.fadeOut();
  7358. tooltip.isHidden = true;
  7359. }, pick(this.options.hideDelay, 500));
  7360. // hide previous hoverPoints and set new
  7361. if (hoverPoints) {
  7362. each(hoverPoints, function (point) {
  7363. point.setState();
  7364. });
  7365. }
  7366. this.chart.hoverPoints = null;
  7367. }
  7368. },
  7369. /**
  7370. * Hide the crosshairs
  7371. */
  7372. hideCrosshairs: function () {
  7373. each(this.crosshairs, function (crosshair) {
  7374. if (crosshair) {
  7375. crosshair.hide();
  7376. }
  7377. });
  7378. },
  7379. /**
  7380. * Extendable method to get the anchor position of the tooltip
  7381. * from a point or set of points
  7382. */
  7383. getAnchor: function (points, mouseEvent) {
  7384. var ret,
  7385. chart = this.chart,
  7386. inverted = chart.inverted,
  7387. plotTop = chart.plotTop,
  7388. plotX = 0,
  7389. plotY = 0,
  7390. yAxis;
  7391. points = splat(points);
  7392. // Pie uses a special tooltipPos
  7393. ret = points[0].tooltipPos;
  7394. // When tooltip follows mouse, relate the position to the mouse
  7395. if (this.followPointer && mouseEvent) {
  7396. if (mouseEvent.chartX === UNDEFINED) {
  7397. mouseEvent = chart.pointer.normalize(mouseEvent);
  7398. }
  7399. ret = [
  7400. mouseEvent.chartX - chart.plotLeft,
  7401. mouseEvent.chartY - plotTop
  7402. ];
  7403. }
  7404. // When shared, use the average position
  7405. if (!ret) {
  7406. each(points, function (point) {
  7407. yAxis = point.series.yAxis;
  7408. plotX += point.plotX;
  7409. plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) +
  7410. (!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151
  7411. });
  7412. plotX /= points.length;
  7413. plotY /= points.length;
  7414. ret = [
  7415. inverted ? chart.plotWidth - plotY : plotX,
  7416. this.shared && !inverted && points.length > 1 && mouseEvent ?
  7417. mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424)
  7418. inverted ? chart.plotHeight - plotX : plotY
  7419. ];
  7420. }
  7421. return map(ret, mathRound);
  7422. },
  7423. /**
  7424. * Place the tooltip in a chart without spilling over
  7425. * and not covering the point it self.
  7426. */
  7427. getPosition: function (boxWidth, boxHeight, point) {
  7428. // Set up the variables
  7429. var chart = this.chart,
  7430. plotLeft = chart.plotLeft,
  7431. plotTop = chart.plotTop,
  7432. plotWidth = chart.plotWidth,
  7433. plotHeight = chart.plotHeight,
  7434. distance = pick(this.options.distance, 12),
  7435. pointX = point.plotX,
  7436. pointY = point.plotY,
  7437. x = pointX + plotLeft + (chart.inverted ? distance : -boxWidth - distance),
  7438. y = pointY - boxHeight + plotTop + 15, // 15 means the point is 15 pixels up from the bottom of the tooltip
  7439. alignedRight;
  7440. // It is too far to the left, adjust it
  7441. if (x < 7) {
  7442. x = plotLeft + mathMax(pointX, 0) + distance;
  7443. }
  7444. // Test to see if the tooltip is too far to the right,
  7445. // if it is, move it back to be inside and then up to not cover the point.
  7446. if ((x + boxWidth) > (plotLeft + plotWidth)) {
  7447. x -= (x + boxWidth) - (plotLeft + plotWidth);
  7448. y = pointY - boxHeight + plotTop - distance;
  7449. alignedRight = true;
  7450. }
  7451. // If it is now above the plot area, align it to the top of the plot area
  7452. if (y < plotTop + 5) {
  7453. y = plotTop + 5;
  7454. // If the tooltip is still covering the point, move it below instead
  7455. if (alignedRight && pointY >= y && pointY <= (y + boxHeight)) {
  7456. y = pointY + plotTop + distance; // below
  7457. }
  7458. }
  7459. // Now if the tooltip is below the chart, move it up. It's better to cover the
  7460. // point than to disappear outside the chart. #834.
  7461. if (y + boxHeight > plotTop + plotHeight) {
  7462. y = mathMax(plotTop, plotTop + plotHeight - boxHeight - distance); // below
  7463. }
  7464. return {x: x, y: y};
  7465. },
  7466. /**
  7467. * In case no user defined formatter is given, this will be used. Note that the context
  7468. * here is an object holding point, series, x, y etc.
  7469. */
  7470. defaultFormatter: function (tooltip) {
  7471. var items = this.points || splat(this),
  7472. series = items[0].series,
  7473. s;
  7474. // build the header
  7475. s = [series.tooltipHeaderFormatter(items[0])];
  7476. // build the values
  7477. each(items, function (item) {
  7478. series = item.series;
  7479. s.push((series.tooltipFormatter && series.tooltipFormatter(item)) ||
  7480. item.point.tooltipFormatter(series.tooltipOptions.pointFormat));
  7481. });
  7482. // footer
  7483. s.push(tooltip.options.footerFormat || '');
  7484. return s.join('');
  7485. },
  7486. /**
  7487. * Refresh the tooltip's text and position.
  7488. * @param {Object} point
  7489. */
  7490. refresh: function (point, mouseEvent) {
  7491. var tooltip = this,
  7492. chart = tooltip.chart,
  7493. label = tooltip.label,
  7494. options = tooltip.options,
  7495. x,
  7496. y,
  7497. show,
  7498. anchor,
  7499. textConfig = {},
  7500. text,
  7501. pointConfig = [],
  7502. formatter = options.formatter || tooltip.defaultFormatter,
  7503. hoverPoints = chart.hoverPoints,
  7504. borderColor,
  7505. crosshairsOptions = options.crosshairs,
  7506. shared = tooltip.shared,
  7507. currentSeries;
  7508. clearTimeout(this.hideTimer);
  7509. // get the reference point coordinates (pie charts use tooltipPos)
  7510. tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer;
  7511. anchor = tooltip.getAnchor(point, mouseEvent);
  7512. x = anchor[0];
  7513. y = anchor[1];
  7514. // shared tooltip, array is sent over
  7515. if (shared && !(point.series && point.series.noSharedTooltip)) {
  7516. // hide previous hoverPoints and set new
  7517. chart.hoverPoints = point;
  7518. if (hoverPoints) {
  7519. each(hoverPoints, function (point) {
  7520. point.setState();
  7521. });
  7522. }
  7523. each(point, function (item) {
  7524. item.setState(HOVER_STATE);
  7525. pointConfig.push(item.getLabelConfig());
  7526. });
  7527. textConfig = {
  7528. x: point[0].category,
  7529. y: point[0].y
  7530. };
  7531. textConfig.points = pointConfig;
  7532. point = point[0];
  7533. // single point tooltip
  7534. } else {
  7535. textConfig = point.getLabelConfig();
  7536. }
  7537. text = formatter.call(textConfig, tooltip);
  7538. // register the current series
  7539. currentSeries = point.series;
  7540. // For line type series, hide tooltip if the point falls outside the plot
  7541. show = shared || !currentSeries.isCartesian || currentSeries.tooltipOutsidePlot || chart.isInsidePlot(x, y);
  7542. // update the inner HTML
  7543. if (text === false || !show) {
  7544. this.hide();
  7545. } else {
  7546. // show it
  7547. if (tooltip.isHidden) {
  7548. stop(label);
  7549. label.attr('opacity', 1).show();
  7550. }
  7551. // update text
  7552. label.attr({
  7553. text: text
  7554. });
  7555. // set the stroke color of the box
  7556. borderColor = options.borderColor || point.color || currentSeries.color || '#606060';
  7557. label.attr({
  7558. stroke: borderColor
  7559. });
  7560. tooltip.updatePosition({ plotX: x, plotY: y });
  7561. this.isHidden = false;
  7562. }
  7563. // crosshairs
  7564. if (crosshairsOptions) {
  7565. crosshairsOptions = splat(crosshairsOptions); // [x, y]
  7566. var path,
  7567. i = crosshairsOptions.length,
  7568. attribs,
  7569. axis,
  7570. val;
  7571. while (i--) {
  7572. axis = point.series[i ? 'yAxis' : 'xAxis'];
  7573. if (crosshairsOptions[i] && axis) {
  7574. val = i ? pick(point.stackY, point.y) : point.x; // #814
  7575. if (axis.isLog) { // #1671
  7576. val = log2lin(val);
  7577. }
  7578. path = axis.getPlotLinePath(
  7579. val,
  7580. 1
  7581. );
  7582. if (tooltip.crosshairs[i]) {
  7583. tooltip.crosshairs[i].attr({ d: path, visibility: VISIBLE });
  7584. } else {
  7585. attribs = {
  7586. 'stroke-width': crosshairsOptions[i].width || 1,
  7587. stroke: crosshairsOptions[i].color || '#C0C0C0',
  7588. zIndex: crosshairsOptions[i].zIndex || 2
  7589. };
  7590. if (crosshairsOptions[i].dashStyle) {
  7591. attribs.dashstyle = crosshairsOptions[i].dashStyle;
  7592. }
  7593. tooltip.crosshairs[i] = chart.renderer.path(path)
  7594. .attr(attribs)
  7595. .add();
  7596. }
  7597. }
  7598. }
  7599. }
  7600. fireEvent(chart, 'tooltipRefresh', {
  7601. text: text,
  7602. x: x + chart.plotLeft,
  7603. y: y + chart.plotTop,
  7604. borderColor: borderColor
  7605. });
  7606. },
  7607. /**
  7608. * Find the new position and perform the move
  7609. */
  7610. updatePosition: function (point) {
  7611. var chart = this.chart,
  7612. label = this.label,
  7613. pos = (this.options.positioner || this.getPosition).call(
  7614. this,
  7615. label.width,
  7616. label.height,
  7617. point
  7618. );
  7619. // do the move
  7620. this.move(
  7621. mathRound(pos.x),
  7622. mathRound(pos.y),
  7623. point.plotX + chart.plotLeft,
  7624. point.plotY + chart.plotTop
  7625. );
  7626. }
  7627. };
  7628. /**
  7629. * The mouse tracker object. All methods starting with "on" are primary DOM event handlers.
  7630. * Subsequent methods should be named differently from what they are doing.
  7631. * @param {Object} chart The Chart instance
  7632. * @param {Object} options The root options object
  7633. */
  7634. function Pointer(chart, options) {
  7635. this.init(chart, options);
  7636. }
  7637. Pointer.prototype = {
  7638. /**
  7639. * Initialize Pointer
  7640. */
  7641. init: function (chart, options) {
  7642. var zoomType = useCanVG ? '' : options.chart.zoomType,
  7643. inverted = chart.inverted,
  7644. zoomX,
  7645. zoomY;
  7646. // Store references
  7647. this.options = options;
  7648. this.chart = chart;
  7649. // Zoom status
  7650. this.zoomX = zoomX = /x/.test(zoomType);
  7651. this.zoomY = zoomY = /y/.test(zoomType);
  7652. this.zoomHor = (zoomX && !inverted) || (zoomY && inverted);
  7653. this.zoomVert = (zoomY && !inverted) || (zoomX && inverted);
  7654. this.pinchDown = [];
  7655. this.lastValidTouch = {};
  7656. if (options.tooltip.enabled) {
  7657. chart.tooltip = new Tooltip(chart, options.tooltip);
  7658. }
  7659. this.setDOMEvents();
  7660. },
  7661. /**
  7662. * Add crossbrowser support for chartX and chartY
  7663. * @param {Object} e The event object in standard browsers
  7664. */
  7665. normalize: function (e) {
  7666. var chartPosition,
  7667. chartX,
  7668. chartY,
  7669. ePos;
  7670. // common IE normalizing
  7671. e = e || win.event;
  7672. if (!e.target) {
  7673. e.target = e.srcElement;
  7674. }
  7675. // Framework specific normalizing (#1165)
  7676. e = washMouseEvent(e);
  7677. // iOS
  7678. ePos = e.touches ? e.touches.item(0) : e;
  7679. // get mouse position
  7680. this.chartPosition = chartPosition = offset(this.chart.container);
  7681. // chartX and chartY
  7682. if (ePos.pageX === UNDEFINED) { // IE < 9. #886.
  7683. chartX = e.x;
  7684. chartY = e.y;
  7685. } else {
  7686. chartX = ePos.pageX - chartPosition.left;
  7687. chartY = ePos.pageY - chartPosition.top;
  7688. }
  7689. return extend(e, {
  7690. chartX: mathRound(chartX),
  7691. chartY: mathRound(chartY)
  7692. });
  7693. },
  7694. /**
  7695. * Get the click position in terms of axis values.
  7696. *
  7697. * @param {Object} e A pointer event
  7698. */
  7699. getCoordinates: function (e) {
  7700. var coordinates = {
  7701. xAxis: [],
  7702. yAxis: []
  7703. };
  7704. each(this.chart.axes, function (axis) {
  7705. coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({
  7706. axis: axis,
  7707. value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY'])
  7708. });
  7709. });
  7710. return coordinates;
  7711. },
  7712. /**
  7713. * Return the index in the tooltipPoints array, corresponding to pixel position in
  7714. * the plot area.
  7715. */
  7716. getIndex: function (e) {
  7717. var chart = this.chart;
  7718. return chart.inverted ?
  7719. chart.plotHeight + chart.plotTop - e.chartY :
  7720. e.chartX - chart.plotLeft;
  7721. },
  7722. /**
  7723. * With line type charts with a single tracker, get the point closest to the mouse.
  7724. * Run Point.onMouseOver and display tooltip for the point or points.
  7725. */
  7726. runPointActions: function (e) {
  7727. var pointer = this,
  7728. chart = pointer.chart,
  7729. series = chart.series,
  7730. tooltip = chart.tooltip,
  7731. point,
  7732. points,
  7733. hoverPoint = chart.hoverPoint,
  7734. hoverSeries = chart.hoverSeries,
  7735. i,
  7736. j,
  7737. distance = chart.chartWidth,
  7738. index = pointer.getIndex(e),
  7739. anchor;
  7740. // shared tooltip
  7741. if (tooltip && pointer.options.tooltip.shared && !(hoverSeries && hoverSeries.noSharedTooltip)) {
  7742. points = [];
  7743. // loop over all series and find the ones with points closest to the mouse
  7744. i = series.length;
  7745. for (j = 0; j < i; j++) {
  7746. if (series[j].visible &&
  7747. series[j].options.enableMouseTracking !== false &&
  7748. !series[j].noSharedTooltip && series[j].tooltipPoints.length) {
  7749. point = series[j].tooltipPoints[index];
  7750. if (point.series) { // not a dummy point, #1544
  7751. point._dist = mathAbs(index - point.clientX);
  7752. distance = mathMin(distance, point._dist);
  7753. points.push(point);
  7754. }
  7755. }
  7756. }
  7757. // remove furthest points
  7758. i = points.length;
  7759. while (i--) {
  7760. if (points[i]._dist > distance) {
  7761. points.splice(i, 1);
  7762. }
  7763. }
  7764. // refresh the tooltip if necessary
  7765. if (points.length && (points[0].clientX !== pointer.hoverX)) {
  7766. tooltip.refresh(points, e);
  7767. pointer.hoverX = points[0].clientX;
  7768. }
  7769. }
  7770. // separate tooltip and general mouse events
  7771. if (hoverSeries && hoverSeries.tracker) { // only use for line-type series with common tracker
  7772. // get the point
  7773. point = hoverSeries.tooltipPoints[index];
  7774. // a new point is hovered, refresh the tooltip
  7775. if (point && point !== hoverPoint) {
  7776. // trigger the events
  7777. point.onMouseOver(e);
  7778. }
  7779. } else if (tooltip && tooltip.followPointer && !tooltip.isHidden) {
  7780. anchor = tooltip.getAnchor([{}], e);
  7781. tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] });
  7782. }
  7783. },
  7784. /**
  7785. * Reset the tracking by hiding the tooltip, the hover series state and the hover point
  7786. *
  7787. * @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible
  7788. */
  7789. reset: function (allowMove) {
  7790. var pointer = this,
  7791. chart = pointer.chart,
  7792. hoverSeries = chart.hoverSeries,
  7793. hoverPoint = chart.hoverPoint,
  7794. tooltip = chart.tooltip,
  7795. tooltipPoints = tooltip && tooltip.shared ? chart.hoverPoints : hoverPoint;
  7796. // Narrow in allowMove
  7797. allowMove = allowMove && tooltip && tooltipPoints;
  7798. // Check if the points have moved outside the plot area, #1003
  7799. if (allowMove && splat(tooltipPoints)[0].plotX === UNDEFINED) {
  7800. allowMove = false;
  7801. }
  7802. // Just move the tooltip, #349
  7803. if (allowMove) {
  7804. tooltip.refresh(tooltipPoints);
  7805. // Full reset
  7806. } else {
  7807. if (hoverPoint) {
  7808. hoverPoint.onMouseOut();
  7809. }
  7810. if (hoverSeries) {
  7811. hoverSeries.onMouseOut();
  7812. }
  7813. if (tooltip) {
  7814. tooltip.hide();
  7815. tooltip.hideCrosshairs();
  7816. }
  7817. pointer.hoverX = null;
  7818. }
  7819. },
  7820. /**
  7821. * Scale series groups to a certain scale and translation
  7822. */
  7823. scaleGroups: function (attribs, clip) {
  7824. var chart = this.chart;
  7825. // Scale each series
  7826. each(chart.series, function (series) {
  7827. if (series.xAxis.zoomEnabled) {
  7828. series.group.attr(attribs);
  7829. if (series.markerGroup) {
  7830. series.markerGroup.attr(attribs);
  7831. series.markerGroup.clip(clip ? chart.clipRect : null);
  7832. }
  7833. if (series.dataLabelsGroup) {
  7834. series.dataLabelsGroup.attr(attribs);
  7835. }
  7836. }
  7837. });
  7838. // Clip
  7839. chart.clipRect.attr(clip || chart.clipBox);
  7840. },
  7841. /**
  7842. * Run translation operations for each direction (horizontal and vertical) independently
  7843. */
  7844. pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) {
  7845. var chart = this.chart,
  7846. xy = horiz ? 'x' : 'y',
  7847. XY = horiz ? 'X' : 'Y',
  7848. sChartXY = 'chart' + XY,
  7849. wh = horiz ? 'width' : 'height',
  7850. plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')],
  7851. selectionWH,
  7852. selectionXY,
  7853. clipXY,
  7854. scale = 1,
  7855. inverted = chart.inverted,
  7856. bounds = chart.bounds[horiz ? 'h' : 'v'],
  7857. singleTouch = pinchDown.length === 1,
  7858. touch0Start = pinchDown[0][sChartXY],
  7859. touch0Now = touches[0][sChartXY],
  7860. touch1Start = !singleTouch && pinchDown[1][sChartXY],
  7861. touch1Now = !singleTouch && touches[1][sChartXY],
  7862. outOfBounds,
  7863. transformScale,
  7864. scaleKey,
  7865. setScale = function () {
  7866. if (!singleTouch && mathAbs(touch0Start - touch1Start) > 20) { // Don't zoom if fingers are too close on this axis
  7867. scale = mathAbs(touch0Now - touch1Now) / mathAbs(touch0Start - touch1Start);
  7868. }
  7869. clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start;
  7870. selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale;
  7871. };
  7872. // Set the scale, first pass
  7873. setScale();
  7874. selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not
  7875. // Out of bounds
  7876. if (selectionXY < bounds.min) {
  7877. selectionXY = bounds.min;
  7878. outOfBounds = true;
  7879. } else if (selectionXY + selectionWH > bounds.max) {
  7880. selectionXY = bounds.max - selectionWH;
  7881. outOfBounds = true;
  7882. }
  7883. // Is the chart dragged off its bounds, determined by dataMin and dataMax?
  7884. if (outOfBounds) {
  7885. // Modify the touchNow position in order to create an elastic drag movement. This indicates
  7886. // to the user that the chart is responsive but can't be dragged further.
  7887. touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]);
  7888. if (!singleTouch) {
  7889. touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]);
  7890. }
  7891. // Set the scale, second pass to adapt to the modified touchNow positions
  7892. setScale();
  7893. } else {
  7894. lastValidTouch[xy] = [touch0Now, touch1Now];
  7895. }
  7896. // Set geometry for clipping, selection and transformation
  7897. if (!inverted) { // TODO: implement clipping for inverted charts
  7898. clip[xy] = clipXY - plotLeftTop;
  7899. clip[wh] = selectionWH;
  7900. }
  7901. scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY;
  7902. transformScale = inverted ? 1 / scale : scale;
  7903. selectionMarker[wh] = selectionWH;
  7904. selectionMarker[xy] = selectionXY;
  7905. transform[scaleKey] = scale;
  7906. transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start));
  7907. },
  7908. /**
  7909. * Handle touch events with two touches
  7910. */
  7911. pinch: function (e) {
  7912. var self = this,
  7913. chart = self.chart,
  7914. pinchDown = self.pinchDown,
  7915. followTouchMove = chart.tooltip.options.followTouchMove,
  7916. touches = e.touches,
  7917. touchesLength = touches.length,
  7918. lastValidTouch = self.lastValidTouch,
  7919. zoomHor = self.zoomHor || self.pinchHor,
  7920. zoomVert = self.zoomVert || self.pinchVert,
  7921. hasZoom = zoomHor || zoomVert,
  7922. selectionMarker = self.selectionMarker,
  7923. transform = {},
  7924. clip = {};
  7925. // On touch devices, only proceed to trigger click if a handler is defined
  7926. if (e.type === 'touchstart' && followTouchMove) {
  7927. if (self.inClass(e.target, PREFIX + 'tracker')) {
  7928. if (!chart.runTrackerClick || touchesLength > 1) {
  7929. e.preventDefault();
  7930. }
  7931. } else if (!chart.runChartClick || touchesLength > 1) {
  7932. e.preventDefault();
  7933. }
  7934. }
  7935. // Normalize each touch
  7936. map(touches, function (e) {
  7937. return self.normalize(e);
  7938. });
  7939. // Register the touch start position
  7940. if (e.type === 'touchstart') {
  7941. each(touches, function (e, i) {
  7942. pinchDown[i] = { chartX: e.chartX, chartY: e.chartY };
  7943. });
  7944. lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX];
  7945. lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY];
  7946. // Identify the data bounds in pixels
  7947. each(chart.axes, function (axis) {
  7948. if (axis.zoomEnabled) {
  7949. var bounds = chart.bounds[axis.horiz ? 'h' : 'v'],
  7950. minPixelPadding = axis.minPixelPadding,
  7951. min = axis.toPixels(axis.dataMin),
  7952. max = axis.toPixels(axis.dataMax),
  7953. absMin = mathMin(min, max),
  7954. absMax = mathMax(min, max);
  7955. // Store the bounds for use in the touchmove handler
  7956. bounds.min = mathMin(axis.pos, absMin - minPixelPadding);
  7957. bounds.max = mathMax(axis.pos + axis.len, absMax + minPixelPadding);
  7958. }
  7959. });
  7960. // Event type is touchmove, handle panning and pinching
  7961. } else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first
  7962. // Set the marker
  7963. if (!selectionMarker) {
  7964. self.selectionMarker = selectionMarker = extend({
  7965. destroy: noop
  7966. }, chart.plotBox);
  7967. }
  7968. if (zoomHor) {
  7969. self.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
  7970. }
  7971. if (zoomVert) {
  7972. self.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
  7973. }
  7974. self.hasPinched = hasZoom;
  7975. // Scale and translate the groups to provide visual feedback during pinching
  7976. self.scaleGroups(transform, clip);
  7977. // Optionally move the tooltip on touchmove
  7978. if (!hasZoom && followTouchMove && touchesLength === 1) {
  7979. this.runPointActions(self.normalize(e));
  7980. }
  7981. }
  7982. },
  7983. /**
  7984. * Start a drag operation
  7985. */
  7986. dragStart: function (e) {
  7987. var chart = this.chart;
  7988. // Record the start position
  7989. chart.mouseIsDown = e.type;
  7990. chart.cancelClick = false;
  7991. chart.mouseDownX = this.mouseDownX = e.chartX;
  7992. this.mouseDownY = e.chartY;
  7993. },
  7994. /**
  7995. * Perform a drag operation in response to a mousemove event while the mouse is down
  7996. */
  7997. drag: function (e) {
  7998. var chart = this.chart,
  7999. chartOptions = chart.options.chart,
  8000. chartX = e.chartX,
  8001. chartY = e.chartY,
  8002. zoomHor = this.zoomHor,
  8003. zoomVert = this.zoomVert,
  8004. plotLeft = chart.plotLeft,
  8005. plotTop = chart.plotTop,
  8006. plotWidth = chart.plotWidth,
  8007. plotHeight = chart.plotHeight,
  8008. clickedInside,
  8009. size,
  8010. mouseDownX = this.mouseDownX,
  8011. mouseDownY = this.mouseDownY;
  8012. // If the mouse is outside the plot area, adjust to cooordinates
  8013. // inside to prevent the selection marker from going outside
  8014. if (chartX < plotLeft) {
  8015. chartX = plotLeft;
  8016. } else if (chartX > plotLeft + plotWidth) {
  8017. chartX = plotLeft + plotWidth;
  8018. }
  8019. if (chartY < plotTop) {
  8020. chartY = plotTop;
  8021. } else if (chartY > plotTop + plotHeight) {
  8022. chartY = plotTop + plotHeight;
  8023. }
  8024. // determine if the mouse has moved more than 10px
  8025. this.hasDragged = Math.sqrt(
  8026. Math.pow(mouseDownX - chartX, 2) +
  8027. Math.pow(mouseDownY - chartY, 2)
  8028. );
  8029. if (this.hasDragged > 10) {
  8030. clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop);
  8031. // make a selection
  8032. if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside) {
  8033. if (!this.selectionMarker) {
  8034. this.selectionMarker = chart.renderer.rect(
  8035. plotLeft,
  8036. plotTop,
  8037. zoomHor ? 1 : plotWidth,
  8038. zoomVert ? 1 : plotHeight,
  8039. 0
  8040. )
  8041. .attr({
  8042. fill: chartOptions.selectionMarkerFill || 'rgba(69,114,167,0.25)',
  8043. zIndex: 7
  8044. })
  8045. .add();
  8046. }
  8047. }
  8048. // adjust the width of the selection marker
  8049. if (this.selectionMarker && zoomHor) {
  8050. size = chartX - mouseDownX;
  8051. this.selectionMarker.attr({
  8052. width: mathAbs(size),
  8053. x: (size > 0 ? 0 : size) + mouseDownX
  8054. });
  8055. }
  8056. // adjust the height of the selection marker
  8057. if (this.selectionMarker && zoomVert) {
  8058. size = chartY - mouseDownY;
  8059. this.selectionMarker.attr({
  8060. height: mathAbs(size),
  8061. y: (size > 0 ? 0 : size) + mouseDownY
  8062. });
  8063. }
  8064. // panning
  8065. if (clickedInside && !this.selectionMarker && chartOptions.panning) {
  8066. chart.pan(chartX);
  8067. }
  8068. }
  8069. },
  8070. /**
  8071. * On mouse up or touch end across the entire document, drop the selection.
  8072. */
  8073. drop: function (e) {
  8074. var chart = this.chart,
  8075. hasPinched = this.hasPinched;
  8076. if (this.selectionMarker) {
  8077. var selectionData = {
  8078. xAxis: [],
  8079. yAxis: [],
  8080. originalEvent: e.originalEvent || e
  8081. },
  8082. selectionBox = this.selectionMarker,
  8083. selectionLeft = selectionBox.x,
  8084. selectionTop = selectionBox.y,
  8085. runZoom;
  8086. // a selection has been made
  8087. if (this.hasDragged || hasPinched) {
  8088. // record each axis' min and max
  8089. each(chart.axes, function (axis) {
  8090. if (axis.zoomEnabled) {
  8091. var horiz = axis.horiz,
  8092. minPixelPadding = axis.minPixelPadding,
  8093. selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop) + minPixelPadding),
  8094. selectionMax = axis.toValue((horiz ? selectionLeft + selectionBox.width : selectionTop + selectionBox.height) - minPixelPadding);
  8095. if (!isNaN(selectionMin) && !isNaN(selectionMax)) { // #859
  8096. selectionData[axis.xOrY + 'Axis'].push({
  8097. axis: axis,
  8098. min: mathMin(selectionMin, selectionMax), // for reversed axes,
  8099. max: mathMax(selectionMin, selectionMax)
  8100. });
  8101. runZoom = true;
  8102. }
  8103. }
  8104. });
  8105. if (runZoom) {
  8106. fireEvent(chart, 'selection', selectionData, function (args) {
  8107. chart.zoom(extend(args, hasPinched ? { animation: false } : null));
  8108. });
  8109. }
  8110. }
  8111. this.selectionMarker = this.selectionMarker.destroy();
  8112. // Reset scaling preview
  8113. if (hasPinched) {
  8114. this.scaleGroups({
  8115. translateX: chart.plotLeft,
  8116. translateY: chart.plotTop,
  8117. scaleX: 1,
  8118. scaleY: 1
  8119. });
  8120. }
  8121. }
  8122. // Reset all
  8123. if (chart) { // it may be destroyed on mouse up - #877
  8124. css(chart.container, { cursor: chart._cursor });
  8125. chart.cancelClick = this.hasDragged; // #370
  8126. chart.mouseIsDown = this.hasDragged = this.hasPinched = false;
  8127. this.pinchDown = [];
  8128. }
  8129. },
  8130. onContainerMouseDown: function (e) {
  8131. e = this.normalize(e);
  8132. // issue #295, dragging not always working in Firefox
  8133. if (e.preventDefault) {
  8134. e.preventDefault();
  8135. }
  8136. this.dragStart(e);
  8137. },
  8138. onDocumentMouseUp: function (e) {
  8139. this.drop(e);
  8140. },
  8141. /**
  8142. * Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea.
  8143. * Issue #149 workaround. The mouseleave event does not always fire.
  8144. */
  8145. onDocumentMouseMove: function (e) {
  8146. var chart = this.chart,
  8147. chartPosition = this.chartPosition,
  8148. hoverSeries = chart.hoverSeries;
  8149. // Get e.pageX and e.pageY back in MooTools
  8150. e = washMouseEvent(e);
  8151. // If we're outside, hide the tooltip
  8152. if (chartPosition && hoverSeries && hoverSeries.isCartesian &&
  8153. !chart.isInsidePlot(e.pageX - chartPosition.left - chart.plotLeft,
  8154. e.pageY - chartPosition.top - chart.plotTop)) {
  8155. this.reset();
  8156. }
  8157. },
  8158. /**
  8159. * When mouse leaves the container, hide the tooltip.
  8160. */
  8161. onContainerMouseLeave: function () {
  8162. this.reset();
  8163. this.chartPosition = null; // also reset the chart position, used in #149 fix
  8164. },
  8165. // The mousemove, touchmove and touchstart event handler
  8166. onContainerMouseMove: function (e) {
  8167. var chart = this.chart;
  8168. // normalize
  8169. e = this.normalize(e);
  8170. // #295
  8171. e.returnValue = false;
  8172. if (chart.mouseIsDown === 'mousedown') {
  8173. this.drag(e);
  8174. }
  8175. // Show the tooltip and run mouse over events (#977)
  8176. if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
  8177. this.runPointActions(e);
  8178. }
  8179. },
  8180. /**
  8181. * Utility to detect whether an element has, or has a parent with, a specific
  8182. * class name. Used on detection of tracker objects and on deciding whether
  8183. * hovering the tooltip should cause the active series to mouse out.
  8184. */
  8185. inClass: function (element, className) {
  8186. var elemClassName;
  8187. while (element) {
  8188. elemClassName = attr(element, 'class');
  8189. if (elemClassName) {
  8190. if (elemClassName.indexOf(className) !== -1) {
  8191. return true;
  8192. } else if (elemClassName.indexOf(PREFIX + 'container') !== -1) {
  8193. return false;
  8194. }
  8195. }
  8196. element = element.parentNode;
  8197. }
  8198. },
  8199. onTrackerMouseOut: function (e) {
  8200. var series = this.chart.hoverSeries;
  8201. if (series && !series.options.stickyTracking && !this.inClass(e.toElement || e.relatedTarget, PREFIX + 'tooltip')) {
  8202. series.onMouseOut();
  8203. }
  8204. },
  8205. onContainerClick: function (e) {
  8206. var chart = this.chart,
  8207. hoverPoint = chart.hoverPoint,
  8208. plotLeft = chart.plotLeft,
  8209. plotTop = chart.plotTop,
  8210. inverted = chart.inverted,
  8211. chartPosition,
  8212. plotX,
  8213. plotY;
  8214. e = this.normalize(e);
  8215. e.cancelBubble = true; // IE specific
  8216. if (!chart.cancelClick) {
  8217. // On tracker click, fire the series and point events. #783, #1583
  8218. if (hoverPoint && this.inClass(e.target, PREFIX + 'tracker')) {
  8219. chartPosition = this.chartPosition;
  8220. plotX = hoverPoint.plotX;
  8221. plotY = hoverPoint.plotY;
  8222. // add page position info
  8223. extend(hoverPoint, {
  8224. pageX: chartPosition.left + plotLeft +
  8225. (inverted ? chart.plotWidth - plotY : plotX),
  8226. pageY: chartPosition.top + plotTop +
  8227. (inverted ? chart.plotHeight - plotX : plotY)
  8228. });
  8229. // the series click event
  8230. fireEvent(hoverPoint.series, 'click', extend(e, {
  8231. point: hoverPoint
  8232. }));
  8233. // the point click event
  8234. hoverPoint.firePointEvent('click', e);
  8235. // When clicking outside a tracker, fire a chart event
  8236. } else {
  8237. extend(e, this.getCoordinates(e));
  8238. // fire a click event in the chart
  8239. if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) {
  8240. fireEvent(chart, 'click', e);
  8241. }
  8242. }
  8243. }
  8244. },
  8245. onContainerTouchStart: function (e) {
  8246. var chart = this.chart;
  8247. if (e.touches.length === 1) {
  8248. e = this.normalize(e);
  8249. if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
  8250. // Prevent the click pseudo event from firing unless it is set in the options
  8251. /*if (!chart.runChartClick) {
  8252. e.preventDefault();
  8253. }*/
  8254. // Run mouse events and display tooltip etc
  8255. this.runPointActions(e);
  8256. this.pinch(e);
  8257. }
  8258. } else if (e.touches.length === 2) {
  8259. this.pinch(e);
  8260. }
  8261. },
  8262. onContainerTouchMove: function (e) {
  8263. if (e.touches.length === 1 || e.touches.length === 2) {
  8264. this.pinch(e);
  8265. }
  8266. },
  8267. onDocumentTouchEnd: function (e) {
  8268. this.drop(e);
  8269. },
  8270. /**
  8271. * Set the JS DOM events on the container and document. This method should contain
  8272. * a one-to-one assignment between methods and their handlers. Any advanced logic should
  8273. * be moved to the handler reflecting the event's name.
  8274. */
  8275. setDOMEvents: function () {
  8276. var pointer = this,
  8277. container = pointer.chart.container,
  8278. events;
  8279. this._events = events = [
  8280. [container, 'onmousedown', 'onContainerMouseDown'],
  8281. [container, 'onmousemove', 'onContainerMouseMove'],
  8282. [container, 'onclick', 'onContainerClick'],
  8283. [container, 'mouseleave', 'onContainerMouseLeave'],
  8284. [doc, 'mousemove', 'onDocumentMouseMove'],
  8285. [doc, 'mouseup', 'onDocumentMouseUp']
  8286. ];
  8287. if (hasTouch) {
  8288. events.push(
  8289. [container, 'ontouchstart', 'onContainerTouchStart'],
  8290. [container, 'ontouchmove', 'onContainerTouchMove'],
  8291. [doc, 'touchend', 'onDocumentTouchEnd']
  8292. );
  8293. }
  8294. each(events, function (eventConfig) {
  8295. // First, create the callback function that in turn calls the method on Pointer
  8296. pointer['_' + eventConfig[2]] = function (e) {
  8297. pointer[eventConfig[2]](e);
  8298. };
  8299. // Now attach the function, either as a direct property or through addEvent
  8300. if (eventConfig[1].indexOf('on') === 0) {
  8301. eventConfig[0][eventConfig[1]] = pointer['_' + eventConfig[2]];
  8302. } else {
  8303. addEvent(eventConfig[0], eventConfig[1], pointer['_' + eventConfig[2]]);
  8304. }
  8305. });
  8306. },
  8307. /**
  8308. * Destroys the Pointer object and disconnects DOM events.
  8309. */
  8310. destroy: function () {
  8311. var pointer = this;
  8312. // Release all DOM events
  8313. each(pointer._events, function (eventConfig) {
  8314. if (eventConfig[1].indexOf('on') === 0) {
  8315. eventConfig[0][eventConfig[1]] = null; // delete breaks oldIE
  8316. } else {
  8317. removeEvent(eventConfig[0], eventConfig[1], pointer['_' + eventConfig[2]]);
  8318. }
  8319. });
  8320. delete pointer._events;
  8321. // memory and CPU leak
  8322. clearInterval(pointer.tooltipTimeout);
  8323. }
  8324. };
  8325. /**
  8326. * The overview of the chart's series
  8327. */
  8328. function Legend(chart, options) {
  8329. this.init(chart, options);
  8330. }
  8331. Legend.prototype = {
  8332. /**
  8333. * Initialize the legend
  8334. */
  8335. init: function (chart, options) {
  8336. var legend = this,
  8337. itemStyle = options.itemStyle,
  8338. padding = pick(options.padding, 8),
  8339. itemMarginTop = options.itemMarginTop || 0;
  8340. this.options = options;
  8341. if (!options.enabled) {
  8342. return;
  8343. }
  8344. legend.baseline = pInt(itemStyle.fontSize) + 3 + itemMarginTop; // used in Series prototype
  8345. legend.itemStyle = itemStyle;
  8346. legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle);
  8347. legend.itemMarginTop = itemMarginTop;
  8348. legend.padding = padding;
  8349. legend.initialItemX = padding;
  8350. legend.initialItemY = padding - 5; // 5 is the number of pixels above the text
  8351. legend.maxItemWidth = 0;
  8352. legend.chart = chart;
  8353. legend.itemHeight = 0;
  8354. legend.lastLineHeight = 0;
  8355. // Render it
  8356. legend.render();
  8357. // move checkboxes
  8358. addEvent(legend.chart, 'endResize', function () {
  8359. legend.positionCheckboxes();
  8360. });
  8361. },
  8362. /**
  8363. * Set the colors for the legend item
  8364. * @param {Object} item A Series or Point instance
  8365. * @param {Object} visible Dimmed or colored
  8366. */
  8367. colorizeItem: function (item, visible) {
  8368. var legend = this,
  8369. options = legend.options,
  8370. legendItem = item.legendItem,
  8371. legendLine = item.legendLine,
  8372. legendSymbol = item.legendSymbol,
  8373. hiddenColor = legend.itemHiddenStyle.color,
  8374. textColor = visible ? options.itemStyle.color : hiddenColor,
  8375. symbolColor = visible ? item.color : hiddenColor,
  8376. markerOptions = item.options && item.options.marker,
  8377. symbolAttr = {
  8378. stroke: symbolColor,
  8379. fill: symbolColor
  8380. },
  8381. key,
  8382. val;
  8383. if (legendItem) {
  8384. legendItem.css({ fill: textColor, color: textColor }); // color for #1553, oldIE
  8385. }
  8386. if (legendLine) {
  8387. legendLine.attr({ stroke: symbolColor });
  8388. }
  8389. if (legendSymbol) {
  8390. // Apply marker options
  8391. if (markerOptions) {
  8392. markerOptions = item.convertAttribs(markerOptions);
  8393. for (key in markerOptions) {
  8394. val = markerOptions[key];
  8395. if (val !== UNDEFINED) {
  8396. symbolAttr[key] = val;
  8397. }
  8398. }
  8399. }
  8400. legendSymbol.attr(symbolAttr);
  8401. }
  8402. },
  8403. /**
  8404. * Position the legend item
  8405. * @param {Object} item A Series or Point instance
  8406. */
  8407. positionItem: function (item) {
  8408. var legend = this,
  8409. options = legend.options,
  8410. symbolPadding = options.symbolPadding,
  8411. ltr = !options.rtl,
  8412. legendItemPos = item._legendItemPos,
  8413. itemX = legendItemPos[0],
  8414. itemY = legendItemPos[1],
  8415. checkbox = item.checkbox;
  8416. if (item.legendGroup) {
  8417. item.legendGroup.translate(
  8418. ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4,
  8419. itemY
  8420. );
  8421. }
  8422. if (checkbox) {
  8423. checkbox.x = itemX;
  8424. checkbox.y = itemY;
  8425. }
  8426. },
  8427. /**
  8428. * Destroy a single legend item
  8429. * @param {Object} item The series or point
  8430. */
  8431. destroyItem: function (item) {
  8432. var checkbox = item.checkbox;
  8433. // destroy SVG elements
  8434. each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) {
  8435. if (item[key]) {
  8436. item[key].destroy();
  8437. }
  8438. });
  8439. if (checkbox) {
  8440. discardElement(item.checkbox);
  8441. }
  8442. },
  8443. /**
  8444. * Destroys the legend.
  8445. */
  8446. destroy: function () {
  8447. var legend = this,
  8448. legendGroup = legend.group,
  8449. box = legend.box;
  8450. if (box) {
  8451. legend.box = box.destroy();
  8452. }
  8453. if (legendGroup) {
  8454. legend.group = legendGroup.destroy();
  8455. }
  8456. },
  8457. /**
  8458. * Position the checkboxes after the width is determined
  8459. */
  8460. positionCheckboxes: function (scrollOffset) {
  8461. var alignAttr = this.group.alignAttr,
  8462. translateY,
  8463. clipHeight = this.clipHeight || this.legendHeight;
  8464. if (alignAttr) {
  8465. translateY = alignAttr.translateY;
  8466. each(this.allItems, function (item) {
  8467. var checkbox = item.checkbox,
  8468. top;
  8469. if (checkbox) {
  8470. top = (translateY + checkbox.y + (scrollOffset || 0) + 3);
  8471. css(checkbox, {
  8472. left: (alignAttr.translateX + item.legendItemWidth + checkbox.x - 20) + PX,
  8473. top: top + PX,
  8474. display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE
  8475. });
  8476. }
  8477. });
  8478. }
  8479. },
  8480. /**
  8481. * Render the legend title on top of the legend
  8482. */
  8483. renderTitle: function () {
  8484. var options = this.options,
  8485. padding = this.padding,
  8486. titleOptions = options.title,
  8487. titleHeight = 0;
  8488. if (titleOptions.text) {
  8489. if (!this.title) {
  8490. this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title')
  8491. .attr({ zIndex: 1 })
  8492. .css(titleOptions.style)
  8493. .add(this.group);
  8494. }
  8495. titleHeight = this.title.getBBox().height;
  8496. this.contentGroup.attr({ translateY: titleHeight });
  8497. }
  8498. this.titleHeight = titleHeight;
  8499. },
  8500. /**
  8501. * Render a single specific legend item
  8502. * @param {Object} item A series or point
  8503. */
  8504. renderItem: function (item) {
  8505. var legend = this,
  8506. chart = legend.chart,
  8507. renderer = chart.renderer,
  8508. options = legend.options,
  8509. horizontal = options.layout === 'horizontal',
  8510. symbolWidth = options.symbolWidth,
  8511. symbolPadding = options.symbolPadding,
  8512. itemStyle = legend.itemStyle,
  8513. itemHiddenStyle = legend.itemHiddenStyle,
  8514. padding = legend.padding,
  8515. ltr = !options.rtl,
  8516. itemHeight,
  8517. widthOption = options.width,
  8518. itemMarginBottom = options.itemMarginBottom || 0,
  8519. itemMarginTop = legend.itemMarginTop,
  8520. initialItemX = legend.initialItemX,
  8521. bBox,
  8522. itemWidth,
  8523. li = item.legendItem,
  8524. series = item.series || item,
  8525. itemOptions = series.options,
  8526. showCheckbox = itemOptions.showCheckbox,
  8527. useHTML = options.useHTML;
  8528. if (!li) { // generate it once, later move it
  8529. // Generate the group box
  8530. // A group to hold the symbol and text. Text is to be appended in Legend class.
  8531. item.legendGroup = renderer.g('legend-item')
  8532. .attr({ zIndex: 1 })
  8533. .add(legend.scrollGroup);
  8534. // Draw the legend symbol inside the group box
  8535. series.drawLegendSymbol(legend, item);
  8536. // Generate the list item text and add it to the group
  8537. item.legendItem = li = renderer.text(
  8538. options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item),
  8539. ltr ? symbolWidth + symbolPadding : -symbolPadding,
  8540. legend.baseline,
  8541. useHTML
  8542. )
  8543. .css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021)
  8544. .attr({
  8545. align: ltr ? 'left' : 'right',
  8546. zIndex: 2
  8547. })
  8548. .add(item.legendGroup);
  8549. // Set the events on the item group, or in case of useHTML, the item itself (#1249)
  8550. (useHTML ? li : item.legendGroup).on('mouseover', function () {
  8551. item.setState(HOVER_STATE);
  8552. li.css(legend.options.itemHoverStyle);
  8553. })
  8554. .on('mouseout', function () {
  8555. li.css(item.visible ? itemStyle : itemHiddenStyle);
  8556. item.setState();
  8557. })
  8558. .on('click', function (event) {
  8559. var strLegendItemClick = 'legendItemClick',
  8560. fnLegendItemClick = function () {
  8561. item.setVisible();
  8562. };
  8563. // Pass over the click/touch event. #4.
  8564. event = {
  8565. browserEvent: event
  8566. };
  8567. // click the name or symbol
  8568. if (item.firePointEvent) { // point
  8569. item.firePointEvent(strLegendItemClick, event, fnLegendItemClick);
  8570. } else {
  8571. fireEvent(item, strLegendItemClick, event, fnLegendItemClick);
  8572. }
  8573. });
  8574. // Colorize the items
  8575. legend.colorizeItem(item, item.visible);
  8576. // add the HTML checkbox on top
  8577. if (itemOptions && showCheckbox) {
  8578. item.checkbox = createElement('input', {
  8579. type: 'checkbox',
  8580. checked: item.selected,
  8581. defaultChecked: item.selected // required by IE7
  8582. }, options.itemCheckboxStyle, chart.container);
  8583. addEvent(item.checkbox, 'click', function (event) {
  8584. var target = event.target;
  8585. fireEvent(item, 'checkboxClick', {
  8586. checked: target.checked
  8587. },
  8588. function () {
  8589. item.select();
  8590. }
  8591. );
  8592. });
  8593. }
  8594. }
  8595. // calculate the positions for the next line
  8596. bBox = li.getBBox();
  8597. itemWidth = item.legendItemWidth =
  8598. options.itemWidth || symbolWidth + symbolPadding + bBox.width + padding +
  8599. (showCheckbox ? 20 : 0);
  8600. legend.itemHeight = itemHeight = bBox.height;
  8601. // if the item exceeds the width, start a new line
  8602. if (horizontal && legend.itemX - initialItemX + itemWidth >
  8603. (widthOption || (chart.chartWidth - 2 * padding - initialItemX))) {
  8604. legend.itemX = initialItemX;
  8605. legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom;
  8606. legend.lastLineHeight = 0; // reset for next line
  8607. }
  8608. // If the item exceeds the height, start a new column
  8609. /*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) {
  8610. legend.itemY = legend.initialItemY;
  8611. legend.itemX += legend.maxItemWidth;
  8612. legend.maxItemWidth = 0;
  8613. }*/
  8614. // Set the edge positions
  8615. legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth);
  8616. legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom;
  8617. legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915
  8618. // cache the position of the newly generated or reordered items
  8619. item._legendItemPos = [legend.itemX, legend.itemY];
  8620. // advance
  8621. if (horizontal) {
  8622. legend.itemX += itemWidth;
  8623. } else {
  8624. legend.itemY += itemMarginTop + itemHeight + itemMarginBottom;
  8625. legend.lastLineHeight = itemHeight;
  8626. }
  8627. // the width of the widest item
  8628. legend.offsetWidth = widthOption || mathMax(
  8629. horizontal ? legend.itemX - initialItemX : itemWidth,
  8630. legend.offsetWidth
  8631. );
  8632. },
  8633. /**
  8634. * Render the legend. This method can be called both before and after
  8635. * chart.render. If called after, it will only rearrange items instead
  8636. * of creating new ones.
  8637. */
  8638. render: function () {
  8639. var legend = this,
  8640. chart = legend.chart,
  8641. renderer = chart.renderer,
  8642. legendGroup = legend.group,
  8643. allItems,
  8644. display,
  8645. legendWidth,
  8646. legendHeight,
  8647. box = legend.box,
  8648. options = legend.options,
  8649. padding = legend.padding,
  8650. legendBorderWidth = options.borderWidth,
  8651. legendBackgroundColor = options.backgroundColor;
  8652. legend.itemX = legend.initialItemX;
  8653. legend.itemY = legend.initialItemY;
  8654. legend.offsetWidth = 0;
  8655. legend.lastItemY = 0;
  8656. if (!legendGroup) {
  8657. legend.group = legendGroup = renderer.g('legend')
  8658. .attr({ zIndex: 7 })
  8659. .add();
  8660. legend.contentGroup = renderer.g()
  8661. .attr({ zIndex: 1 }) // above background
  8662. .add(legendGroup);
  8663. legend.scrollGroup = renderer.g()
  8664. .add(legend.contentGroup);
  8665. legend.clipRect = renderer.clipRect(0, 0, 9999, chart.chartHeight);
  8666. legend.contentGroup.clip(legend.clipRect);
  8667. }
  8668. legend.renderTitle();
  8669. // add each series or point
  8670. allItems = [];
  8671. each(chart.series, function (serie) {
  8672. var seriesOptions = serie.options;
  8673. if (!seriesOptions.showInLegend || defined(seriesOptions.linkedTo)) {
  8674. return;
  8675. }
  8676. // use points or series for the legend item depending on legendType
  8677. allItems = allItems.concat(
  8678. serie.legendItems ||
  8679. (seriesOptions.legendType === 'point' ?
  8680. serie.data :
  8681. serie)
  8682. );
  8683. });
  8684. // sort by legendIndex
  8685. stableSort(allItems, function (a, b) {
  8686. return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0);
  8687. });
  8688. // reversed legend
  8689. if (options.reversed) {
  8690. allItems.reverse();
  8691. }
  8692. legend.allItems = allItems;
  8693. legend.display = display = !!allItems.length;
  8694. // render the items
  8695. each(allItems, function (item) {
  8696. legend.renderItem(item);
  8697. });
  8698. // Draw the border
  8699. legendWidth = options.width || legend.offsetWidth;
  8700. legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight;
  8701. legendHeight = legend.handleOverflow(legendHeight);
  8702. if (legendBorderWidth || legendBackgroundColor) {
  8703. legendWidth += padding;
  8704. legendHeight += padding;
  8705. if (!box) {
  8706. legend.box = box = renderer.rect(
  8707. 0,
  8708. 0,
  8709. legendWidth,
  8710. legendHeight,
  8711. options.borderRadius,
  8712. legendBorderWidth || 0
  8713. ).attr({
  8714. stroke: options.borderColor,
  8715. 'stroke-width': legendBorderWidth || 0,
  8716. fill: legendBackgroundColor || NONE
  8717. })
  8718. .add(legendGroup)
  8719. .shadow(options.shadow);
  8720. box.isNew = true;
  8721. } else if (legendWidth > 0 && legendHeight > 0) {
  8722. box[box.isNew ? 'attr' : 'animate'](
  8723. box.crisp(null, null, null, legendWidth, legendHeight)
  8724. );
  8725. box.isNew = false;
  8726. }
  8727. // hide the border if no items
  8728. box[display ? 'show' : 'hide']();
  8729. }
  8730. legend.legendWidth = legendWidth;
  8731. legend.legendHeight = legendHeight;
  8732. // Now that the legend width and height are established, put the items in the
  8733. // final position
  8734. each(allItems, function (item) {
  8735. legend.positionItem(item);
  8736. });
  8737. // 1.x compatibility: positioning based on style
  8738. /*var props = ['left', 'right', 'top', 'bottom'],
  8739. prop,
  8740. i = 4;
  8741. while (i--) {
  8742. prop = props[i];
  8743. if (options.style[prop] && options.style[prop] !== 'auto') {
  8744. options[i < 2 ? 'align' : 'verticalAlign'] = prop;
  8745. options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1);
  8746. }
  8747. }*/
  8748. if (display) {
  8749. legendGroup.align(extend({
  8750. width: legendWidth,
  8751. height: legendHeight
  8752. }, options), true, 'spacingBox');
  8753. }
  8754. if (!chart.isResizing) {
  8755. this.positionCheckboxes();
  8756. }
  8757. },
  8758. /**
  8759. * Set up the overflow handling by adding navigation with up and down arrows below the
  8760. * legend.
  8761. */
  8762. handleOverflow: function (legendHeight) {
  8763. var legend = this,
  8764. chart = this.chart,
  8765. renderer = chart.renderer,
  8766. pageCount,
  8767. options = this.options,
  8768. optionsY = options.y,
  8769. alignTop = options.verticalAlign === 'top',
  8770. spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding,
  8771. maxHeight = options.maxHeight,
  8772. clipHeight,
  8773. clipRect = this.clipRect,
  8774. navOptions = options.navigation,
  8775. animation = pick(navOptions.animation, true),
  8776. arrowSize = navOptions.arrowSize || 12,
  8777. nav = this.nav;
  8778. // Adjust the height
  8779. if (options.layout === 'horizontal') {
  8780. spaceHeight /= 2;
  8781. }
  8782. if (maxHeight) {
  8783. spaceHeight = mathMin(spaceHeight, maxHeight);
  8784. }
  8785. // Reset the legend height and adjust the clipping rectangle
  8786. if (legendHeight > spaceHeight && !options.useHTML) {
  8787. this.clipHeight = clipHeight = spaceHeight - 20 - this.titleHeight;
  8788. this.pageCount = pageCount = mathCeil(legendHeight / clipHeight);
  8789. this.currentPage = pick(this.currentPage, 1);
  8790. this.fullHeight = legendHeight;
  8791. clipRect.attr({
  8792. height: clipHeight
  8793. });
  8794. // Add navigation elements
  8795. if (!nav) {
  8796. this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group);
  8797. this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize)
  8798. .on('click', function () {
  8799. legend.scroll(-1, animation);
  8800. })
  8801. .add(nav);
  8802. this.pager = renderer.text('', 15, 10)
  8803. .css(navOptions.style)
  8804. .add(nav);
  8805. this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize)
  8806. .on('click', function () {
  8807. legend.scroll(1, animation);
  8808. })
  8809. .add(nav);
  8810. }
  8811. // Set initial position
  8812. legend.scroll(0);
  8813. legendHeight = spaceHeight;
  8814. } else if (nav) {
  8815. clipRect.attr({
  8816. height: chart.chartHeight
  8817. });
  8818. nav.hide();
  8819. this.scrollGroup.attr({
  8820. translateY: 1
  8821. });
  8822. this.clipHeight = 0; // #1379
  8823. }
  8824. return legendHeight;
  8825. },
  8826. /**
  8827. * Scroll the legend by a number of pages
  8828. * @param {Object} scrollBy
  8829. * @param {Object} animation
  8830. */
  8831. scroll: function (scrollBy, animation) {
  8832. var pageCount = this.pageCount,
  8833. currentPage = this.currentPage + scrollBy,
  8834. clipHeight = this.clipHeight,
  8835. navOptions = this.options.navigation,
  8836. activeColor = navOptions.activeColor,
  8837. inactiveColor = navOptions.inactiveColor,
  8838. pager = this.pager,
  8839. padding = this.padding,
  8840. scrollOffset;
  8841. // When resizing while looking at the last page
  8842. if (currentPage > pageCount) {
  8843. currentPage = pageCount;
  8844. }
  8845. if (currentPage > 0) {
  8846. if (animation !== UNDEFINED) {
  8847. setAnimation(animation, this.chart);
  8848. }
  8849. this.nav.attr({
  8850. translateX: padding,
  8851. translateY: clipHeight + 7 + this.titleHeight,
  8852. visibility: VISIBLE
  8853. });
  8854. this.up.attr({
  8855. fill: currentPage === 1 ? inactiveColor : activeColor
  8856. })
  8857. .css({
  8858. cursor: currentPage === 1 ? 'default' : 'pointer'
  8859. });
  8860. pager.attr({
  8861. text: currentPage + '/' + this.pageCount
  8862. });
  8863. this.down.attr({
  8864. x: 18 + this.pager.getBBox().width, // adjust to text width
  8865. fill: currentPage === pageCount ? inactiveColor : activeColor
  8866. })
  8867. .css({
  8868. cursor: currentPage === pageCount ? 'default' : 'pointer'
  8869. });
  8870. scrollOffset = -mathMin(clipHeight * (currentPage - 1), this.fullHeight - clipHeight + padding) + 1;
  8871. this.scrollGroup.animate({
  8872. translateY: scrollOffset
  8873. });
  8874. pager.attr({
  8875. text: currentPage + '/' + pageCount
  8876. });
  8877. this.currentPage = currentPage;
  8878. this.positionCheckboxes(scrollOffset);
  8879. }
  8880. }
  8881. };
  8882. /**
  8883. * The chart class
  8884. * @param {Object} options
  8885. * @param {Function} callback Function to run when the chart has loaded
  8886. */
  8887. function Chart() {
  8888. this.init.apply(this, arguments);
  8889. }
  8890. Chart.prototype = {
  8891. /**
  8892. * Initialize the chart
  8893. */
  8894. init: function (userOptions, callback) {
  8895. // Handle regular options
  8896. var options,
  8897. seriesOptions = userOptions.series; // skip merging data points to increase performance
  8898. userOptions.series = null;
  8899. options = merge(defaultOptions, userOptions); // do the merge
  8900. options.series = userOptions.series = seriesOptions; // set back the series data
  8901. var optionsChart = options.chart,
  8902. optionsMargin = optionsChart.margin,
  8903. margin = isObject(optionsMargin) ?
  8904. optionsMargin :
  8905. [optionsMargin, optionsMargin, optionsMargin, optionsMargin];
  8906. this.optionsMarginTop = pick(optionsChart.marginTop, margin[0]);
  8907. this.optionsMarginRight = pick(optionsChart.marginRight, margin[1]);
  8908. this.optionsMarginBottom = pick(optionsChart.marginBottom, margin[2]);
  8909. this.optionsMarginLeft = pick(optionsChart.marginLeft, margin[3]);
  8910. var chartEvents = optionsChart.events;
  8911. this.runChartClick = chartEvents && !!chartEvents.click;
  8912. this.bounds = { h: {}, v: {} }; // Pixel data bounds for touch zoom
  8913. this.callback = callback;
  8914. this.isResizing = 0;
  8915. this.options = options;
  8916. //chartTitleOptions = UNDEFINED;
  8917. //chartSubtitleOptions = UNDEFINED;
  8918. this.axes = [];
  8919. this.series = [];
  8920. this.hasCartesianSeries = optionsChart.showAxes;
  8921. //this.axisOffset = UNDEFINED;
  8922. //this.maxTicks = UNDEFINED; // handle the greatest amount of ticks on grouped axes
  8923. //this.inverted = UNDEFINED;
  8924. //this.loadingShown = UNDEFINED;
  8925. //this.container = UNDEFINED;
  8926. //this.chartWidth = UNDEFINED;
  8927. //this.chartHeight = UNDEFINED;
  8928. //this.marginRight = UNDEFINED;
  8929. //this.marginBottom = UNDEFINED;
  8930. //this.containerWidth = UNDEFINED;
  8931. //this.containerHeight = UNDEFINED;
  8932. //this.oldChartWidth = UNDEFINED;
  8933. //this.oldChartHeight = UNDEFINED;
  8934. //this.renderTo = UNDEFINED;
  8935. //this.renderToClone = UNDEFINED;
  8936. //this.spacingBox = UNDEFINED
  8937. //this.legend = UNDEFINED;
  8938. // Elements
  8939. //this.chartBackground = UNDEFINED;
  8940. //this.plotBackground = UNDEFINED;
  8941. //this.plotBGImage = UNDEFINED;
  8942. //this.plotBorder = UNDEFINED;
  8943. //this.loadingDiv = UNDEFINED;
  8944. //this.loadingSpan = UNDEFINED;
  8945. var chart = this,
  8946. eventType;
  8947. // Add the chart to the global lookup
  8948. chart.index = charts.length;
  8949. charts.push(chart);
  8950. // Set up auto resize
  8951. if (optionsChart.reflow !== false) {
  8952. addEvent(chart, 'load', function () {
  8953. chart.initReflow();
  8954. });
  8955. }
  8956. // Chart event handlers
  8957. if (chartEvents) {
  8958. for (eventType in chartEvents) {
  8959. addEvent(chart, eventType, chartEvents[eventType]);
  8960. }
  8961. }
  8962. chart.xAxis = [];
  8963. chart.yAxis = [];
  8964. // Expose methods and variables
  8965. chart.animation = useCanVG ? false : pick(optionsChart.animation, true);
  8966. chart.pointCount = 0;
  8967. chart.counters = new ChartCounters();
  8968. chart.firstRender();
  8969. },
  8970. /**
  8971. * Initialize an individual series, called internally before render time
  8972. */
  8973. initSeries: function (options) {
  8974. var chart = this,
  8975. optionsChart = chart.options.chart,
  8976. type = options.type || optionsChart.type || optionsChart.defaultSeriesType,
  8977. series,
  8978. constr = seriesTypes[type];
  8979. // No such series type
  8980. if (!constr) {
  8981. error(17, true);
  8982. }
  8983. series = new constr();
  8984. series.init(this, options);
  8985. return series;
  8986. },
  8987. /**
  8988. * Add a series dynamically after time
  8989. *
  8990. * @param {Object} options The config options
  8991. * @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true.
  8992. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  8993. * configuration
  8994. *
  8995. * @return {Object} series The newly created series object
  8996. */
  8997. addSeries: function (options, redraw, animation) {
  8998. var series,
  8999. chart = this;
  9000. if (options) {
  9001. redraw = pick(redraw, true); // defaults to true
  9002. fireEvent(chart, 'addSeries', { options: options }, function () {
  9003. series = chart.initSeries(options);
  9004. chart.isDirtyLegend = true; // the series array is out of sync with the display
  9005. if (redraw) {
  9006. chart.redraw(animation);
  9007. }
  9008. });
  9009. }
  9010. return series;
  9011. },
  9012. /**
  9013. * Add an axis to the chart
  9014. * @param {Object} options The axis option
  9015. * @param {Boolean} isX Whether it is an X axis or a value axis
  9016. */
  9017. addAxis: function (options, isX, redraw, animation) {
  9018. var key = isX ? 'xAxis' : 'yAxis',
  9019. chartOptions = this.options,
  9020. axis;
  9021. /*jslint unused: false*/
  9022. axis = new Axis(this, merge(options, {
  9023. index: this[key].length
  9024. }));
  9025. /*jslint unused: true*/
  9026. // Push the new axis options to the chart options
  9027. chartOptions[key] = splat(chartOptions[key] || {});
  9028. chartOptions[key].push(options);
  9029. if (pick(redraw, true)) {
  9030. this.redraw(animation);
  9031. }
  9032. },
  9033. /**
  9034. * Check whether a given point is within the plot area
  9035. *
  9036. * @param {Number} plotX Pixel x relative to the plot area
  9037. * @param {Number} plotY Pixel y relative to the plot area
  9038. * @param {Boolean} inverted Whether the chart is inverted
  9039. */
  9040. isInsidePlot: function (plotX, plotY, inverted) {
  9041. var x = inverted ? plotY : plotX,
  9042. y = inverted ? plotX : plotY;
  9043. return x >= 0 &&
  9044. x <= this.plotWidth &&
  9045. y >= 0 &&
  9046. y <= this.plotHeight;
  9047. },
  9048. /**
  9049. * Adjust all axes tick amounts
  9050. */
  9051. adjustTickAmounts: function () {
  9052. if (this.options.chart.alignTicks !== false) {
  9053. each(this.axes, function (axis) {
  9054. axis.adjustTickAmount();
  9055. });
  9056. }
  9057. this.maxTicks = null;
  9058. },
  9059. /**
  9060. * Redraw legend, axes or series based on updated data
  9061. *
  9062. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  9063. * configuration
  9064. */
  9065. redraw: function (animation) {
  9066. var chart = this,
  9067. axes = chart.axes,
  9068. series = chart.series,
  9069. pointer = chart.pointer,
  9070. legend = chart.legend,
  9071. redrawLegend = chart.isDirtyLegend,
  9072. hasStackedSeries,
  9073. isDirtyBox = chart.isDirtyBox, // todo: check if it has actually changed?
  9074. seriesLength = series.length,
  9075. i = seriesLength,
  9076. serie,
  9077. renderer = chart.renderer,
  9078. isHiddenChart = renderer.isHidden(),
  9079. afterRedraw = [];
  9080. setAnimation(animation, chart);
  9081. if (isHiddenChart) {
  9082. chart.cloneRenderTo();
  9083. }
  9084. // link stacked series
  9085. while (i--) {
  9086. serie = series[i];
  9087. if (serie.isDirty && serie.options.stacking) {
  9088. hasStackedSeries = true;
  9089. break;
  9090. }
  9091. }
  9092. if (hasStackedSeries) { // mark others as dirty
  9093. i = seriesLength;
  9094. while (i--) {
  9095. serie = series[i];
  9096. if (serie.options.stacking) {
  9097. serie.isDirty = true;
  9098. }
  9099. }
  9100. }
  9101. // handle updated data in the series
  9102. each(series, function (serie) {
  9103. if (serie.isDirty) { // prepare the data so axis can read it
  9104. if (serie.options.legendType === 'point') {
  9105. redrawLegend = true;
  9106. }
  9107. }
  9108. });
  9109. // handle added or removed series
  9110. if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed
  9111. // draw legend graphics
  9112. legend.render();
  9113. chart.isDirtyLegend = false;
  9114. }
  9115. if (chart.hasCartesianSeries) {
  9116. if (!chart.isResizing) {
  9117. // reset maxTicks
  9118. chart.maxTicks = null;
  9119. // set axes scales
  9120. each(axes, function (axis) {
  9121. axis.setScale();
  9122. });
  9123. }
  9124. chart.adjustTickAmounts();
  9125. chart.getMargins();
  9126. // redraw axes
  9127. each(axes, function (axis) {
  9128. // Fire 'afterSetExtremes' only if extremes are set
  9129. if (axis.isDirtyExtremes) { // #821
  9130. axis.isDirtyExtremes = false;
  9131. afterRedraw.push(function () { // prevent a recursive call to chart.redraw() (#1119)
  9132. fireEvent(axis, 'afterSetExtremes', axis.getExtremes()); // #747, #751
  9133. });
  9134. }
  9135. if (axis.isDirty || isDirtyBox || hasStackedSeries) {
  9136. axis.redraw();
  9137. isDirtyBox = true; // #792
  9138. }
  9139. });
  9140. }
  9141. // the plot areas size has changed
  9142. if (isDirtyBox) {
  9143. chart.drawChartBox();
  9144. }
  9145. // redraw affected series
  9146. each(series, function (serie) {
  9147. if (serie.isDirty && serie.visible &&
  9148. (!serie.isCartesian || serie.xAxis)) { // issue #153
  9149. serie.redraw();
  9150. }
  9151. });
  9152. // move tooltip or reset
  9153. if (pointer && pointer.reset) {
  9154. pointer.reset(true);
  9155. }
  9156. // redraw if canvas
  9157. renderer.draw();
  9158. // fire the event
  9159. fireEvent(chart, 'redraw'); // jQuery breaks this when calling it from addEvent. Overwrites chart.redraw
  9160. if (isHiddenChart) {
  9161. chart.cloneRenderTo(true);
  9162. }
  9163. // Fire callbacks that are put on hold until after the redraw
  9164. each(afterRedraw, function (callback) {
  9165. callback.call();
  9166. });
  9167. },
  9168. /**
  9169. * Dim the chart and show a loading text or symbol
  9170. * @param {String} str An optional text to show in the loading label instead of the default one
  9171. */
  9172. showLoading: function (str) {
  9173. var chart = this,
  9174. options = chart.options,
  9175. loadingDiv = chart.loadingDiv;
  9176. var loadingOptions = options.loading;
  9177. // create the layer at the first call
  9178. if (!loadingDiv) {
  9179. chart.loadingDiv = loadingDiv = createElement(DIV, {
  9180. className: PREFIX + 'loading'
  9181. }, extend(loadingOptions.style, {
  9182. zIndex: 10,
  9183. display: NONE
  9184. }), chart.container);
  9185. chart.loadingSpan = createElement(
  9186. 'span',
  9187. null,
  9188. loadingOptions.labelStyle,
  9189. loadingDiv
  9190. );
  9191. }
  9192. // update text
  9193. chart.loadingSpan.innerHTML = str || options.lang.loading;
  9194. // show it
  9195. if (!chart.loadingShown) {
  9196. css(loadingDiv, {
  9197. opacity: 0,
  9198. display: '',
  9199. left: chart.plotLeft + PX,
  9200. top: chart.plotTop + PX,
  9201. width: chart.plotWidth + PX,
  9202. height: chart.plotHeight + PX
  9203. });
  9204. animate(loadingDiv, {
  9205. opacity: loadingOptions.style.opacity
  9206. }, {
  9207. duration: loadingOptions.showDuration || 0
  9208. });
  9209. chart.loadingShown = true;
  9210. }
  9211. },
  9212. /**
  9213. * Hide the loading layer
  9214. */
  9215. hideLoading: function () {
  9216. var options = this.options,
  9217. loadingDiv = this.loadingDiv;
  9218. if (loadingDiv) {
  9219. animate(loadingDiv, {
  9220. opacity: 0
  9221. }, {
  9222. duration: options.loading.hideDuration || 100,
  9223. complete: function () {
  9224. css(loadingDiv, { display: NONE });
  9225. }
  9226. });
  9227. }
  9228. this.loadingShown = false;
  9229. },
  9230. /**
  9231. * Get an axis, series or point object by id.
  9232. * @param id {String} The id as given in the configuration options
  9233. */
  9234. get: function (id) {
  9235. var chart = this,
  9236. axes = chart.axes,
  9237. series = chart.series;
  9238. var i,
  9239. j,
  9240. points;
  9241. // search axes
  9242. for (i = 0; i < axes.length; i++) {
  9243. if (axes[i].options.id === id) {
  9244. return axes[i];
  9245. }
  9246. }
  9247. // search series
  9248. for (i = 0; i < series.length; i++) {
  9249. if (series[i].options.id === id) {
  9250. return series[i];
  9251. }
  9252. }
  9253. // search points
  9254. for (i = 0; i < series.length; i++) {
  9255. points = series[i].points || [];
  9256. for (j = 0; j < points.length; j++) {
  9257. if (points[j].id === id) {
  9258. return points[j];
  9259. }
  9260. }
  9261. }
  9262. return null;
  9263. },
  9264. /**
  9265. * Create the Axis instances based on the config options
  9266. */
  9267. getAxes: function () {
  9268. var chart = this,
  9269. options = this.options,
  9270. xAxisOptions = options.xAxis = splat(options.xAxis || {}),
  9271. yAxisOptions = options.yAxis = splat(options.yAxis || {}),
  9272. optionsArray,
  9273. axis;
  9274. // make sure the options are arrays and add some members
  9275. each(xAxisOptions, function (axis, i) {
  9276. axis.index = i;
  9277. axis.isX = true;
  9278. });
  9279. each(yAxisOptions, function (axis, i) {
  9280. axis.index = i;
  9281. });
  9282. // concatenate all axis options into one array
  9283. optionsArray = xAxisOptions.concat(yAxisOptions);
  9284. each(optionsArray, function (axisOptions) {
  9285. axis = new Axis(chart, axisOptions);
  9286. });
  9287. chart.adjustTickAmounts();
  9288. },
  9289. /**
  9290. * Get the currently selected points from all series
  9291. */
  9292. getSelectedPoints: function () {
  9293. var points = [];
  9294. each(this.series, function (serie) {
  9295. points = points.concat(grep(serie.points || [], function (point) {
  9296. return point.selected;
  9297. }));
  9298. });
  9299. return points;
  9300. },
  9301. /**
  9302. * Get the currently selected series
  9303. */
  9304. getSelectedSeries: function () {
  9305. return grep(this.series, function (serie) {
  9306. return serie.selected;
  9307. });
  9308. },
  9309. /**
  9310. * Display the zoom button
  9311. */
  9312. showResetZoom: function () {
  9313. var chart = this,
  9314. lang = defaultOptions.lang,
  9315. btnOptions = chart.options.chart.resetZoomButton,
  9316. theme = btnOptions.theme,
  9317. states = theme.states,
  9318. alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox';
  9319. this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, function () { chart.zoomOut(); }, theme, states && states.hover)
  9320. .attr({
  9321. align: btnOptions.position.align,
  9322. title: lang.resetZoomTitle
  9323. })
  9324. .add()
  9325. .align(btnOptions.position, false, alignTo);
  9326. },
  9327. /**
  9328. * Zoom out to 1:1
  9329. */
  9330. zoomOut: function () {
  9331. var chart = this;
  9332. fireEvent(chart, 'selection', { resetSelection: true }, function () {
  9333. chart.zoom();
  9334. });
  9335. },
  9336. /**
  9337. * Zoom into a given portion of the chart given by axis coordinates
  9338. * @param {Object} event
  9339. */
  9340. zoom: function (event) {
  9341. var chart = this,
  9342. hasZoomed,
  9343. pointer = chart.pointer,
  9344. displayButton = false,
  9345. resetZoomButton;
  9346. // If zoom is called with no arguments, reset the axes
  9347. if (!event || event.resetSelection) {
  9348. each(chart.axes, function (axis) {
  9349. hasZoomed = axis.zoom();
  9350. });
  9351. } else { // else, zoom in on all axes
  9352. each(event.xAxis.concat(event.yAxis), function (axisData) {
  9353. var axis = axisData.axis,
  9354. isXAxis = axis.isXAxis;
  9355. // don't zoom more than minRange
  9356. if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) {
  9357. hasZoomed = axis.zoom(axisData.min, axisData.max);
  9358. if (axis.displayBtn) {
  9359. displayButton = true;
  9360. }
  9361. }
  9362. });
  9363. }
  9364. // Show or hide the Reset zoom button
  9365. resetZoomButton = chart.resetZoomButton;
  9366. if (displayButton && !resetZoomButton) {
  9367. chart.showResetZoom();
  9368. } else if (!displayButton && isObject(resetZoomButton)) {
  9369. chart.resetZoomButton = resetZoomButton.destroy();
  9370. }
  9371. // Redraw
  9372. if (hasZoomed) {
  9373. chart.redraw(
  9374. pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation
  9375. );
  9376. }
  9377. },
  9378. /**
  9379. * Pan the chart by dragging the mouse across the pane. This function is called
  9380. * on mouse move, and the distance to pan is computed from chartX compared to
  9381. * the first chartX position in the dragging operation.
  9382. */
  9383. pan: function (chartX) {
  9384. var chart = this,
  9385. xAxis = chart.xAxis[0],
  9386. mouseDownX = chart.mouseDownX,
  9387. halfPointRange = xAxis.pointRange / 2,
  9388. extremes = xAxis.getExtremes(),
  9389. newMin = xAxis.translate(mouseDownX - chartX, true) + halfPointRange,
  9390. newMax = xAxis.translate(mouseDownX + chart.plotWidth - chartX, true) - halfPointRange,
  9391. hoverPoints = chart.hoverPoints;
  9392. // remove active points for shared tooltip
  9393. if (hoverPoints) {
  9394. each(hoverPoints, function (point) {
  9395. point.setState();
  9396. });
  9397. }
  9398. if (xAxis.series.length && newMin > mathMin(extremes.dataMin, extremes.min) && newMax < mathMax(extremes.dataMax, extremes.max)) {
  9399. xAxis.setExtremes(newMin, newMax, true, false, { trigger: 'pan' });
  9400. }
  9401. chart.mouseDownX = chartX; // set new reference for next run
  9402. css(chart.container, { cursor: 'move' });
  9403. },
  9404. /**
  9405. * Show the title and subtitle of the chart
  9406. *
  9407. * @param titleOptions {Object} New title options
  9408. * @param subtitleOptions {Object} New subtitle options
  9409. *
  9410. */
  9411. setTitle: function (titleOptions, subtitleOptions) {
  9412. var chart = this,
  9413. options = chart.options,
  9414. chartTitleOptions,
  9415. chartSubtitleOptions;
  9416. chartTitleOptions = options.title = merge(options.title, titleOptions);
  9417. chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions);
  9418. // add title and subtitle
  9419. each([
  9420. ['title', titleOptions, chartTitleOptions],
  9421. ['subtitle', subtitleOptions, chartSubtitleOptions]
  9422. ], function (arr) {
  9423. var name = arr[0],
  9424. title = chart[name],
  9425. titleOptions = arr[1],
  9426. chartTitleOptions = arr[2];
  9427. if (title && titleOptions) {
  9428. chart[name] = title = title.destroy(); // remove old
  9429. }
  9430. if (chartTitleOptions && chartTitleOptions.text && !title) {
  9431. chart[name] = chart.renderer.text(
  9432. chartTitleOptions.text,
  9433. 0,
  9434. 0,
  9435. chartTitleOptions.useHTML
  9436. )
  9437. .attr({
  9438. align: chartTitleOptions.align,
  9439. 'class': PREFIX + name,
  9440. zIndex: chartTitleOptions.zIndex || 4
  9441. })
  9442. .css(chartTitleOptions.style)
  9443. .add()
  9444. .align(chartTitleOptions, false, 'spacingBox');
  9445. }
  9446. });
  9447. },
  9448. /**
  9449. * Get chart width and height according to options and container size
  9450. */
  9451. getChartSize: function () {
  9452. var chart = this,
  9453. optionsChart = chart.options.chart,
  9454. renderTo = chart.renderToClone || chart.renderTo;
  9455. // get inner width and height from jQuery (#824)
  9456. chart.containerWidth = adapterRun(renderTo, 'width');
  9457. chart.containerHeight = adapterRun(renderTo, 'height');
  9458. chart.chartWidth = mathMax(0, optionsChart.width || chart.containerWidth || 600); // #1393, 1460
  9459. chart.chartHeight = mathMax(0, pick(optionsChart.height,
  9460. // the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7:
  9461. chart.containerHeight > 19 ? chart.containerHeight : 400));
  9462. },
  9463. /**
  9464. * Create a clone of the chart's renderTo div and place it outside the viewport to allow
  9465. * size computation on chart.render and chart.redraw
  9466. */
  9467. cloneRenderTo: function (revert) {
  9468. var clone = this.renderToClone,
  9469. container = this.container;
  9470. // Destroy the clone and bring the container back to the real renderTo div
  9471. if (revert) {
  9472. if (clone) {
  9473. this.renderTo.appendChild(container);
  9474. discardElement(clone);
  9475. delete this.renderToClone;
  9476. }
  9477. // Set up the clone
  9478. } else {
  9479. if (container) {
  9480. this.renderTo.removeChild(container); // do not clone this
  9481. }
  9482. this.renderToClone = clone = this.renderTo.cloneNode(0);
  9483. css(clone, {
  9484. position: ABSOLUTE,
  9485. top: '-9999px',
  9486. display: 'block' // #833
  9487. });
  9488. doc.body.appendChild(clone);
  9489. if (container) {
  9490. clone.appendChild(container);
  9491. }
  9492. }
  9493. },
  9494. /**
  9495. * Get the containing element, determine the size and create the inner container
  9496. * div to hold the chart
  9497. */
  9498. getContainer: function () {
  9499. var chart = this,
  9500. container,
  9501. optionsChart = chart.options.chart,
  9502. chartWidth,
  9503. chartHeight,
  9504. renderTo,
  9505. indexAttrName = 'data-highcharts-chart',
  9506. oldChartIndex,
  9507. containerId;
  9508. chart.renderTo = renderTo = optionsChart.renderTo;
  9509. containerId = PREFIX + idCounter++;
  9510. if (isString(renderTo)) {
  9511. chart.renderTo = renderTo = doc.getElementById(renderTo);
  9512. }
  9513. // Display an error if the renderTo is wrong
  9514. if (!renderTo) {
  9515. error(13, true);
  9516. }
  9517. // If the container already holds a chart, destroy it
  9518. oldChartIndex = pInt(attr(renderTo, indexAttrName));
  9519. if (!isNaN(oldChartIndex) && charts[oldChartIndex]) {
  9520. charts[oldChartIndex].destroy();
  9521. }
  9522. // Make a reference to the chart from the div
  9523. attr(renderTo, indexAttrName, chart.index);
  9524. // remove previous chart
  9525. renderTo.innerHTML = '';
  9526. // If the container doesn't have an offsetWidth, it has or is a child of a node
  9527. // that has display:none. We need to temporarily move it out to a visible
  9528. // state to determine the size, else the legend and tooltips won't render
  9529. // properly
  9530. if (!renderTo.offsetWidth) {
  9531. chart.cloneRenderTo();
  9532. }
  9533. // get the width and height
  9534. chart.getChartSize();
  9535. chartWidth = chart.chartWidth;
  9536. chartHeight = chart.chartHeight;
  9537. // create the inner container
  9538. chart.container = container = createElement(DIV, {
  9539. className: PREFIX + 'container' +
  9540. (optionsChart.className ? ' ' + optionsChart.className : ''),
  9541. id: containerId
  9542. }, extend({
  9543. position: RELATIVE,
  9544. overflow: HIDDEN, // needed for context menu (avoid scrollbars) and
  9545. // content overflow in IE
  9546. width: chartWidth + PX,
  9547. height: chartHeight + PX,
  9548. textAlign: 'left',
  9549. lineHeight: 'normal', // #427
  9550. zIndex: 0 // #1072
  9551. }, optionsChart.style),
  9552. chart.renderToClone || renderTo
  9553. );
  9554. // cache the cursor (#1650)
  9555. chart._cursor = container.style.cursor;
  9556. chart.renderer =
  9557. optionsChart.forExport ? // force SVG, used for SVG export
  9558. new SVGRenderer(container, chartWidth, chartHeight, true) :
  9559. new Renderer(container, chartWidth, chartHeight);
  9560. if (useCanVG) {
  9561. // If we need canvg library, extend and configure the renderer
  9562. // to get the tracker for translating mouse events
  9563. chart.renderer.create(chart, container, chartWidth, chartHeight);
  9564. }
  9565. },
  9566. /**
  9567. * Calculate margins by rendering axis labels in a preliminary position. Title,
  9568. * subtitle and legend have already been rendered at this stage, but will be
  9569. * moved into their final positions
  9570. */
  9571. getMargins: function () {
  9572. var chart = this,
  9573. optionsChart = chart.options.chart,
  9574. spacingTop = optionsChart.spacingTop,
  9575. spacingRight = optionsChart.spacingRight,
  9576. spacingBottom = optionsChart.spacingBottom,
  9577. spacingLeft = optionsChart.spacingLeft,
  9578. axisOffset,
  9579. legend = chart.legend,
  9580. optionsMarginTop = chart.optionsMarginTop,
  9581. optionsMarginLeft = chart.optionsMarginLeft,
  9582. optionsMarginRight = chart.optionsMarginRight,
  9583. optionsMarginBottom = chart.optionsMarginBottom,
  9584. chartTitleOptions = chart.options.title,
  9585. chartSubtitleOptions = chart.options.subtitle,
  9586. legendOptions = chart.options.legend,
  9587. legendMargin = pick(legendOptions.margin, 10),
  9588. legendX = legendOptions.x,
  9589. legendY = legendOptions.y,
  9590. align = legendOptions.align,
  9591. verticalAlign = legendOptions.verticalAlign,
  9592. titleOffset;
  9593. chart.resetMargins();
  9594. axisOffset = chart.axisOffset;
  9595. // adjust for title and subtitle
  9596. if ((chart.title || chart.subtitle) && !defined(chart.optionsMarginTop)) {
  9597. titleOffset = mathMax(
  9598. (chart.title && !chartTitleOptions.floating && !chartTitleOptions.verticalAlign && chartTitleOptions.y) || 0,
  9599. (chart.subtitle && !chartSubtitleOptions.floating && !chartSubtitleOptions.verticalAlign && chartSubtitleOptions.y) || 0
  9600. );
  9601. if (titleOffset) {
  9602. chart.plotTop = mathMax(chart.plotTop, titleOffset + pick(chartTitleOptions.margin, 15) + spacingTop);
  9603. }
  9604. }
  9605. // adjust for legend
  9606. if (legend.display && !legendOptions.floating) {
  9607. if (align === 'right') { // horizontal alignment handled first
  9608. if (!defined(optionsMarginRight)) {
  9609. chart.marginRight = mathMax(
  9610. chart.marginRight,
  9611. legend.legendWidth - legendX + legendMargin + spacingRight
  9612. );
  9613. }
  9614. } else if (align === 'left') {
  9615. if (!defined(optionsMarginLeft)) {
  9616. chart.plotLeft = mathMax(
  9617. chart.plotLeft,
  9618. legend.legendWidth + legendX + legendMargin + spacingLeft
  9619. );
  9620. }
  9621. } else if (verticalAlign === 'top') {
  9622. if (!defined(optionsMarginTop)) {
  9623. chart.plotTop = mathMax(
  9624. chart.plotTop,
  9625. legend.legendHeight + legendY + legendMargin + spacingTop
  9626. );
  9627. }
  9628. } else if (verticalAlign === 'bottom') {
  9629. if (!defined(optionsMarginBottom)) {
  9630. chart.marginBottom = mathMax(
  9631. chart.marginBottom,
  9632. legend.legendHeight - legendY + legendMargin + spacingBottom
  9633. );
  9634. }
  9635. }
  9636. }
  9637. // adjust for scroller
  9638. if (chart.extraBottomMargin) {
  9639. chart.marginBottom += chart.extraBottomMargin;
  9640. }
  9641. if (chart.extraTopMargin) {
  9642. chart.plotTop += chart.extraTopMargin;
  9643. }
  9644. // pre-render axes to get labels offset width
  9645. if (chart.hasCartesianSeries) {
  9646. each(chart.axes, function (axis) {
  9647. axis.getOffset();
  9648. });
  9649. }
  9650. if (!defined(optionsMarginLeft)) {
  9651. chart.plotLeft += axisOffset[3];
  9652. }
  9653. if (!defined(optionsMarginTop)) {
  9654. chart.plotTop += axisOffset[0];
  9655. }
  9656. if (!defined(optionsMarginBottom)) {
  9657. chart.marginBottom += axisOffset[2];
  9658. }
  9659. if (!defined(optionsMarginRight)) {
  9660. chart.marginRight += axisOffset[1];
  9661. }
  9662. chart.setChartSize();
  9663. },
  9664. /**
  9665. * Add the event handlers necessary for auto resizing
  9666. *
  9667. */
  9668. initReflow: function () {
  9669. var chart = this,
  9670. optionsChart = chart.options.chart,
  9671. renderTo = chart.renderTo,
  9672. reflowTimeout;
  9673. function reflow(e) {
  9674. var width = optionsChart.width || adapterRun(renderTo, 'width'),
  9675. height = optionsChart.height || adapterRun(renderTo, 'height'),
  9676. target = e ? e.target : win; // #805 - MooTools doesn't supply e
  9677. // Width and height checks for display:none. Target is doc in IE8 and Opera,
  9678. // win in Firefox, Chrome and IE9.
  9679. if (!chart.hasUserSize && width && height && (target === win || target === doc)) {
  9680. if (width !== chart.containerWidth || height !== chart.containerHeight) {
  9681. clearTimeout(reflowTimeout);
  9682. chart.reflowTimeout = reflowTimeout = setTimeout(function () {
  9683. if (chart.container) { // It may have been destroyed in the meantime (#1257)
  9684. chart.setSize(width, height, false);
  9685. chart.hasUserSize = null;
  9686. }
  9687. }, 100);
  9688. }
  9689. chart.containerWidth = width;
  9690. chart.containerHeight = height;
  9691. }
  9692. }
  9693. addEvent(win, 'resize', reflow);
  9694. addEvent(chart, 'destroy', function () {
  9695. removeEvent(win, 'resize', reflow);
  9696. });
  9697. },
  9698. /**
  9699. * Resize the chart to a given width and height
  9700. * @param {Number} width
  9701. * @param {Number} height
  9702. * @param {Object|Boolean} animation
  9703. */
  9704. setSize: function (width, height, animation) {
  9705. var chart = this,
  9706. chartWidth,
  9707. chartHeight,
  9708. fireEndResize;
  9709. // Handle the isResizing counter
  9710. chart.isResizing += 1;
  9711. fireEndResize = function () {
  9712. if (chart) {
  9713. fireEvent(chart, 'endResize', null, function () {
  9714. chart.isResizing -= 1;
  9715. });
  9716. }
  9717. };
  9718. // set the animation for the current process
  9719. setAnimation(animation, chart);
  9720. chart.oldChartHeight = chart.chartHeight;
  9721. chart.oldChartWidth = chart.chartWidth;
  9722. if (defined(width)) {
  9723. chart.chartWidth = chartWidth = mathMax(0, mathRound(width));
  9724. chart.hasUserSize = !!chartWidth;
  9725. }
  9726. if (defined(height)) {
  9727. chart.chartHeight = chartHeight = mathMax(0, mathRound(height));
  9728. }
  9729. css(chart.container, {
  9730. width: chartWidth + PX,
  9731. height: chartHeight + PX
  9732. });
  9733. chart.setChartSize(true);
  9734. chart.renderer.setSize(chartWidth, chartHeight, animation);
  9735. // handle axes
  9736. chart.maxTicks = null;
  9737. each(chart.axes, function (axis) {
  9738. axis.isDirty = true;
  9739. axis.setScale();
  9740. });
  9741. // make sure non-cartesian series are also handled
  9742. each(chart.series, function (serie) {
  9743. serie.isDirty = true;
  9744. });
  9745. chart.isDirtyLegend = true; // force legend redraw
  9746. chart.isDirtyBox = true; // force redraw of plot and chart border
  9747. chart.getMargins();
  9748. chart.redraw(animation);
  9749. chart.oldChartHeight = null;
  9750. fireEvent(chart, 'resize');
  9751. // fire endResize and set isResizing back
  9752. // If animation is disabled, fire without delay
  9753. if (globalAnimation === false) {
  9754. fireEndResize();
  9755. } else { // else set a timeout with the animation duration
  9756. setTimeout(fireEndResize, (globalAnimation && globalAnimation.duration) || 500);
  9757. }
  9758. },
  9759. /**
  9760. * Set the public chart properties. This is done before and after the pre-render
  9761. * to determine margin sizes
  9762. */
  9763. setChartSize: function (skipAxes) {
  9764. var chart = this,
  9765. inverted = chart.inverted,
  9766. renderer = chart.renderer,
  9767. chartWidth = chart.chartWidth,
  9768. chartHeight = chart.chartHeight,
  9769. optionsChart = chart.options.chart,
  9770. spacingTop = optionsChart.spacingTop,
  9771. spacingRight = optionsChart.spacingRight,
  9772. spacingBottom = optionsChart.spacingBottom,
  9773. spacingLeft = optionsChart.spacingLeft,
  9774. clipOffset = chart.clipOffset,
  9775. clipX,
  9776. clipY,
  9777. plotLeft,
  9778. plotTop,
  9779. plotWidth,
  9780. plotHeight,
  9781. plotBorderWidth;
  9782. chart.plotLeft = plotLeft = mathRound(chart.plotLeft);
  9783. chart.plotTop = plotTop = mathRound(chart.plotTop);
  9784. chart.plotWidth = plotWidth = mathMax(0, mathRound(chartWidth - plotLeft - chart.marginRight));
  9785. chart.plotHeight = plotHeight = mathMax(0, mathRound(chartHeight - plotTop - chart.marginBottom));
  9786. chart.plotSizeX = inverted ? plotHeight : plotWidth;
  9787. chart.plotSizeY = inverted ? plotWidth : plotHeight;
  9788. chart.plotBorderWidth = plotBorderWidth = optionsChart.plotBorderWidth || 0;
  9789. // Set boxes used for alignment
  9790. chart.spacingBox = renderer.spacingBox = {
  9791. x: spacingLeft,
  9792. y: spacingTop,
  9793. width: chartWidth - spacingLeft - spacingRight,
  9794. height: chartHeight - spacingTop - spacingBottom
  9795. };
  9796. chart.plotBox = renderer.plotBox = {
  9797. x: plotLeft,
  9798. y: plotTop,
  9799. width: plotWidth,
  9800. height: plotHeight
  9801. };
  9802. clipX = mathCeil(mathMax(plotBorderWidth, clipOffset[3]) / 2);
  9803. clipY = mathCeil(mathMax(plotBorderWidth, clipOffset[0]) / 2);
  9804. chart.clipBox = {
  9805. x: clipX,
  9806. y: clipY,
  9807. width: mathFloor(chart.plotSizeX - mathMax(plotBorderWidth, clipOffset[1]) / 2 - clipX),
  9808. height: mathFloor(chart.plotSizeY - mathMax(plotBorderWidth, clipOffset[2]) / 2 - clipY)
  9809. };
  9810. if (!skipAxes) {
  9811. each(chart.axes, function (axis) {
  9812. axis.setAxisSize();
  9813. axis.setAxisTranslation();
  9814. });
  9815. }
  9816. },
  9817. /**
  9818. * Initial margins before auto size margins are applied
  9819. */
  9820. resetMargins: function () {
  9821. var chart = this,
  9822. optionsChart = chart.options.chart,
  9823. spacingTop = optionsChart.spacingTop,
  9824. spacingRight = optionsChart.spacingRight,
  9825. spacingBottom = optionsChart.spacingBottom,
  9826. spacingLeft = optionsChart.spacingLeft;
  9827. chart.plotTop = pick(chart.optionsMarginTop, spacingTop);
  9828. chart.marginRight = pick(chart.optionsMarginRight, spacingRight);
  9829. chart.marginBottom = pick(chart.optionsMarginBottom, spacingBottom);
  9830. chart.plotLeft = pick(chart.optionsMarginLeft, spacingLeft);
  9831. chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left
  9832. chart.clipOffset = [0, 0, 0, 0];
  9833. },
  9834. /**
  9835. * Draw the borders and backgrounds for chart and plot area
  9836. */
  9837. drawChartBox: function () {
  9838. var chart = this,
  9839. optionsChart = chart.options.chart,
  9840. renderer = chart.renderer,
  9841. chartWidth = chart.chartWidth,
  9842. chartHeight = chart.chartHeight,
  9843. chartBackground = chart.chartBackground,
  9844. plotBackground = chart.plotBackground,
  9845. plotBorder = chart.plotBorder,
  9846. plotBGImage = chart.plotBGImage,
  9847. chartBorderWidth = optionsChart.borderWidth || 0,
  9848. chartBackgroundColor = optionsChart.backgroundColor,
  9849. plotBackgroundColor = optionsChart.plotBackgroundColor,
  9850. plotBackgroundImage = optionsChart.plotBackgroundImage,
  9851. plotBorderWidth = optionsChart.plotBorderWidth || 0,
  9852. mgn,
  9853. bgAttr,
  9854. plotLeft = chart.plotLeft,
  9855. plotTop = chart.plotTop,
  9856. plotWidth = chart.plotWidth,
  9857. plotHeight = chart.plotHeight,
  9858. plotBox = chart.plotBox,
  9859. clipRect = chart.clipRect,
  9860. clipBox = chart.clipBox;
  9861. // Chart area
  9862. mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0);
  9863. if (chartBorderWidth || chartBackgroundColor) {
  9864. if (!chartBackground) {
  9865. bgAttr = {
  9866. fill: chartBackgroundColor || NONE
  9867. };
  9868. if (chartBorderWidth) { // #980
  9869. bgAttr.stroke = optionsChart.borderColor;
  9870. bgAttr['stroke-width'] = chartBorderWidth;
  9871. }
  9872. chart.chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn,
  9873. optionsChart.borderRadius, chartBorderWidth)
  9874. .attr(bgAttr)
  9875. .add()
  9876. .shadow(optionsChart.shadow);
  9877. } else { // resize
  9878. chartBackground.animate(
  9879. chartBackground.crisp(null, null, null, chartWidth - mgn, chartHeight - mgn)
  9880. );
  9881. }
  9882. }
  9883. // Plot background
  9884. if (plotBackgroundColor) {
  9885. if (!plotBackground) {
  9886. chart.plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0)
  9887. .attr({
  9888. fill: plotBackgroundColor
  9889. })
  9890. .add()
  9891. .shadow(optionsChart.plotShadow);
  9892. } else {
  9893. plotBackground.animate(plotBox);
  9894. }
  9895. }
  9896. if (plotBackgroundImage) {
  9897. if (!plotBGImage) {
  9898. chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight)
  9899. .add();
  9900. } else {
  9901. plotBGImage.animate(plotBox);
  9902. }
  9903. }
  9904. // Plot clip
  9905. if (!clipRect) {
  9906. chart.clipRect = renderer.clipRect(clipBox);
  9907. } else {
  9908. clipRect.animate({
  9909. width: clipBox.width,
  9910. height: clipBox.height
  9911. });
  9912. }
  9913. // Plot area border
  9914. if (plotBorderWidth) {
  9915. if (!plotBorder) {
  9916. chart.plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, plotBorderWidth)
  9917. .attr({
  9918. stroke: optionsChart.plotBorderColor,
  9919. 'stroke-width': plotBorderWidth,
  9920. zIndex: 1
  9921. })
  9922. .add();
  9923. } else {
  9924. plotBorder.animate(
  9925. plotBorder.crisp(null, plotLeft, plotTop, plotWidth, plotHeight)
  9926. );
  9927. }
  9928. }
  9929. // reset
  9930. chart.isDirtyBox = false;
  9931. },
  9932. /**
  9933. * Detect whether a certain chart property is needed based on inspecting its options
  9934. * and series. This mainly applies to the chart.invert property, and in extensions to
  9935. * the chart.angular and chart.polar properties.
  9936. */
  9937. propFromSeries: function () {
  9938. var chart = this,
  9939. optionsChart = chart.options.chart,
  9940. klass,
  9941. seriesOptions = chart.options.series,
  9942. i,
  9943. value;
  9944. each(['inverted', 'angular', 'polar'], function (key) {
  9945. // The default series type's class
  9946. klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType];
  9947. // Get the value from available chart-wide properties
  9948. value = (
  9949. chart[key] || // 1. it is set before
  9950. optionsChart[key] || // 2. it is set in the options
  9951. (klass && klass.prototype[key]) // 3. it's default series class requires it
  9952. );
  9953. // 4. Check if any the chart's series require it
  9954. i = seriesOptions && seriesOptions.length;
  9955. while (!value && i--) {
  9956. klass = seriesTypes[seriesOptions[i].type];
  9957. if (klass && klass.prototype[key]) {
  9958. value = true;
  9959. }
  9960. }
  9961. // Set the chart property
  9962. chart[key] = value;
  9963. });
  9964. },
  9965. /**
  9966. * Render all graphics for the chart
  9967. */
  9968. render: function () {
  9969. var chart = this,
  9970. axes = chart.axes,
  9971. renderer = chart.renderer,
  9972. options = chart.options;
  9973. var labels = options.labels,
  9974. credits = options.credits,
  9975. creditsHref;
  9976. // Title
  9977. chart.setTitle();
  9978. // Legend
  9979. chart.legend = new Legend(chart, options.legend);
  9980. // Get margins by pre-rendering axes
  9981. // set axes scales
  9982. each(axes, function (axis) {
  9983. axis.setScale();
  9984. });
  9985. chart.getMargins();
  9986. chart.maxTicks = null; // reset for second pass
  9987. each(axes, function (axis) {
  9988. axis.setTickPositions(true); // update to reflect the new margins
  9989. axis.setMaxTicks();
  9990. });
  9991. chart.adjustTickAmounts();
  9992. chart.getMargins(); // second pass to check for new labels
  9993. // Draw the borders and backgrounds
  9994. chart.drawChartBox();
  9995. // Axes
  9996. if (chart.hasCartesianSeries) {
  9997. each(axes, function (axis) {
  9998. axis.render();
  9999. });
  10000. }
  10001. // The series
  10002. if (!chart.seriesGroup) {
  10003. chart.seriesGroup = renderer.g('series-group')
  10004. .attr({ zIndex: 3 })
  10005. .add();
  10006. }
  10007. each(chart.series, function (serie) {
  10008. serie.translate();
  10009. serie.setTooltipPoints();
  10010. serie.render();
  10011. });
  10012. // Labels
  10013. if (labels.items) {
  10014. each(labels.items, function (label) {
  10015. var style = extend(labels.style, label.style),
  10016. x = pInt(style.left) + chart.plotLeft,
  10017. y = pInt(style.top) + chart.plotTop + 12;
  10018. // delete to prevent rewriting in IE
  10019. delete style.left;
  10020. delete style.top;
  10021. renderer.text(
  10022. label.html,
  10023. x,
  10024. y
  10025. )
  10026. .attr({ zIndex: 2 })
  10027. .css(style)
  10028. .add();
  10029. });
  10030. }
  10031. // Credits
  10032. if (credits.enabled && !chart.credits) {
  10033. creditsHref = credits.href;
  10034. chart.credits = renderer.text(
  10035. credits.text,
  10036. 0,
  10037. 0
  10038. )
  10039. .on('click', function () {
  10040. if (creditsHref) {
  10041. location.href = creditsHref;
  10042. }
  10043. })
  10044. .attr({
  10045. align: credits.position.align,
  10046. zIndex: 8
  10047. })
  10048. .css(credits.style)
  10049. .add()
  10050. .align(credits.position);
  10051. }
  10052. // Set flag
  10053. chart.hasRendered = true;
  10054. },
  10055. /**
  10056. * Clean up memory usage
  10057. */
  10058. destroy: function () {
  10059. var chart = this,
  10060. axes = chart.axes,
  10061. series = chart.series,
  10062. container = chart.container,
  10063. i,
  10064. parentNode = container && container.parentNode;
  10065. // fire the chart.destoy event
  10066. fireEvent(chart, 'destroy');
  10067. // Delete the chart from charts lookup array
  10068. charts[chart.index] = UNDEFINED;
  10069. chart.renderTo.removeAttribute('data-highcharts-chart');
  10070. // remove events
  10071. removeEvent(chart);
  10072. // ==== Destroy collections:
  10073. // Destroy axes
  10074. i = axes.length;
  10075. while (i--) {
  10076. axes[i] = axes[i].destroy();
  10077. }
  10078. // Destroy each series
  10079. i = series.length;
  10080. while (i--) {
  10081. series[i] = series[i].destroy();
  10082. }
  10083. // ==== Destroy chart properties:
  10084. each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage',
  10085. 'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer', 'scroller',
  10086. 'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'], function (name) {
  10087. var prop = chart[name];
  10088. if (prop && prop.destroy) {
  10089. chart[name] = prop.destroy();
  10090. }
  10091. });
  10092. // remove container and all SVG
  10093. if (container) { // can break in IE when destroyed before finished loading
  10094. container.innerHTML = '';
  10095. removeEvent(container);
  10096. if (parentNode) {
  10097. discardElement(container);
  10098. }
  10099. }
  10100. // clean it all up
  10101. for (i in chart) {
  10102. delete chart[i];
  10103. }
  10104. },
  10105. /**
  10106. * VML namespaces can't be added until after complete. Listening
  10107. * for Perini's doScroll hack is not enough.
  10108. */
  10109. isReadyToRender: function () {
  10110. var chart = this;
  10111. // Note: in spite of JSLint's complaints, win == win.top is required
  10112. /*jslint eqeq: true*/
  10113. if ((!hasSVG && (win == win.top && doc.readyState !== 'complete')) || (useCanVG && !win.canvg)) {
  10114. /*jslint eqeq: false*/
  10115. if (useCanVG) {
  10116. // Delay rendering until canvg library is downloaded and ready
  10117. CanVGController.push(function () { chart.firstRender(); }, chart.options.global.canvasToolsURL);
  10118. } else {
  10119. doc.attachEvent('onreadystatechange', function () {
  10120. doc.detachEvent('onreadystatechange', chart.firstRender);
  10121. if (doc.readyState === 'complete') {
  10122. chart.firstRender();
  10123. }
  10124. });
  10125. }
  10126. return false;
  10127. }
  10128. return true;
  10129. },
  10130. /**
  10131. * Prepare for first rendering after all data are loaded
  10132. */
  10133. firstRender: function () {
  10134. var chart = this,
  10135. options = chart.options,
  10136. callback = chart.callback;
  10137. // Check whether the chart is ready to render
  10138. if (!chart.isReadyToRender()) {
  10139. return;
  10140. }
  10141. // Create the container
  10142. chart.getContainer();
  10143. // Run an early event after the container and renderer are established
  10144. fireEvent(chart, 'init');
  10145. chart.resetMargins();
  10146. chart.setChartSize();
  10147. // Set the common chart properties (mainly invert) from the given series
  10148. chart.propFromSeries();
  10149. // get axes
  10150. chart.getAxes();
  10151. // Initialize the series
  10152. each(options.series || [], function (serieOptions) {
  10153. chart.initSeries(serieOptions);
  10154. });
  10155. // Run an event after axes and series are initialized, but before render. At this stage,
  10156. // the series data is indexed and cached in the xData and yData arrays, so we can access
  10157. // those before rendering. Used in Highstock.
  10158. fireEvent(chart, 'beforeRender');
  10159. // depends on inverted and on margins being set
  10160. chart.pointer = new Pointer(chart, options);
  10161. chart.render();
  10162. // add canvas
  10163. chart.renderer.draw();
  10164. // run callbacks
  10165. if (callback) {
  10166. callback.apply(chart, [chart]);
  10167. }
  10168. each(chart.callbacks, function (fn) {
  10169. fn.apply(chart, [chart]);
  10170. });
  10171. // If the chart was rendered outside the top container, put it back in
  10172. chart.cloneRenderTo(true);
  10173. fireEvent(chart, 'load');
  10174. }
  10175. }; // end Chart
  10176. // Hook for exporting module
  10177. Chart.prototype.callbacks = [];
  10178. /**
  10179. * The Point object and prototype. Inheritable and used as base for PiePoint
  10180. */
  10181. var Point = function () {};
  10182. Point.prototype = {
  10183. /**
  10184. * Initialize the point
  10185. * @param {Object} series The series object containing this point
  10186. * @param {Object} options The data in either number, array or object format
  10187. */
  10188. init: function (series, options, x) {
  10189. var point = this,
  10190. colors;
  10191. point.series = series;
  10192. point.applyOptions(options, x);
  10193. point.pointAttr = {};
  10194. if (series.options.colorByPoint) {
  10195. colors = series.options.colors || series.chart.options.colors;
  10196. point.color = point.color || colors[series.colorCounter++];
  10197. // loop back to zero
  10198. if (series.colorCounter === colors.length) {
  10199. series.colorCounter = 0;
  10200. }
  10201. }
  10202. series.chart.pointCount++;
  10203. return point;
  10204. },
  10205. /**
  10206. * Apply the options containing the x and y data and possible some extra properties.
  10207. * This is called on point init or from point.update.
  10208. *
  10209. * @param {Object} options
  10210. */
  10211. applyOptions: function (options, x) {
  10212. var point = this,
  10213. series = point.series,
  10214. pointValKey = series.pointValKey;
  10215. options = Point.prototype.optionsToObject.call(this, options);
  10216. // copy options directly to point
  10217. extend(point, options);
  10218. point.options = point.options ? extend(point.options, options) : options;
  10219. // For higher dimension series types. For instance, for ranges, point.y is mapped to point.low.
  10220. if (pointValKey) {
  10221. point.y = point[pointValKey];
  10222. }
  10223. // If no x is set by now, get auto incremented value. All points must have an
  10224. // x value, however the y value can be null to create a gap in the series
  10225. if (point.x === UNDEFINED && series) {
  10226. point.x = x === UNDEFINED ? series.autoIncrement() : x;
  10227. }
  10228. return point;
  10229. },
  10230. /**
  10231. * Transform number or array configs into objects
  10232. */
  10233. optionsToObject: function (options) {
  10234. var ret,
  10235. series = this.series,
  10236. pointArrayMap = series.pointArrayMap || ['y'],
  10237. valueCount = pointArrayMap.length,
  10238. firstItemType,
  10239. i = 0,
  10240. j = 0;
  10241. if (typeof options === 'number' || options === null) {
  10242. ret = { y: options };
  10243. } else if (isArray(options)) {
  10244. ret = {};
  10245. // with leading x value
  10246. if (options.length > valueCount) {
  10247. firstItemType = typeof options[0];
  10248. if (firstItemType === 'string') {
  10249. ret.name = options[0];
  10250. } else if (firstItemType === 'number') {
  10251. ret.x = options[0];
  10252. }
  10253. i++;
  10254. }
  10255. while (j < valueCount) {
  10256. ret[pointArrayMap[j++]] = options[i++];
  10257. }
  10258. } else if (typeof options === 'object') {
  10259. ret = options;
  10260. // This is the fastest way to detect if there are individual point dataLabels that need
  10261. // to be considered in drawDataLabels. These can only occur in object configs.
  10262. if (options.dataLabels) {
  10263. series._hasPointLabels = true;
  10264. }
  10265. // Same approach as above for markers
  10266. if (options.marker) {
  10267. series._hasPointMarkers = true;
  10268. }
  10269. }
  10270. return ret;
  10271. },
  10272. /**
  10273. * Destroy a point to clear memory. Its reference still stays in series.data.
  10274. */
  10275. destroy: function () {
  10276. var point = this,
  10277. series = point.series,
  10278. chart = series.chart,
  10279. hoverPoints = chart.hoverPoints,
  10280. prop;
  10281. chart.pointCount--;
  10282. if (hoverPoints) {
  10283. point.setState();
  10284. erase(hoverPoints, point);
  10285. if (!hoverPoints.length) {
  10286. chart.hoverPoints = null;
  10287. }
  10288. }
  10289. if (point === chart.hoverPoint) {
  10290. point.onMouseOut();
  10291. }
  10292. // remove all events
  10293. if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive
  10294. removeEvent(point);
  10295. point.destroyElements();
  10296. }
  10297. if (point.legendItem) { // pies have legend items
  10298. chart.legend.destroyItem(point);
  10299. }
  10300. for (prop in point) {
  10301. point[prop] = null;
  10302. }
  10303. },
  10304. /**
  10305. * Destroy SVG elements associated with the point
  10306. */
  10307. destroyElements: function () {
  10308. var point = this,
  10309. props = ['graphic', 'dataLabel', 'dataLabelUpper', 'group', 'connector', 'shadowGroup'],
  10310. prop,
  10311. i = 6;
  10312. while (i--) {
  10313. prop = props[i];
  10314. if (point[prop]) {
  10315. point[prop] = point[prop].destroy();
  10316. }
  10317. }
  10318. },
  10319. /**
  10320. * Return the configuration hash needed for the data label and tooltip formatters
  10321. */
  10322. getLabelConfig: function () {
  10323. var point = this;
  10324. return {
  10325. x: point.category,
  10326. y: point.y,
  10327. key: point.name || point.category,
  10328. series: point.series,
  10329. point: point,
  10330. percentage: point.percentage,
  10331. total: point.total || point.stackTotal
  10332. };
  10333. },
  10334. /**
  10335. * Toggle the selection status of a point
  10336. * @param {Boolean} selected Whether to select or unselect the point.
  10337. * @param {Boolean} accumulate Whether to add to the previous selection. By default,
  10338. * this happens if the control key (Cmd on Mac) was pressed during clicking.
  10339. */
  10340. select: function (selected, accumulate) {
  10341. var point = this,
  10342. series = point.series,
  10343. chart = series.chart;
  10344. selected = pick(selected, !point.selected);
  10345. // fire the event with the defalut handler
  10346. point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () {
  10347. point.selected = point.options.selected = selected;
  10348. series.options.data[inArray(point, series.data)] = point.options;
  10349. point.setState(selected && SELECT_STATE);
  10350. // unselect all other points unless Ctrl or Cmd + click
  10351. if (!accumulate) {
  10352. each(chart.getSelectedPoints(), function (loopPoint) {
  10353. if (loopPoint.selected && loopPoint !== point) {
  10354. loopPoint.selected = loopPoint.options.selected = false;
  10355. series.options.data[inArray(loopPoint, series.data)] = loopPoint.options;
  10356. loopPoint.setState(NORMAL_STATE);
  10357. loopPoint.firePointEvent('unselect');
  10358. }
  10359. });
  10360. }
  10361. });
  10362. },
  10363. /**
  10364. * Runs on mouse over the point
  10365. */
  10366. onMouseOver: function (e) {
  10367. var point = this,
  10368. series = point.series,
  10369. chart = series.chart,
  10370. tooltip = chart.tooltip,
  10371. hoverPoint = chart.hoverPoint;
  10372. // set normal state to previous series
  10373. if (hoverPoint && hoverPoint !== point) {
  10374. hoverPoint.onMouseOut();
  10375. }
  10376. // trigger the event
  10377. point.firePointEvent('mouseOver');
  10378. // update the tooltip
  10379. if (tooltip && (!tooltip.shared || series.noSharedTooltip)) {
  10380. tooltip.refresh(point, e);
  10381. }
  10382. // hover this
  10383. point.setState(HOVER_STATE);
  10384. chart.hoverPoint = point;
  10385. },
  10386. /**
  10387. * Runs on mouse out from the point
  10388. */
  10389. onMouseOut: function () {
  10390. var chart = this.series.chart,
  10391. hoverPoints = chart.hoverPoints;
  10392. if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887
  10393. this.firePointEvent('mouseOut');
  10394. this.setState();
  10395. chart.hoverPoint = null;
  10396. }
  10397. },
  10398. /**
  10399. * Extendable method for formatting each point's tooltip line
  10400. *
  10401. * @return {String} A string to be concatenated in to the common tooltip text
  10402. */
  10403. tooltipFormatter: function (pointFormat) {
  10404. // Insert options for valueDecimals, valuePrefix, and valueSuffix
  10405. var series = this.series,
  10406. seriesTooltipOptions = series.tooltipOptions,
  10407. valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''),
  10408. valuePrefix = seriesTooltipOptions.valuePrefix || '',
  10409. valueSuffix = seriesTooltipOptions.valueSuffix || '';
  10410. // Loop over the point array map and replace unformatted values with sprintf formatting markup
  10411. each(series.pointArrayMap || ['y'], function (key) {
  10412. key = '{point.' + key; // without the closing bracket
  10413. if (valuePrefix || valueSuffix) {
  10414. pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix);
  10415. }
  10416. pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}');
  10417. });
  10418. return format(pointFormat, {
  10419. point: this,
  10420. series: this.series
  10421. });
  10422. },
  10423. /**
  10424. * Update the point with new options (typically x/y data) and optionally redraw the series.
  10425. *
  10426. * @param {Object} options Point options as defined in the series.data array
  10427. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  10428. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  10429. * configuration
  10430. *
  10431. */
  10432. update: function (options, redraw, animation) {
  10433. var point = this,
  10434. series = point.series,
  10435. graphic = point.graphic,
  10436. i,
  10437. data = series.data,
  10438. chart = series.chart;
  10439. redraw = pick(redraw, true);
  10440. // fire the event with a default handler of doing the update
  10441. point.firePointEvent('update', { options: options }, function () {
  10442. point.applyOptions(options);
  10443. // update visuals
  10444. if (isObject(options)) {
  10445. series.getAttribs();
  10446. if (graphic) {
  10447. graphic.attr(point.pointAttr[series.state]);
  10448. }
  10449. }
  10450. // record changes in the parallel arrays
  10451. i = inArray(point, data);
  10452. series.xData[i] = point.x;
  10453. series.yData[i] = series.toYData ? series.toYData(point) : point.y;
  10454. series.zData[i] = point.z;
  10455. series.options.data[i] = point.options;
  10456. // redraw
  10457. series.isDirty = true;
  10458. series.isDirtyData = true;
  10459. if (redraw) {
  10460. chart.redraw(animation);
  10461. }
  10462. });
  10463. },
  10464. /**
  10465. * Remove a point and optionally redraw the series and if necessary the axes
  10466. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  10467. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  10468. * configuration
  10469. */
  10470. remove: function (redraw, animation) {
  10471. var point = this,
  10472. series = point.series,
  10473. chart = series.chart,
  10474. i,
  10475. data = series.data;
  10476. setAnimation(animation, chart);
  10477. redraw = pick(redraw, true);
  10478. // fire the event with a default handler of removing the point
  10479. point.firePointEvent('remove', null, function () {
  10480. // splice all the parallel arrays
  10481. i = inArray(point, data);
  10482. data.splice(i, 1);
  10483. series.options.data.splice(i, 1);
  10484. series.xData.splice(i, 1);
  10485. series.yData.splice(i, 1);
  10486. series.zData.splice(i, 1);
  10487. point.destroy();
  10488. // redraw
  10489. series.isDirty = true;
  10490. series.isDirtyData = true;
  10491. if (redraw) {
  10492. chart.redraw();
  10493. }
  10494. });
  10495. },
  10496. /**
  10497. * Fire an event on the Point object. Must not be renamed to fireEvent, as this
  10498. * causes a name clash in MooTools
  10499. * @param {String} eventType
  10500. * @param {Object} eventArgs Additional event arguments
  10501. * @param {Function} defaultFunction Default event handler
  10502. */
  10503. firePointEvent: function (eventType, eventArgs, defaultFunction) {
  10504. var point = this,
  10505. series = this.series,
  10506. seriesOptions = series.options;
  10507. // load event handlers on demand to save time on mouseover/out
  10508. if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) {
  10509. this.importEvents();
  10510. }
  10511. // add default handler if in selection mode
  10512. if (eventType === 'click' && seriesOptions.allowPointSelect) {
  10513. defaultFunction = function (event) {
  10514. // Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera
  10515. point.select(null, event.ctrlKey || event.metaKey || event.shiftKey);
  10516. };
  10517. }
  10518. fireEvent(this, eventType, eventArgs, defaultFunction);
  10519. },
  10520. /**
  10521. * Import events from the series' and point's options. Only do it on
  10522. * demand, to save processing time on hovering.
  10523. */
  10524. importEvents: function () {
  10525. if (!this.hasImportedEvents) {
  10526. var point = this,
  10527. options = merge(point.series.options.point, point.options),
  10528. events = options.events,
  10529. eventType;
  10530. point.events = events;
  10531. for (eventType in events) {
  10532. addEvent(point, eventType, events[eventType]);
  10533. }
  10534. this.hasImportedEvents = true;
  10535. }
  10536. },
  10537. /**
  10538. * Set the point's state
  10539. * @param {String} state
  10540. */
  10541. setState: function (state) {
  10542. var point = this,
  10543. plotX = point.plotX,
  10544. plotY = point.plotY,
  10545. series = point.series,
  10546. stateOptions = series.options.states,
  10547. markerOptions = defaultPlotOptions[series.type].marker && series.options.marker,
  10548. normalDisabled = markerOptions && !markerOptions.enabled,
  10549. markerStateOptions = markerOptions && markerOptions.states[state],
  10550. stateDisabled = markerStateOptions && markerStateOptions.enabled === false,
  10551. stateMarkerGraphic = series.stateMarkerGraphic,
  10552. pointMarker = point.marker || {},
  10553. chart = series.chart,
  10554. radius,
  10555. newSymbol,
  10556. pointAttr = point.pointAttr;
  10557. state = state || NORMAL_STATE; // empty string
  10558. if (
  10559. // already has this state
  10560. state === point.state ||
  10561. // selected points don't respond to hover
  10562. (point.selected && state !== SELECT_STATE) ||
  10563. // series' state options is disabled
  10564. (stateOptions[state] && stateOptions[state].enabled === false) ||
  10565. // point marker's state options is disabled
  10566. (state && (stateDisabled || (normalDisabled && !markerStateOptions.enabled)))
  10567. ) {
  10568. return;
  10569. }
  10570. // apply hover styles to the existing point
  10571. if (point.graphic) {
  10572. radius = markerOptions && point.graphic.symbolName && pointAttr[state].r;
  10573. point.graphic.attr(merge(
  10574. pointAttr[state],
  10575. radius ? { // new symbol attributes (#507, #612)
  10576. x: plotX - radius,
  10577. y: plotY - radius,
  10578. width: 2 * radius,
  10579. height: 2 * radius
  10580. } : {}
  10581. ));
  10582. } else {
  10583. // if a graphic is not applied to each point in the normal state, create a shared
  10584. // graphic for the hover state
  10585. if (state && markerStateOptions) {
  10586. radius = markerStateOptions.radius;
  10587. newSymbol = pointMarker.symbol || series.symbol;
  10588. // If the point has another symbol than the previous one, throw away the
  10589. // state marker graphic and force a new one (#1459)
  10590. if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) {
  10591. stateMarkerGraphic = stateMarkerGraphic.destroy();
  10592. }
  10593. // Add a new state marker graphic
  10594. if (!stateMarkerGraphic) {
  10595. series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol(
  10596. newSymbol,
  10597. plotX - radius,
  10598. plotY - radius,
  10599. 2 * radius,
  10600. 2 * radius
  10601. )
  10602. .attr(pointAttr[state])
  10603. .add(series.markerGroup);
  10604. stateMarkerGraphic.currentSymbol = newSymbol;
  10605. // Move the existing graphic
  10606. } else {
  10607. stateMarkerGraphic.attr({ // #1054
  10608. x: plotX - radius,
  10609. y: plotY - radius
  10610. });
  10611. }
  10612. }
  10613. if (stateMarkerGraphic) {
  10614. stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY) ? 'show' : 'hide']();
  10615. }
  10616. }
  10617. point.state = state;
  10618. }
  10619. };
  10620. /**
  10621. * @classDescription The base function which all other series types inherit from. The data in the series is stored
  10622. * in various arrays.
  10623. *
  10624. * - First, series.options.data contains all the original config options for
  10625. * each point whether added by options or methods like series.addPoint.
  10626. * - Next, series.data contains those values converted to points, but in case the series data length
  10627. * exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It
  10628. * only contains the points that have been created on demand.
  10629. * - Then there's series.points that contains all currently visible point objects. In case of cropping,
  10630. * the cropped-away points are not part of this array. The series.points array starts at series.cropStart
  10631. * compared to series.data and series.options.data. If however the series data is grouped, these can't
  10632. * be correlated one to one.
  10633. * - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points.
  10634. * - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points.
  10635. *
  10636. * @param {Object} chart
  10637. * @param {Object} options
  10638. */
  10639. var Series = function () {};
  10640. Series.prototype = {
  10641. isCartesian: true,
  10642. type: 'line',
  10643. pointClass: Point,
  10644. sorted: true, // requires the data to be sorted
  10645. requireSorting: true,
  10646. pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
  10647. stroke: 'lineColor',
  10648. 'stroke-width': 'lineWidth',
  10649. fill: 'fillColor',
  10650. r: 'radius'
  10651. },
  10652. colorCounter: 0,
  10653. init: function (chart, options) {
  10654. var series = this,
  10655. eventType,
  10656. events,
  10657. linkedTo,
  10658. chartSeries = chart.series;
  10659. series.chart = chart;
  10660. series.options = options = series.setOptions(options); // merge with plotOptions
  10661. // bind the axes
  10662. series.bindAxes();
  10663. // set some variables
  10664. extend(series, {
  10665. name: options.name,
  10666. state: NORMAL_STATE,
  10667. pointAttr: {},
  10668. visible: options.visible !== false, // true by default
  10669. selected: options.selected === true // false by default
  10670. });
  10671. // special
  10672. if (useCanVG) {
  10673. options.animation = false;
  10674. }
  10675. // register event listeners
  10676. events = options.events;
  10677. for (eventType in events) {
  10678. addEvent(series, eventType, events[eventType]);
  10679. }
  10680. if (
  10681. (events && events.click) ||
  10682. (options.point && options.point.events && options.point.events.click) ||
  10683. options.allowPointSelect
  10684. ) {
  10685. chart.runTrackerClick = true;
  10686. }
  10687. series.getColor();
  10688. series.getSymbol();
  10689. // set the data
  10690. series.setData(options.data, false);
  10691. // Mark cartesian
  10692. if (series.isCartesian) {
  10693. chart.hasCartesianSeries = true;
  10694. }
  10695. // Register it in the chart
  10696. chartSeries.push(series);
  10697. series._i = chartSeries.length - 1;
  10698. // Sort series according to index option (#248, #1123)
  10699. stableSort(chartSeries, function (a, b) {
  10700. return pick(a.options.index, a._i) - pick(b.options.index, a._i);
  10701. });
  10702. each(chartSeries, function (series, i) {
  10703. series.index = i;
  10704. series.name = series.name || 'Series ' + (i + 1);
  10705. });
  10706. // Linked series
  10707. linkedTo = options.linkedTo;
  10708. series.linkedSeries = [];
  10709. if (isString(linkedTo)) {
  10710. if (linkedTo === ':previous') {
  10711. linkedTo = chartSeries[series.index - 1];
  10712. } else {
  10713. linkedTo = chart.get(linkedTo);
  10714. }
  10715. if (linkedTo) {
  10716. linkedTo.linkedSeries.push(series);
  10717. series.linkedParent = linkedTo;
  10718. }
  10719. }
  10720. },
  10721. /**
  10722. * Set the xAxis and yAxis properties of cartesian series, and register the series
  10723. * in the axis.series array
  10724. */
  10725. bindAxes: function () {
  10726. var series = this,
  10727. seriesOptions = series.options,
  10728. chart = series.chart,
  10729. axisOptions;
  10730. if (series.isCartesian) {
  10731. each(['xAxis', 'yAxis'], function (AXIS) { // repeat for xAxis and yAxis
  10732. each(chart[AXIS], function (axis) { // loop through the chart's axis objects
  10733. axisOptions = axis.options;
  10734. // apply if the series xAxis or yAxis option mathches the number of the
  10735. // axis, or if undefined, use the first axis
  10736. if ((seriesOptions[AXIS] === axisOptions.index) ||
  10737. (seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) ||
  10738. (seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) {
  10739. // register this series in the axis.series lookup
  10740. axis.series.push(series);
  10741. // set this series.xAxis or series.yAxis reference
  10742. series[AXIS] = axis;
  10743. // mark dirty for redraw
  10744. axis.isDirty = true;
  10745. }
  10746. });
  10747. // The series needs an X and an Y axis
  10748. if (!series[AXIS]) {
  10749. error(17, true);
  10750. }
  10751. });
  10752. }
  10753. },
  10754. /**
  10755. * Return an auto incremented x value based on the pointStart and pointInterval options.
  10756. * This is only used if an x value is not given for the point that calls autoIncrement.
  10757. */
  10758. autoIncrement: function () {
  10759. var series = this,
  10760. options = series.options,
  10761. xIncrement = series.xIncrement;
  10762. xIncrement = pick(xIncrement, options.pointStart, 0);
  10763. series.pointInterval = pick(series.pointInterval, options.pointInterval, 1);
  10764. series.xIncrement = xIncrement + series.pointInterval;
  10765. return xIncrement;
  10766. },
  10767. /**
  10768. * Divide the series data into segments divided by null values.
  10769. */
  10770. getSegments: function () {
  10771. var series = this,
  10772. lastNull = -1,
  10773. segments = [],
  10774. i,
  10775. points = series.points,
  10776. pointsLength = points.length;
  10777. if (pointsLength) { // no action required for []
  10778. // if connect nulls, just remove null points
  10779. if (series.options.connectNulls) {
  10780. i = pointsLength;
  10781. while (i--) {
  10782. if (points[i].y === null) {
  10783. points.splice(i, 1);
  10784. }
  10785. }
  10786. if (points.length) {
  10787. segments = [points];
  10788. }
  10789. // else, split on null points
  10790. } else {
  10791. each(points, function (point, i) {
  10792. if (point.y === null) {
  10793. if (i > lastNull + 1) {
  10794. segments.push(points.slice(lastNull + 1, i));
  10795. }
  10796. lastNull = i;
  10797. } else if (i === pointsLength - 1) { // last value
  10798. segments.push(points.slice(lastNull + 1, i + 1));
  10799. }
  10800. });
  10801. }
  10802. }
  10803. // register it
  10804. series.segments = segments;
  10805. },
  10806. /**
  10807. * Set the series options by merging from the options tree
  10808. * @param {Object} itemOptions
  10809. */
  10810. setOptions: function (itemOptions) {
  10811. var chart = this.chart,
  10812. chartOptions = chart.options,
  10813. plotOptions = chartOptions.plotOptions,
  10814. typeOptions = plotOptions[this.type],
  10815. options;
  10816. this.userOptions = itemOptions;
  10817. options = merge(
  10818. typeOptions,
  10819. plotOptions.series,
  10820. itemOptions
  10821. );
  10822. // the tooltip options are merged between global and series specific options
  10823. this.tooltipOptions = merge(chartOptions.tooltip, options.tooltip);
  10824. // Delte marker object if not allowed (#1125)
  10825. if (typeOptions.marker === null) {
  10826. delete options.marker;
  10827. }
  10828. return options;
  10829. },
  10830. /**
  10831. * Get the series' color
  10832. */
  10833. getColor: function () {
  10834. var options = this.options,
  10835. userOptions = this.userOptions,
  10836. defaultColors = this.chart.options.colors,
  10837. counters = this.chart.counters,
  10838. color,
  10839. colorIndex;
  10840. color = options.color || defaultPlotOptions[this.type].color;
  10841. if (!color && !options.colorByPoint) {
  10842. if (defined(userOptions._colorIndex)) { // after Series.update()
  10843. colorIndex = userOptions._colorIndex;
  10844. } else {
  10845. userOptions._colorIndex = counters.color;
  10846. colorIndex = counters.color++;
  10847. }
  10848. color = defaultColors[colorIndex];
  10849. }
  10850. this.color = color;
  10851. counters.wrapColor(defaultColors.length);
  10852. },
  10853. /**
  10854. * Get the series' symbol
  10855. */
  10856. getSymbol: function () {
  10857. var series = this,
  10858. userOptions = series.userOptions,
  10859. seriesMarkerOption = series.options.marker,
  10860. chart = series.chart,
  10861. defaultSymbols = chart.options.symbols,
  10862. counters = chart.counters,
  10863. symbolIndex;
  10864. series.symbol = seriesMarkerOption.symbol;
  10865. if (!series.symbol) {
  10866. if (defined(userOptions._symbolIndex)) { // after Series.update()
  10867. symbolIndex = userOptions._symbolIndex;
  10868. } else {
  10869. userOptions._symbolIndex = counters.symbol;
  10870. symbolIndex = counters.symbol++;
  10871. }
  10872. series.symbol = defaultSymbols[symbolIndex];
  10873. }
  10874. // don't substract radius in image symbols (#604)
  10875. if (/^url/.test(series.symbol)) {
  10876. seriesMarkerOption.radius = 0;
  10877. }
  10878. counters.wrapSymbol(defaultSymbols.length);
  10879. },
  10880. /**
  10881. * Get the series' symbol in the legend. This method should be overridable to create custom
  10882. * symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols.
  10883. *
  10884. * @param {Object} legend The legend object
  10885. */
  10886. drawLegendSymbol: function (legend) {
  10887. var options = this.options,
  10888. markerOptions = options.marker,
  10889. radius,
  10890. legendOptions = legend.options,
  10891. legendSymbol,
  10892. symbolWidth = legendOptions.symbolWidth,
  10893. renderer = this.chart.renderer,
  10894. legendItemGroup = this.legendGroup,
  10895. baseline = legend.baseline,
  10896. attr;
  10897. // Draw the line
  10898. if (options.lineWidth) {
  10899. attr = {
  10900. 'stroke-width': options.lineWidth
  10901. };
  10902. if (options.dashStyle) {
  10903. attr.dashstyle = options.dashStyle;
  10904. }
  10905. this.legendLine = renderer.path([
  10906. M,
  10907. 0,
  10908. baseline - 4,
  10909. L,
  10910. symbolWidth,
  10911. baseline - 4
  10912. ])
  10913. .attr(attr)
  10914. .add(legendItemGroup);
  10915. }
  10916. // Draw the marker
  10917. if (markerOptions && markerOptions.enabled) {
  10918. radius = markerOptions.radius;
  10919. this.legendSymbol = legendSymbol = renderer.symbol(
  10920. this.symbol,
  10921. (symbolWidth / 2) - radius,
  10922. baseline - 4 - radius,
  10923. 2 * radius,
  10924. 2 * radius
  10925. )
  10926. .add(legendItemGroup);
  10927. }
  10928. },
  10929. /**
  10930. * Add a point dynamically after chart load time
  10931. * @param {Object} options Point options as given in series.data
  10932. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  10933. * @param {Boolean} shift If shift is true, a point is shifted off the start
  10934. * of the series as one is appended to the end.
  10935. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  10936. * configuration
  10937. */
  10938. addPoint: function (options, redraw, shift, animation) {
  10939. var series = this,
  10940. seriesOptions = series.options,
  10941. data = series.data,
  10942. graph = series.graph,
  10943. area = series.area,
  10944. chart = series.chart,
  10945. xData = series.xData,
  10946. yData = series.yData,
  10947. zData = series.zData,
  10948. names = series.names,
  10949. currentShift = (graph && graph.shift) || 0,
  10950. dataOptions = seriesOptions.data,
  10951. point;
  10952. setAnimation(animation, chart);
  10953. // Make graph animate sideways
  10954. if (graph && shift) {
  10955. graph.shift = currentShift + 1;
  10956. }
  10957. if (area) {
  10958. if (shift) { // #780
  10959. area.shift = currentShift + 1;
  10960. }
  10961. area.isArea = true; // needed in animation, both with and without shift
  10962. }
  10963. // Optional redraw, defaults to true
  10964. redraw = pick(redraw, true);
  10965. // Get options and push the point to xData, yData and series.options. In series.generatePoints
  10966. // the Point instance will be created on demand and pushed to the series.data array.
  10967. point = { series: series };
  10968. series.pointClass.prototype.applyOptions.apply(point, [options]);
  10969. xData.push(point.x);
  10970. yData.push(series.toYData ? series.toYData(point) : point.y);
  10971. zData.push(point.z);
  10972. if (names) {
  10973. names[point.x] = point.name;
  10974. }
  10975. dataOptions.push(options);
  10976. // Generate points to be added to the legend (#1329)
  10977. if (seriesOptions.legendType === 'point') {
  10978. series.generatePoints();
  10979. }
  10980. // Shift the first point off the parallel arrays
  10981. // todo: consider series.removePoint(i) method
  10982. if (shift) {
  10983. if (data[0] && data[0].remove) {
  10984. data[0].remove(false);
  10985. } else {
  10986. data.shift();
  10987. xData.shift();
  10988. yData.shift();
  10989. zData.shift();
  10990. dataOptions.shift();
  10991. }
  10992. }
  10993. series.getAttribs();
  10994. // redraw
  10995. series.isDirty = true;
  10996. series.isDirtyData = true;
  10997. if (redraw) {
  10998. chart.redraw();
  10999. }
  11000. },
  11001. /**
  11002. * Replace the series data with a new set of data
  11003. * @param {Object} data
  11004. * @param {Object} redraw
  11005. */
  11006. setData: function (data, redraw) {
  11007. var series = this,
  11008. oldData = series.points,
  11009. options = series.options,
  11010. chart = series.chart,
  11011. firstPoint = null,
  11012. xAxis = series.xAxis,
  11013. names = xAxis && xAxis.categories && !xAxis.categories.length ? [] : null,
  11014. i;
  11015. // reset properties
  11016. series.xIncrement = null;
  11017. series.pointRange = xAxis && xAxis.categories ? 1 : options.pointRange;
  11018. series.colorCounter = 0; // for series with colorByPoint (#1547)
  11019. // parallel arrays
  11020. var xData = [],
  11021. yData = [],
  11022. zData = [],
  11023. dataLength = data ? data.length : [],
  11024. turboThreshold = options.turboThreshold || 1000,
  11025. pt,
  11026. pointArrayMap = series.pointArrayMap,
  11027. valueCount = pointArrayMap && pointArrayMap.length,
  11028. hasToYData = !!series.toYData;
  11029. // In turbo mode, only one- or twodimensional arrays of numbers are allowed. The
  11030. // first value is tested, and we assume that all the rest are defined the same
  11031. // way. Although the 'for' loops are similar, they are repeated inside each
  11032. // if-else conditional for max performance.
  11033. if (dataLength > turboThreshold) {
  11034. // find the first non-null point
  11035. i = 0;
  11036. while (firstPoint === null && i < dataLength) {
  11037. firstPoint = data[i];
  11038. i++;
  11039. }
  11040. if (isNumber(firstPoint)) { // assume all points are numbers
  11041. var x = pick(options.pointStart, 0),
  11042. pointInterval = pick(options.pointInterval, 1);
  11043. for (i = 0; i < dataLength; i++) {
  11044. xData[i] = x;
  11045. yData[i] = data[i];
  11046. x += pointInterval;
  11047. }
  11048. series.xIncrement = x;
  11049. } else if (isArray(firstPoint)) { // assume all points are arrays
  11050. if (valueCount) { // [x, low, high] or [x, o, h, l, c]
  11051. for (i = 0; i < dataLength; i++) {
  11052. pt = data[i];
  11053. xData[i] = pt[0];
  11054. yData[i] = pt.slice(1, valueCount + 1);
  11055. }
  11056. } else { // [x, y]
  11057. for (i = 0; i < dataLength; i++) {
  11058. pt = data[i];
  11059. xData[i] = pt[0];
  11060. yData[i] = pt[1];
  11061. }
  11062. }
  11063. } /* else {
  11064. error(12); // Highcharts expects configs to be numbers or arrays in turbo mode
  11065. }*/
  11066. } else {
  11067. for (i = 0; i < dataLength; i++) {
  11068. if (data[i] !== UNDEFINED) { // stray commas in oldIE
  11069. pt = { series: series };
  11070. series.pointClass.prototype.applyOptions.apply(pt, [data[i]]);
  11071. xData[i] = pt.x;
  11072. yData[i] = hasToYData ? series.toYData(pt) : pt.y;
  11073. zData[i] = pt.z;
  11074. if (names && pt.name) {
  11075. names[i] = pt.name;
  11076. }
  11077. }
  11078. }
  11079. }
  11080. // Unsorted data is not supported by the line tooltip as well as data grouping and
  11081. // navigation in Stock charts (#725)
  11082. if (series.requireSorting && xData.length > 1 && xData[1] < xData[0]) {
  11083. error(15);
  11084. }
  11085. // Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON
  11086. if (isString(yData[0])) {
  11087. error(14, true);
  11088. }
  11089. series.data = [];
  11090. series.options.data = data;
  11091. series.xData = xData;
  11092. series.yData = yData;
  11093. series.zData = zData;
  11094. series.names = names;
  11095. // destroy old points
  11096. i = (oldData && oldData.length) || 0;
  11097. while (i--) {
  11098. if (oldData[i] && oldData[i].destroy) {
  11099. oldData[i].destroy();
  11100. }
  11101. }
  11102. // reset minRange (#878)
  11103. if (xAxis) {
  11104. xAxis.minRange = xAxis.userMinRange;
  11105. }
  11106. // redraw
  11107. series.isDirty = series.isDirtyData = chart.isDirtyBox = true;
  11108. if (pick(redraw, true)) {
  11109. chart.redraw(false);
  11110. }
  11111. },
  11112. /**
  11113. * Remove a series and optionally redraw the chart
  11114. *
  11115. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  11116. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  11117. * configuration
  11118. */
  11119. remove: function (redraw, animation) {
  11120. var series = this,
  11121. chart = series.chart;
  11122. redraw = pick(redraw, true);
  11123. if (!series.isRemoving) { /* prevent triggering native event in jQuery
  11124. (calling the remove function from the remove event) */
  11125. series.isRemoving = true;
  11126. // fire the event with a default handler of removing the point
  11127. fireEvent(series, 'remove', null, function () {
  11128. // destroy elements
  11129. series.destroy();
  11130. // redraw
  11131. chart.isDirtyLegend = chart.isDirtyBox = true;
  11132. if (redraw) {
  11133. chart.redraw(animation);
  11134. }
  11135. });
  11136. }
  11137. series.isRemoving = false;
  11138. },
  11139. /**
  11140. * Process the data by cropping away unused data points if the series is longer
  11141. * than the crop threshold. This saves computing time for lage series.
  11142. */
  11143. processData: function (force) {
  11144. var series = this,
  11145. processedXData = series.xData, // copied during slice operation below
  11146. processedYData = series.yData,
  11147. dataLength = processedXData.length,
  11148. cropStart = 0,
  11149. cropEnd = dataLength,
  11150. cropped,
  11151. distance,
  11152. closestPointRange,
  11153. xAxis = series.xAxis,
  11154. i, // loop variable
  11155. options = series.options,
  11156. cropThreshold = options.cropThreshold,
  11157. isCartesian = series.isCartesian;
  11158. // If the series data or axes haven't changed, don't go through this. Return false to pass
  11159. // the message on to override methods like in data grouping.
  11160. if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) {
  11161. return false;
  11162. }
  11163. // optionally filter out points outside the plot area
  11164. if (isCartesian && series.sorted && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) {
  11165. var extremes = xAxis.getExtremes(),
  11166. min = extremes.min,
  11167. max = extremes.max;
  11168. // it's outside current extremes
  11169. if (processedXData[dataLength - 1] < min || processedXData[0] > max) {
  11170. processedXData = [];
  11171. processedYData = [];
  11172. // only crop if it's actually spilling out
  11173. } else if (processedXData[0] < min || processedXData[dataLength - 1] > max) {
  11174. // iterate up to find slice start
  11175. for (i = 0; i < dataLength; i++) {
  11176. if (processedXData[i] >= min) {
  11177. cropStart = mathMax(0, i - 1);
  11178. break;
  11179. }
  11180. }
  11181. // proceed to find slice end
  11182. for (; i < dataLength; i++) {
  11183. if (processedXData[i] > max) {
  11184. cropEnd = i + 1;
  11185. break;
  11186. }
  11187. }
  11188. processedXData = processedXData.slice(cropStart, cropEnd);
  11189. processedYData = processedYData.slice(cropStart, cropEnd);
  11190. cropped = true;
  11191. }
  11192. }
  11193. // Find the closest distance between processed points
  11194. for (i = processedXData.length - 1; i > 0; i--) {
  11195. distance = processedXData[i] - processedXData[i - 1];
  11196. if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) {
  11197. closestPointRange = distance;
  11198. }
  11199. }
  11200. // Record the properties
  11201. series.cropped = cropped; // undefined or true
  11202. series.cropStart = cropStart;
  11203. series.processedXData = processedXData;
  11204. series.processedYData = processedYData;
  11205. if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC
  11206. series.pointRange = closestPointRange || 1;
  11207. }
  11208. series.closestPointRange = closestPointRange;
  11209. },
  11210. /**
  11211. * Generate the data point after the data has been processed by cropping away
  11212. * unused points and optionally grouped in Highcharts Stock.
  11213. */
  11214. generatePoints: function () {
  11215. var series = this,
  11216. options = series.options,
  11217. dataOptions = options.data,
  11218. data = series.data,
  11219. dataLength,
  11220. processedXData = series.processedXData,
  11221. processedYData = series.processedYData,
  11222. pointClass = series.pointClass,
  11223. processedDataLength = processedXData.length,
  11224. cropStart = series.cropStart || 0,
  11225. cursor,
  11226. hasGroupedData = series.hasGroupedData,
  11227. point,
  11228. points = [],
  11229. i;
  11230. if (!data && !hasGroupedData) {
  11231. var arr = [];
  11232. arr.length = dataOptions.length;
  11233. data = series.data = arr;
  11234. }
  11235. for (i = 0; i < processedDataLength; i++) {
  11236. cursor = cropStart + i;
  11237. if (!hasGroupedData) {
  11238. if (data[cursor]) {
  11239. point = data[cursor];
  11240. } else if (dataOptions[cursor] !== UNDEFINED) { // #970
  11241. data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]);
  11242. }
  11243. points[i] = point;
  11244. } else {
  11245. // splat the y data in case of ohlc data array
  11246. points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i])));
  11247. }
  11248. }
  11249. // Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when
  11250. // swithching view from non-grouped data to grouped data (#637)
  11251. if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) {
  11252. for (i = 0; i < dataLength; i++) {
  11253. if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points
  11254. i += processedDataLength;
  11255. }
  11256. if (data[i]) {
  11257. data[i].destroyElements();
  11258. data[i].plotX = UNDEFINED; // #1003
  11259. }
  11260. }
  11261. }
  11262. series.data = data;
  11263. series.points = points;
  11264. },
  11265. /**
  11266. * Translate data points from raw data values to chart specific positioning data
  11267. * needed later in drawPoints, drawGraph and drawTracker.
  11268. */
  11269. translate: function () {
  11270. if (!this.processedXData) { // hidden series
  11271. this.processData();
  11272. }
  11273. this.generatePoints();
  11274. var series = this,
  11275. options = series.options,
  11276. stacking = options.stacking,
  11277. xAxis = series.xAxis,
  11278. categories = xAxis.categories,
  11279. yAxis = series.yAxis,
  11280. points = series.points,
  11281. dataLength = points.length,
  11282. hasModifyValue = !!series.modifyValue,
  11283. isBottomSeries,
  11284. allStackSeries = yAxis.series,
  11285. i = allStackSeries.length,
  11286. placeBetween = options.pointPlacement === 'between',
  11287. threshold = options.threshold;
  11288. //nextSeriesDown;
  11289. // Is it the last visible series?
  11290. while (i--) {
  11291. if (allStackSeries[i].visible) {
  11292. if (allStackSeries[i] === series) { // #809
  11293. isBottomSeries = true;
  11294. }
  11295. break;
  11296. }
  11297. }
  11298. // Translate each point
  11299. for (i = 0; i < dataLength; i++) {
  11300. var point = points[i],
  11301. xValue = point.x,
  11302. yValue = point.y,
  11303. yBottom = point.low,
  11304. stack = yAxis.stacks[(yValue < threshold ? '-' : '') + series.stackKey],
  11305. pointStack,
  11306. pointStackTotal;
  11307. // Discard disallowed y values for log axes
  11308. if (yAxis.isLog && yValue <= 0) {
  11309. point.y = yValue = null;
  11310. }
  11311. // Get the plotX translation
  11312. point.plotX = xAxis.translate(xValue, 0, 0, 0, 1, placeBetween); // Math.round fixes #591
  11313. // Calculate the bottom y value for stacked series
  11314. if (stacking && series.visible && stack && stack[xValue]) {
  11315. pointStack = stack[xValue];
  11316. pointStackTotal = pointStack.total;
  11317. pointStack.cum = yBottom = pointStack.cum - yValue; // start from top
  11318. yValue = yBottom + yValue;
  11319. if (isBottomSeries) {
  11320. yBottom = pick(threshold, yAxis.min);
  11321. }
  11322. if (yAxis.isLog && yBottom <= 0) { // #1200, #1232
  11323. yBottom = null;
  11324. }
  11325. if (stacking === 'percent') {
  11326. yBottom = pointStackTotal ? yBottom * 100 / pointStackTotal : 0;
  11327. yValue = pointStackTotal ? yValue * 100 / pointStackTotal : 0;
  11328. }
  11329. point.percentage = pointStackTotal ? point.y * 100 / pointStackTotal : 0;
  11330. point.total = point.stackTotal = pointStackTotal;
  11331. point.stackY = yValue;
  11332. }
  11333. // Set translated yBottom or remove it
  11334. point.yBottom = defined(yBottom) ?
  11335. yAxis.translate(yBottom, 0, 1, 0, 1) :
  11336. null;
  11337. // general hook, used for Highstock compare mode
  11338. if (hasModifyValue) {
  11339. yValue = series.modifyValue(yValue, point);
  11340. }
  11341. // Set the the plotY value, reset it for redraws
  11342. point.plotY = (typeof yValue === 'number' && yValue !== Infinity) ?
  11343. mathRound(yAxis.translate(yValue, 0, 1, 0, 1) * 10) / 10 : // Math.round fixes #591
  11344. UNDEFINED;
  11345. // Set client related positions for mouse tracking
  11346. point.clientX = placeBetween ? xAxis.translate(xValue, 0, 0, 0, 1) : point.plotX; // #1514
  11347. point.negative = point.y < (threshold || 0);
  11348. // some API data
  11349. point.category = categories && categories[point.x] !== UNDEFINED ?
  11350. categories[point.x] : point.x;
  11351. }
  11352. // now that we have the cropped data, build the segments
  11353. series.getSegments();
  11354. },
  11355. /**
  11356. * Memoize tooltip texts and positions
  11357. */
  11358. setTooltipPoints: function (renew) {
  11359. var series = this,
  11360. points = [],
  11361. pointsLength,
  11362. low,
  11363. high,
  11364. xAxis = series.xAxis,
  11365. axisLength = xAxis ? (xAxis.tooltipLen || xAxis.len) : series.chart.plotSizeX, // tooltipLen and tooltipPosName used in polar
  11366. point,
  11367. i,
  11368. tooltipPoints = []; // a lookup array for each pixel in the x dimension
  11369. // don't waste resources if tracker is disabled
  11370. if (series.options.enableMouseTracking === false) {
  11371. return;
  11372. }
  11373. // renew
  11374. if (renew) {
  11375. series.tooltipPoints = null;
  11376. }
  11377. // concat segments to overcome null values
  11378. each(series.segments || series.points, function (segment) {
  11379. points = points.concat(segment);
  11380. });
  11381. // Reverse the points in case the X axis is reversed
  11382. if (xAxis && xAxis.reversed) {
  11383. points = points.reverse();
  11384. }
  11385. // Assign each pixel position to the nearest point
  11386. pointsLength = points.length;
  11387. for (i = 0; i < pointsLength; i++) {
  11388. point = points[i];
  11389. // Set this range's low to the last range's high plus one
  11390. low = points[i - 1] ? high + 1 : 0;
  11391. // Now find the new high
  11392. high = points[i + 1] ?
  11393. mathMax(0, mathFloor((point.clientX + (points[i + 1] ? points[i + 1].clientX : axisLength)) / 2)) :
  11394. axisLength;
  11395. while (low >= 0 && low <= high) {
  11396. tooltipPoints[low++] = point;
  11397. }
  11398. }
  11399. series.tooltipPoints = tooltipPoints;
  11400. },
  11401. /**
  11402. * Format the header of the tooltip
  11403. */
  11404. tooltipHeaderFormatter: function (point) {
  11405. var series = this,
  11406. tooltipOptions = series.tooltipOptions,
  11407. xDateFormat = tooltipOptions.xDateFormat,
  11408. xAxis = series.xAxis,
  11409. isDateTime = xAxis && xAxis.options.type === 'datetime',
  11410. headerFormat = tooltipOptions.headerFormat,
  11411. n;
  11412. // Guess the best date format based on the closest point distance (#568)
  11413. if (isDateTime && !xDateFormat) {
  11414. for (n in timeUnits) {
  11415. if (timeUnits[n] >= xAxis.closestPointRange) {
  11416. xDateFormat = tooltipOptions.dateTimeLabelFormats[n];
  11417. break;
  11418. }
  11419. }
  11420. }
  11421. // Insert the header date format if any
  11422. if (isDateTime && xDateFormat && isNumber(point.key)) {
  11423. headerFormat = headerFormat.replace('{point.key}', '{point.key:' + xDateFormat + '}');
  11424. }
  11425. return format(headerFormat, {
  11426. point: point,
  11427. series: series
  11428. });
  11429. },
  11430. /**
  11431. * Series mouse over handler
  11432. */
  11433. onMouseOver: function () {
  11434. var series = this,
  11435. chart = series.chart,
  11436. hoverSeries = chart.hoverSeries;
  11437. // set normal state to previous series
  11438. if (hoverSeries && hoverSeries !== series) {
  11439. hoverSeries.onMouseOut();
  11440. }
  11441. // trigger the event, but to save processing time,
  11442. // only if defined
  11443. if (series.options.events.mouseOver) {
  11444. fireEvent(series, 'mouseOver');
  11445. }
  11446. // hover this
  11447. series.setState(HOVER_STATE);
  11448. chart.hoverSeries = series;
  11449. },
  11450. /**
  11451. * Series mouse out handler
  11452. */
  11453. onMouseOut: function () {
  11454. // trigger the event only if listeners exist
  11455. var series = this,
  11456. options = series.options,
  11457. chart = series.chart,
  11458. tooltip = chart.tooltip,
  11459. hoverPoint = chart.hoverPoint;
  11460. // trigger mouse out on the point, which must be in this series
  11461. if (hoverPoint) {
  11462. hoverPoint.onMouseOut();
  11463. }
  11464. // fire the mouse out event
  11465. if (series && options.events.mouseOut) {
  11466. fireEvent(series, 'mouseOut');
  11467. }
  11468. // hide the tooltip
  11469. if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) {
  11470. tooltip.hide();
  11471. }
  11472. // set normal state
  11473. series.setState();
  11474. chart.hoverSeries = null;
  11475. },
  11476. /**
  11477. * Animate in the series
  11478. */
  11479. animate: function (init) {
  11480. var series = this,
  11481. chart = series.chart,
  11482. renderer = chart.renderer,
  11483. clipRect,
  11484. markerClipRect,
  11485. animation = series.options.animation,
  11486. clipBox = chart.clipBox,
  11487. inverted = chart.inverted,
  11488. sharedClipKey;
  11489. // Animation option is set to true
  11490. if (animation && !isObject(animation)) {
  11491. animation = defaultPlotOptions[series.type].animation;
  11492. }
  11493. sharedClipKey = '_sharedClip' + animation.duration + animation.easing;
  11494. // Initialize the animation. Set up the clipping rectangle.
  11495. if (init) {
  11496. // If a clipping rectangle with the same properties is currently present in the chart, use that.
  11497. clipRect = chart[sharedClipKey];
  11498. markerClipRect = chart[sharedClipKey + 'm'];
  11499. if (!clipRect) {
  11500. chart[sharedClipKey] = clipRect = renderer.clipRect(
  11501. extend(clipBox, { width: 0 })
  11502. );
  11503. chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect(
  11504. -99, // include the width of the first marker
  11505. inverted ? -chart.plotLeft : -chart.plotTop,
  11506. 99,
  11507. inverted ? chart.chartWidth : chart.chartHeight
  11508. );
  11509. }
  11510. series.group.clip(clipRect);
  11511. series.markerGroup.clip(markerClipRect);
  11512. series.sharedClipKey = sharedClipKey;
  11513. // Run the animation
  11514. } else {
  11515. clipRect = chart[sharedClipKey];
  11516. if (clipRect) {
  11517. clipRect.animate({
  11518. width: chart.plotSizeX
  11519. }, animation);
  11520. chart[sharedClipKey + 'm'].animate({
  11521. width: chart.plotSizeX + 99
  11522. }, animation);
  11523. }
  11524. // Delete this function to allow it only once
  11525. series.animate = null;
  11526. // Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option
  11527. // which should be available to the user).
  11528. series.animationTimeout = setTimeout(function () {
  11529. series.afterAnimate();
  11530. }, animation.duration);
  11531. }
  11532. },
  11533. /**
  11534. * This runs after animation to land on the final plot clipping
  11535. */
  11536. afterAnimate: function () {
  11537. var chart = this.chart,
  11538. sharedClipKey = this.sharedClipKey,
  11539. group = this.group;
  11540. if (group && this.options.clip !== false) {
  11541. group.clip(chart.clipRect);
  11542. this.markerGroup.clip(); // no clip
  11543. }
  11544. // Remove the shared clipping rectancgle when all series are shown
  11545. setTimeout(function () {
  11546. if (sharedClipKey && chart[sharedClipKey]) {
  11547. chart[sharedClipKey] = chart[sharedClipKey].destroy();
  11548. chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy();
  11549. }
  11550. }, 100);
  11551. },
  11552. /**
  11553. * Draw the markers
  11554. */
  11555. drawPoints: function () {
  11556. var series = this,
  11557. pointAttr,
  11558. points = series.points,
  11559. chart = series.chart,
  11560. plotX,
  11561. plotY,
  11562. i,
  11563. point,
  11564. radius,
  11565. symbol,
  11566. isImage,
  11567. graphic,
  11568. options = series.options,
  11569. seriesMarkerOptions = options.marker,
  11570. pointMarkerOptions,
  11571. enabled,
  11572. isInside,
  11573. markerGroup = series.markerGroup;
  11574. if (seriesMarkerOptions.enabled || series._hasPointMarkers) {
  11575. i = points.length;
  11576. while (i--) {
  11577. point = points[i];
  11578. plotX = point.plotX;
  11579. plotY = point.plotY;
  11580. graphic = point.graphic;
  11581. pointMarkerOptions = point.marker || {};
  11582. enabled = (seriesMarkerOptions.enabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled;
  11583. isInside = chart.isInsidePlot(plotX, plotY, chart.inverted);
  11584. // only draw the point if y is defined
  11585. if (enabled && plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) {
  11586. // shortcuts
  11587. pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE];
  11588. radius = pointAttr.r;
  11589. symbol = pick(pointMarkerOptions.symbol, series.symbol);
  11590. isImage = symbol.indexOf('url') === 0;
  11591. if (graphic) { // update
  11592. graphic
  11593. .attr({ // Since the marker group isn't clipped, each individual marker must be toggled
  11594. visibility: isInside ? (hasSVG ? 'inherit' : VISIBLE) : HIDDEN
  11595. })
  11596. .animate(extend({
  11597. x: plotX - radius,
  11598. y: plotY - radius
  11599. }, graphic.symbolName ? { // don't apply to image symbols #507
  11600. width: 2 * radius,
  11601. height: 2 * radius
  11602. } : {}));
  11603. } else if (isInside && (radius > 0 || isImage)) {
  11604. point.graphic = graphic = chart.renderer.symbol(
  11605. symbol,
  11606. plotX - radius,
  11607. plotY - radius,
  11608. 2 * radius,
  11609. 2 * radius
  11610. )
  11611. .attr(pointAttr)
  11612. .add(markerGroup);
  11613. }
  11614. } else if (graphic) {
  11615. point.graphic = graphic.destroy(); // #1269
  11616. }
  11617. }
  11618. }
  11619. },
  11620. /**
  11621. * Convert state properties from API naming conventions to SVG attributes
  11622. *
  11623. * @param {Object} options API options object
  11624. * @param {Object} base1 SVG attribute object to inherit from
  11625. * @param {Object} base2 Second level SVG attribute object to inherit from
  11626. */
  11627. convertAttribs: function (options, base1, base2, base3) {
  11628. var conversion = this.pointAttrToOptions,
  11629. attr,
  11630. option,
  11631. obj = {};
  11632. options = options || {};
  11633. base1 = base1 || {};
  11634. base2 = base2 || {};
  11635. base3 = base3 || {};
  11636. for (attr in conversion) {
  11637. option = conversion[attr];
  11638. obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]);
  11639. }
  11640. return obj;
  11641. },
  11642. /**
  11643. * Get the state attributes. Each series type has its own set of attributes
  11644. * that are allowed to change on a point's state change. Series wide attributes are stored for
  11645. * all series, and additionally point specific attributes are stored for all
  11646. * points with individual marker options. If such options are not defined for the point,
  11647. * a reference to the series wide attributes is stored in point.pointAttr.
  11648. */
  11649. getAttribs: function () {
  11650. var series = this,
  11651. seriesOptions = series.options,
  11652. normalOptions = defaultPlotOptions[series.type].marker ? seriesOptions.marker : seriesOptions,
  11653. stateOptions = normalOptions.states,
  11654. stateOptionsHover = stateOptions[HOVER_STATE],
  11655. pointStateOptionsHover,
  11656. seriesColor = series.color,
  11657. normalDefaults = {
  11658. stroke: seriesColor,
  11659. fill: seriesColor
  11660. },
  11661. points = series.points || [], // #927
  11662. i,
  11663. point,
  11664. seriesPointAttr = [],
  11665. pointAttr,
  11666. pointAttrToOptions = series.pointAttrToOptions,
  11667. hasPointSpecificOptions,
  11668. negativeColor = seriesOptions.negativeColor,
  11669. key;
  11670. // series type specific modifications
  11671. if (seriesOptions.marker) { // line, spline, area, areaspline, scatter
  11672. // if no hover radius is given, default to normal radius + 2
  11673. stateOptionsHover.radius = stateOptionsHover.radius || normalOptions.radius + 2;
  11674. stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + 1;
  11675. } else { // column, bar, pie
  11676. // if no hover color is given, brighten the normal color
  11677. stateOptionsHover.color = stateOptionsHover.color ||
  11678. Color(stateOptionsHover.color || seriesColor)
  11679. .brighten(stateOptionsHover.brightness).get();
  11680. }
  11681. // general point attributes for the series normal state
  11682. seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults);
  11683. // HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius
  11684. each([HOVER_STATE, SELECT_STATE], function (state) {
  11685. seriesPointAttr[state] =
  11686. series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]);
  11687. });
  11688. // set it
  11689. series.pointAttr = seriesPointAttr;
  11690. // Generate the point-specific attribute collections if specific point
  11691. // options are given. If not, create a referance to the series wide point
  11692. // attributes
  11693. i = points.length;
  11694. while (i--) {
  11695. point = points[i];
  11696. normalOptions = (point.options && point.options.marker) || point.options;
  11697. if (normalOptions && normalOptions.enabled === false) {
  11698. normalOptions.radius = 0;
  11699. }
  11700. if (point.negative && negativeColor) {
  11701. point.color = point.fillColor = negativeColor;
  11702. }
  11703. hasPointSpecificOptions = seriesOptions.colorByPoint || point.color; // #868
  11704. // check if the point has specific visual options
  11705. if (point.options) {
  11706. for (key in pointAttrToOptions) {
  11707. if (defined(normalOptions[pointAttrToOptions[key]])) {
  11708. hasPointSpecificOptions = true;
  11709. }
  11710. }
  11711. }
  11712. // a specific marker config object is defined for the individual point:
  11713. // create it's own attribute collection
  11714. if (hasPointSpecificOptions) {
  11715. normalOptions = normalOptions || {};
  11716. pointAttr = [];
  11717. stateOptions = normalOptions.states || {}; // reassign for individual point
  11718. pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {};
  11719. // Handle colors for column and pies
  11720. if (!seriesOptions.marker) { // column, bar, point
  11721. // if no hover color is given, brighten the normal color
  11722. pointStateOptionsHover.color =
  11723. Color(pointStateOptionsHover.color || point.color)
  11724. .brighten(pointStateOptionsHover.brightness ||
  11725. stateOptionsHover.brightness).get();
  11726. }
  11727. // normal point state inherits series wide normal state
  11728. pointAttr[NORMAL_STATE] = series.convertAttribs(extend({
  11729. color: point.color // #868
  11730. }, normalOptions), seriesPointAttr[NORMAL_STATE]);
  11731. // inherit from point normal and series hover
  11732. pointAttr[HOVER_STATE] = series.convertAttribs(
  11733. stateOptions[HOVER_STATE],
  11734. seriesPointAttr[HOVER_STATE],
  11735. pointAttr[NORMAL_STATE]
  11736. );
  11737. // inherit from point normal and series hover
  11738. pointAttr[SELECT_STATE] = series.convertAttribs(
  11739. stateOptions[SELECT_STATE],
  11740. seriesPointAttr[SELECT_STATE],
  11741. pointAttr[NORMAL_STATE]
  11742. );
  11743. // Force the fill to negativeColor on markers
  11744. if (point.negative && seriesOptions.marker) {
  11745. pointAttr[NORMAL_STATE].fill = pointAttr[HOVER_STATE].fill = pointAttr[SELECT_STATE].fill =
  11746. series.convertAttribs({ fillColor: negativeColor }).fill;
  11747. }
  11748. // no marker config object is created: copy a reference to the series-wide
  11749. // attribute collection
  11750. } else {
  11751. pointAttr = seriesPointAttr;
  11752. }
  11753. point.pointAttr = pointAttr;
  11754. }
  11755. },
  11756. /**
  11757. * Update the series with a new set of options
  11758. */
  11759. update: function (newOptions, redraw) {
  11760. var chart = this.chart,
  11761. // must use user options when changing type because this.options is merged
  11762. // in with type specific plotOptions
  11763. oldOptions = this.userOptions,
  11764. oldType = this.type;
  11765. // Do the merge, with some forced options
  11766. newOptions = merge(oldOptions, {
  11767. animation: false,
  11768. index: this.index,
  11769. pointStart: this.xData[0] // when updating after addPoint
  11770. }, newOptions);
  11771. // Destroy the series and reinsert methods from the type prototype
  11772. this.remove(false);
  11773. extend(this, seriesTypes[newOptions.type || oldType].prototype);
  11774. this.init(chart, newOptions);
  11775. if (pick(redraw, true)) {
  11776. chart.redraw(false);
  11777. }
  11778. },
  11779. /**
  11780. * Clear DOM objects and free up memory
  11781. */
  11782. destroy: function () {
  11783. var series = this,
  11784. chart = series.chart,
  11785. issue134 = /AppleWebKit\/533/.test(userAgent),
  11786. destroy,
  11787. i,
  11788. data = series.data || [],
  11789. point,
  11790. prop,
  11791. axis;
  11792. // add event hook
  11793. fireEvent(series, 'destroy');
  11794. // remove all events
  11795. removeEvent(series);
  11796. // erase from axes
  11797. each(['xAxis', 'yAxis'], function (AXIS) {
  11798. axis = series[AXIS];
  11799. if (axis) {
  11800. erase(axis.series, series);
  11801. axis.isDirty = axis.forceRedraw = true;
  11802. }
  11803. });
  11804. // remove legend items
  11805. if (series.legendItem) {
  11806. series.chart.legend.destroyItem(series);
  11807. }
  11808. // destroy all points with their elements
  11809. i = data.length;
  11810. while (i--) {
  11811. point = data[i];
  11812. if (point && point.destroy) {
  11813. point.destroy();
  11814. }
  11815. }
  11816. series.points = null;
  11817. // Clear the animation timeout if we are destroying the series during initial animation
  11818. clearTimeout(series.animationTimeout);
  11819. // destroy all SVGElements associated to the series
  11820. each(['area', 'graph', 'dataLabelsGroup', 'group', 'markerGroup', 'tracker',
  11821. 'graphNeg', 'areaNeg', 'posClip', 'negClip'], function (prop) {
  11822. if (series[prop]) {
  11823. // issue 134 workaround
  11824. destroy = issue134 && prop === 'group' ?
  11825. 'hide' :
  11826. 'destroy';
  11827. series[prop][destroy]();
  11828. }
  11829. });
  11830. // remove from hoverSeries
  11831. if (chart.hoverSeries === series) {
  11832. chart.hoverSeries = null;
  11833. }
  11834. erase(chart.series, series);
  11835. // clear all members
  11836. for (prop in series) {
  11837. delete series[prop];
  11838. }
  11839. },
  11840. /**
  11841. * Draw the data labels
  11842. */
  11843. drawDataLabels: function () {
  11844. var series = this,
  11845. seriesOptions = series.options,
  11846. options = seriesOptions.dataLabels,
  11847. points = series.points,
  11848. pointOptions,
  11849. generalOptions,
  11850. str,
  11851. dataLabelsGroup;
  11852. if (options.enabled || series._hasPointLabels) {
  11853. // Process default alignment of data labels for columns
  11854. if (series.dlProcessOptions) {
  11855. series.dlProcessOptions(options);
  11856. }
  11857. // Create a separate group for the data labels to avoid rotation
  11858. dataLabelsGroup = series.plotGroup(
  11859. 'dataLabelsGroup',
  11860. 'data-labels',
  11861. series.visible ? VISIBLE : HIDDEN,
  11862. options.zIndex || 6
  11863. );
  11864. // Make the labels for each point
  11865. generalOptions = options;
  11866. each(points, function (point) {
  11867. var enabled,
  11868. dataLabel = point.dataLabel,
  11869. labelConfig,
  11870. attr,
  11871. name,
  11872. rotation,
  11873. connector = point.connector,
  11874. isNew = true;
  11875. // Determine if each data label is enabled
  11876. pointOptions = point.options && point.options.dataLabels;
  11877. enabled = generalOptions.enabled || (pointOptions && pointOptions.enabled);
  11878. // If the point is outside the plot area, destroy it. #678, #820
  11879. if (dataLabel && !enabled) {
  11880. point.dataLabel = dataLabel.destroy();
  11881. // Individual labels are disabled if the are explicitly disabled
  11882. // in the point options, or if they fall outside the plot area.
  11883. } else if (enabled) {
  11884. rotation = options.rotation;
  11885. // Create individual options structure that can be extended without
  11886. // affecting others
  11887. options = merge(generalOptions, pointOptions);
  11888. // Get the string
  11889. labelConfig = point.getLabelConfig();
  11890. str = options.format ?
  11891. format(options.format, labelConfig) :
  11892. options.formatter.call(labelConfig, options);
  11893. // Determine the color
  11894. options.style.color = pick(options.color, options.style.color, series.color, 'black');
  11895. // update existing label
  11896. if (dataLabel) {
  11897. if (defined(str)) {
  11898. dataLabel
  11899. .attr({
  11900. text: str
  11901. });
  11902. isNew = false;
  11903. } else { // #1437 - the label is shown conditionally
  11904. point.dataLabel = dataLabel = dataLabel.destroy();
  11905. if (connector) {
  11906. point.connector = connector.destroy();
  11907. }
  11908. }
  11909. // create new label
  11910. } else if (defined(str)) {
  11911. attr = {
  11912. //align: align,
  11913. fill: options.backgroundColor,
  11914. stroke: options.borderColor,
  11915. 'stroke-width': options.borderWidth,
  11916. r: options.borderRadius || 0,
  11917. rotation: rotation,
  11918. padding: options.padding,
  11919. zIndex: 1
  11920. };
  11921. // Remove unused attributes (#947)
  11922. for (name in attr) {
  11923. if (attr[name] === UNDEFINED) {
  11924. delete attr[name];
  11925. }
  11926. }
  11927. dataLabel = point.dataLabel = series.chart.renderer[rotation ? 'text' : 'label']( // labels don't support rotation
  11928. str,
  11929. 0,
  11930. -999,
  11931. null,
  11932. null,
  11933. null,
  11934. options.useHTML
  11935. )
  11936. .attr(attr)
  11937. .css(options.style)
  11938. .add(dataLabelsGroup)
  11939. .shadow(options.shadow);
  11940. }
  11941. if (dataLabel) {
  11942. // Now the data label is created and placed at 0,0, so we need to align it
  11943. series.alignDataLabel(point, dataLabel, options, null, isNew);
  11944. }
  11945. }
  11946. });
  11947. }
  11948. },
  11949. /**
  11950. * Align each individual data label
  11951. */
  11952. alignDataLabel: function (point, dataLabel, options, alignTo, isNew) {
  11953. var chart = this.chart,
  11954. inverted = chart.inverted,
  11955. plotX = pick(point.plotX, -999),
  11956. plotY = pick(point.plotY, -999),
  11957. bBox = dataLabel.getBBox(),
  11958. alignAttr; // the final position;
  11959. // The alignment box is a singular point
  11960. alignTo = extend({
  11961. x: inverted ? chart.plotWidth - plotY : plotX,
  11962. y: mathRound(inverted ? chart.plotHeight - plotX : plotY),
  11963. width: 0,
  11964. height: 0
  11965. }, alignTo);
  11966. // Add the text size for alignment calculation
  11967. extend(options, {
  11968. width: bBox.width,
  11969. height: bBox.height
  11970. });
  11971. // Allow a hook for changing alignment in the last moment, then do the alignment
  11972. if (options.rotation) { // Fancy box alignment isn't supported for rotated text
  11973. alignAttr = {
  11974. align: options.align,
  11975. x: alignTo.x + options.x + alignTo.width / 2,
  11976. y: alignTo.y + options.y + alignTo.height / 2
  11977. };
  11978. dataLabel[isNew ? 'attr' : 'animate'](alignAttr);
  11979. } else {
  11980. dataLabel.align(options, null, alignTo);
  11981. alignAttr = dataLabel.alignAttr;
  11982. }
  11983. // Show or hide based on the final aligned position
  11984. dataLabel.attr({
  11985. visibility: options.crop === false || /*chart.isInsidePlot(alignAttr.x, alignAttr.y) || */chart.isInsidePlot(plotX, plotY, inverted) ?
  11986. (chart.renderer.isSVG ? 'inherit' : VISIBLE) :
  11987. HIDDEN
  11988. });
  11989. },
  11990. /**
  11991. * Return the graph path of a segment
  11992. */
  11993. getSegmentPath: function (segment) {
  11994. var series = this,
  11995. segmentPath = [],
  11996. step = series.options.step;
  11997. // build the segment line
  11998. each(segment, function (point, i) {
  11999. var plotX = point.plotX,
  12000. plotY = point.plotY,
  12001. lastPoint;
  12002. if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object
  12003. segmentPath.push.apply(segmentPath, series.getPointSpline(segment, point, i));
  12004. } else {
  12005. // moveTo or lineTo
  12006. segmentPath.push(i ? L : M);
  12007. // step line?
  12008. if (step && i) {
  12009. lastPoint = segment[i - 1];
  12010. if (step === 'right') {
  12011. segmentPath.push(
  12012. lastPoint.plotX,
  12013. plotY
  12014. );
  12015. } else if (step === 'center') {
  12016. segmentPath.push(
  12017. (lastPoint.plotX + plotX) / 2,
  12018. lastPoint.plotY,
  12019. (lastPoint.plotX + plotX) / 2,
  12020. plotY
  12021. );
  12022. } else {
  12023. segmentPath.push(
  12024. plotX,
  12025. lastPoint.plotY
  12026. );
  12027. }
  12028. }
  12029. // normal line to next point
  12030. segmentPath.push(
  12031. point.plotX,
  12032. point.plotY
  12033. );
  12034. }
  12035. });
  12036. return segmentPath;
  12037. },
  12038. /**
  12039. * Get the graph path
  12040. */
  12041. getGraphPath: function () {
  12042. var series = this,
  12043. graphPath = [],
  12044. segmentPath,
  12045. singlePoints = []; // used in drawTracker
  12046. // Divide into segments and build graph and area paths
  12047. each(series.segments, function (segment) {
  12048. segmentPath = series.getSegmentPath(segment);
  12049. // add the segment to the graph, or a single point for tracking
  12050. if (segment.length > 1) {
  12051. graphPath = graphPath.concat(segmentPath);
  12052. } else {
  12053. singlePoints.push(segment[0]);
  12054. }
  12055. });
  12056. // Record it for use in drawGraph and drawTracker, and return graphPath
  12057. series.singlePoints = singlePoints;
  12058. series.graphPath = graphPath;
  12059. return graphPath;
  12060. },
  12061. /**
  12062. * Draw the actual graph
  12063. */
  12064. drawGraph: function () {
  12065. var series = this,
  12066. options = this.options,
  12067. props = [['graph', options.lineColor || this.color]],
  12068. lineWidth = options.lineWidth,
  12069. dashStyle = options.dashStyle,
  12070. graphPath = this.getGraphPath(),
  12071. negativeColor = options.negativeColor;
  12072. if (negativeColor) {
  12073. props.push(['graphNeg', negativeColor]);
  12074. }
  12075. // draw the graph
  12076. each(props, function (prop, i) {
  12077. var graphKey = prop[0],
  12078. graph = series[graphKey],
  12079. attribs;
  12080. if (graph) {
  12081. stop(graph); // cancel running animations, #459
  12082. graph.animate({ d: graphPath });
  12083. } else if (lineWidth && graphPath.length) { // #1487
  12084. attribs = {
  12085. stroke: prop[1],
  12086. 'stroke-width': lineWidth,
  12087. zIndex: 1 // #1069
  12088. };
  12089. if (dashStyle) {
  12090. attribs.dashstyle = dashStyle;
  12091. }
  12092. series[graphKey] = series.chart.renderer.path(graphPath)
  12093. .attr(attribs)
  12094. .add(series.group)
  12095. .shadow(!i && options.shadow);
  12096. }
  12097. });
  12098. },
  12099. /**
  12100. * Clip the graphs into the positive and negative coloured graphs
  12101. */
  12102. clipNeg: function () {
  12103. var options = this.options,
  12104. chart = this.chart,
  12105. renderer = chart.renderer,
  12106. negativeColor = options.negativeColor,
  12107. translatedThreshold,
  12108. posAttr,
  12109. negAttr,
  12110. posClip = this.posClip,
  12111. negClip = this.negClip,
  12112. chartWidth = chart.chartWidth,
  12113. chartHeight = chart.chartHeight,
  12114. chartSizeMax = mathMax(chartWidth, chartHeight),
  12115. above,
  12116. below;
  12117. if (negativeColor && this.graph) {
  12118. translatedThreshold = mathCeil(this.yAxis.len - this.yAxis.translate(options.threshold || 0));
  12119. above = {
  12120. x: 0,
  12121. y: 0,
  12122. width: chartSizeMax,
  12123. height: translatedThreshold
  12124. };
  12125. below = {
  12126. x: 0,
  12127. y: translatedThreshold,
  12128. width: chartSizeMax,
  12129. height: chartSizeMax - translatedThreshold
  12130. };
  12131. if (chart.inverted && renderer.isVML) {
  12132. above = {
  12133. x: chart.plotWidth - translatedThreshold - chart.plotLeft,
  12134. y: 0,
  12135. width: chartWidth,
  12136. height: chartHeight
  12137. };
  12138. below = {
  12139. x: translatedThreshold + chart.plotLeft - chartWidth,
  12140. y: 0,
  12141. width: chart.plotLeft + translatedThreshold,
  12142. height: chartWidth
  12143. };
  12144. }
  12145. if (this.yAxis.reversed) {
  12146. posAttr = below;
  12147. negAttr = above;
  12148. } else {
  12149. posAttr = above;
  12150. negAttr = below;
  12151. }
  12152. if (posClip) { // update
  12153. posClip.animate(posAttr);
  12154. negClip.animate(negAttr);
  12155. } else {
  12156. this.posClip = posClip = renderer.clipRect(posAttr);
  12157. this.graph.clip(posClip);
  12158. this.negClip = negClip = renderer.clipRect(negAttr);
  12159. this.graphNeg.clip(negClip);
  12160. if (this.area) {
  12161. this.area.clip(posClip);
  12162. this.areaNeg.clip(negClip);
  12163. }
  12164. }
  12165. }
  12166. },
  12167. /**
  12168. * Initialize and perform group inversion on series.group and series.markerGroup
  12169. */
  12170. invertGroups: function () {
  12171. var series = this,
  12172. chart = series.chart;
  12173. // A fixed size is needed for inversion to work
  12174. function setInvert() {
  12175. var size = {
  12176. width: series.yAxis.len,
  12177. height: series.xAxis.len
  12178. };
  12179. each(['group', 'markerGroup'], function (groupName) {
  12180. if (series[groupName]) {
  12181. series[groupName].attr(size).invert();
  12182. }
  12183. });
  12184. }
  12185. addEvent(chart, 'resize', setInvert); // do it on resize
  12186. addEvent(series, 'destroy', function () {
  12187. removeEvent(chart, 'resize', setInvert);
  12188. });
  12189. // Do it now
  12190. setInvert(); // do it now
  12191. // On subsequent render and redraw, just do setInvert without setting up events again
  12192. series.invertGroups = setInvert;
  12193. },
  12194. /**
  12195. * General abstraction for creating plot groups like series.group, series.dataLabelsGroup and
  12196. * series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size.
  12197. */
  12198. plotGroup: function (prop, name, visibility, zIndex, parent) {
  12199. var group = this[prop],
  12200. isNew = !group,
  12201. chart = this.chart,
  12202. xAxis = this.xAxis,
  12203. yAxis = this.yAxis;
  12204. // Generate it on first call
  12205. if (isNew) {
  12206. this[prop] = group = chart.renderer.g(name)
  12207. .attr({
  12208. visibility: visibility,
  12209. zIndex: zIndex || 0.1 // IE8 needs this
  12210. })
  12211. .add(parent);
  12212. }
  12213. // Place it on first and subsequent (redraw) calls
  12214. group[isNew ? 'attr' : 'animate']({
  12215. translateX: xAxis ? xAxis.left : chart.plotLeft,
  12216. translateY: yAxis ? yAxis.top : chart.plotTop,
  12217. scaleX: 1, // #1623
  12218. scaleY: 1
  12219. });
  12220. return group;
  12221. },
  12222. /**
  12223. * Render the graph and markers
  12224. */
  12225. render: function () {
  12226. var series = this,
  12227. chart = series.chart,
  12228. group,
  12229. options = series.options,
  12230. animation = options.animation,
  12231. doAnimation = animation && !!series.animate &&
  12232. chart.renderer.isSVG, // this animation doesn't work in IE8 quirks when the group div is hidden,
  12233. // and looks bad in other oldIE
  12234. visibility = series.visible ? VISIBLE : HIDDEN,
  12235. zIndex = options.zIndex,
  12236. hasRendered = series.hasRendered,
  12237. chartSeriesGroup = chart.seriesGroup;
  12238. // the group
  12239. group = series.plotGroup(
  12240. 'group',
  12241. 'series',
  12242. visibility,
  12243. zIndex,
  12244. chartSeriesGroup
  12245. );
  12246. series.markerGroup = series.plotGroup(
  12247. 'markerGroup',
  12248. 'markers',
  12249. visibility,
  12250. zIndex,
  12251. chartSeriesGroup
  12252. );
  12253. // initiate the animation
  12254. if (doAnimation) {
  12255. series.animate(true);
  12256. }
  12257. // cache attributes for shapes
  12258. series.getAttribs();
  12259. // SVGRenderer needs to know this before drawing elements (#1089)
  12260. group.inverted = chart.inverted;
  12261. // draw the graph if any
  12262. if (series.drawGraph) {
  12263. series.drawGraph();
  12264. series.clipNeg();
  12265. }
  12266. // draw the data labels (inn pies they go before the points)
  12267. series.drawDataLabels();
  12268. // draw the points
  12269. series.drawPoints();
  12270. // draw the mouse tracking area
  12271. if (series.options.enableMouseTracking !== false) {
  12272. series.drawTracker();
  12273. }
  12274. // Handle inverted series and tracker groups
  12275. if (chart.inverted) {
  12276. series.invertGroups();
  12277. }
  12278. // Initial clipping, must be defined after inverting groups for VML
  12279. if (options.clip !== false && !series.sharedClipKey && !hasRendered) {
  12280. group.clip(chart.clipRect);
  12281. }
  12282. // Run the animation
  12283. if (doAnimation) {
  12284. series.animate();
  12285. } else if (!hasRendered) {
  12286. series.afterAnimate();
  12287. }
  12288. series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
  12289. // (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
  12290. series.hasRendered = true;
  12291. },
  12292. /**
  12293. * Redraw the series after an update in the axes.
  12294. */
  12295. redraw: function () {
  12296. var series = this,
  12297. chart = series.chart,
  12298. wasDirtyData = series.isDirtyData, // cache it here as it is set to false in render, but used after
  12299. group = series.group,
  12300. xAxis = series.xAxis,
  12301. yAxis = series.yAxis;
  12302. // reposition on resize
  12303. if (group) {
  12304. if (chart.inverted) {
  12305. group.attr({
  12306. width: chart.plotWidth,
  12307. height: chart.plotHeight
  12308. });
  12309. }
  12310. group.animate({
  12311. translateX: pick(xAxis && xAxis.left, chart.plotLeft),
  12312. translateY: pick(yAxis && yAxis.top, chart.plotTop)
  12313. });
  12314. }
  12315. series.translate();
  12316. series.setTooltipPoints(true);
  12317. series.render();
  12318. if (wasDirtyData) {
  12319. fireEvent(series, 'updatedData');
  12320. }
  12321. },
  12322. /**
  12323. * Set the state of the graph
  12324. */
  12325. setState: function (state) {
  12326. var series = this,
  12327. options = series.options,
  12328. graph = series.graph,
  12329. graphNeg = series.graphNeg,
  12330. stateOptions = options.states,
  12331. lineWidth = options.lineWidth,
  12332. attribs;
  12333. state = state || NORMAL_STATE;
  12334. if (series.state !== state) {
  12335. series.state = state;
  12336. if (stateOptions[state] && stateOptions[state].enabled === false) {
  12337. return;
  12338. }
  12339. if (state) {
  12340. lineWidth = stateOptions[state].lineWidth || lineWidth + 1;
  12341. }
  12342. if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML
  12343. attribs = {
  12344. 'stroke-width': lineWidth
  12345. };
  12346. // use attr because animate will cause any other animation on the graph to stop
  12347. graph.attr(attribs);
  12348. if (graphNeg) {
  12349. graphNeg.attr(attribs);
  12350. }
  12351. }
  12352. }
  12353. },
  12354. /**
  12355. * Set the visibility of the graph
  12356. *
  12357. * @param vis {Boolean} True to show the series, false to hide. If UNDEFINED,
  12358. * the visibility is toggled.
  12359. */
  12360. setVisible: function (vis, redraw) {
  12361. var series = this,
  12362. chart = series.chart,
  12363. legendItem = series.legendItem,
  12364. showOrHide,
  12365. ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries,
  12366. oldVisibility = series.visible;
  12367. // if called without an argument, toggle visibility
  12368. series.visible = vis = series.userOptions.visible = vis === UNDEFINED ? !oldVisibility : vis;
  12369. showOrHide = vis ? 'show' : 'hide';
  12370. // show or hide elements
  12371. each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) {
  12372. if (series[key]) {
  12373. series[key][showOrHide]();
  12374. }
  12375. });
  12376. // hide tooltip (#1361)
  12377. if (chart.hoverSeries === series) {
  12378. series.onMouseOut();
  12379. }
  12380. if (legendItem) {
  12381. chart.legend.colorizeItem(series, vis);
  12382. }
  12383. // rescale or adapt to resized chart
  12384. series.isDirty = true;
  12385. // in a stack, all other series are affected
  12386. if (series.options.stacking) {
  12387. each(chart.series, function (otherSeries) {
  12388. if (otherSeries.options.stacking && otherSeries.visible) {
  12389. otherSeries.isDirty = true;
  12390. }
  12391. });
  12392. }
  12393. // show or hide linked series
  12394. each(series.linkedSeries, function (otherSeries) {
  12395. otherSeries.setVisible(vis, false);
  12396. });
  12397. if (ignoreHiddenSeries) {
  12398. chart.isDirtyBox = true;
  12399. }
  12400. if (redraw !== false) {
  12401. chart.redraw();
  12402. }
  12403. fireEvent(series, showOrHide);
  12404. },
  12405. /**
  12406. * Show the graph
  12407. */
  12408. show: function () {
  12409. this.setVisible(true);
  12410. },
  12411. /**
  12412. * Hide the graph
  12413. */
  12414. hide: function () {
  12415. this.setVisible(false);
  12416. },
  12417. /**
  12418. * Set the selected state of the graph
  12419. *
  12420. * @param selected {Boolean} True to select the series, false to unselect. If
  12421. * UNDEFINED, the selection state is toggled.
  12422. */
  12423. select: function (selected) {
  12424. var series = this;
  12425. // if called without an argument, toggle
  12426. series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected;
  12427. if (series.checkbox) {
  12428. series.checkbox.checked = selected;
  12429. }
  12430. fireEvent(series, selected ? 'select' : 'unselect');
  12431. },
  12432. /**
  12433. * Draw the tracker object that sits above all data labels and markers to
  12434. * track mouse events on the graph or points. For the line type charts
  12435. * the tracker uses the same graphPath, but with a greater stroke width
  12436. * for better control.
  12437. */
  12438. drawTracker: function () {
  12439. var series = this,
  12440. options = series.options,
  12441. trackByArea = options.trackByArea,
  12442. trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath),
  12443. trackerPathLength = trackerPath.length,
  12444. chart = series.chart,
  12445. pointer = chart.pointer,
  12446. renderer = chart.renderer,
  12447. snap = chart.options.tooltip.snap,
  12448. tracker = series.tracker,
  12449. cursor = options.cursor,
  12450. css = cursor && { cursor: cursor },
  12451. singlePoints = series.singlePoints,
  12452. singlePoint,
  12453. i,
  12454. onMouseOver = function () {
  12455. if (chart.hoverSeries !== series) {
  12456. series.onMouseOver();
  12457. }
  12458. };
  12459. // Extend end points. A better way would be to use round linecaps,
  12460. // but those are not clickable in VML.
  12461. if (trackerPathLength && !trackByArea) {
  12462. i = trackerPathLength + 1;
  12463. while (i--) {
  12464. if (trackerPath[i] === M) { // extend left side
  12465. trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L);
  12466. }
  12467. if ((i && trackerPath[i] === M) || i === trackerPathLength) { // extend right side
  12468. trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]);
  12469. }
  12470. }
  12471. }
  12472. // handle single points
  12473. for (i = 0; i < singlePoints.length; i++) {
  12474. singlePoint = singlePoints[i];
  12475. trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY,
  12476. L, singlePoint.plotX + snap, singlePoint.plotY);
  12477. }
  12478. // draw the tracker
  12479. if (tracker) {
  12480. tracker.attr({ d: trackerPath });
  12481. } else { // create
  12482. series.tracker = tracker = renderer.path(trackerPath)
  12483. .attr({
  12484. 'class': PREFIX + 'tracker',
  12485. 'stroke-linejoin': 'round', // #1225
  12486. visibility: series.visible ? VISIBLE : HIDDEN,
  12487. stroke: TRACKER_FILL,
  12488. fill: trackByArea ? TRACKER_FILL : NONE,
  12489. 'stroke-width' : options.lineWidth + (trackByArea ? 0 : 2 * snap),
  12490. zIndex: 2
  12491. })
  12492. .addClass(PREFIX + 'tracker')
  12493. .on('mouseover', onMouseOver)
  12494. .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); })
  12495. .css(css)
  12496. .add(series.markerGroup);
  12497. if (hasTouch) {
  12498. tracker.on('touchstart', onMouseOver);
  12499. }
  12500. }
  12501. }
  12502. }; // end Series prototype
  12503. /**
  12504. * LineSeries object
  12505. */
  12506. var LineSeries = extendClass(Series);
  12507. seriesTypes.line = LineSeries;
  12508. /**
  12509. * Set the default options for area
  12510. */
  12511. defaultPlotOptions.area = merge(defaultSeriesOptions, {
  12512. threshold: 0
  12513. // trackByArea: false,
  12514. // lineColor: null, // overrides color, but lets fillColor be unaltered
  12515. // fillOpacity: 0.75,
  12516. // fillColor: null
  12517. });
  12518. /**
  12519. * AreaSeries object
  12520. */
  12521. var AreaSeries = extendClass(Series, {
  12522. type: 'area',
  12523. /**
  12524. * For stacks, don't split segments on null values. Instead, draw null values with
  12525. * no marker. Also insert dummy points for any X position that exists in other series
  12526. * in the stack.
  12527. */
  12528. getSegments: function () {
  12529. var segments = [],
  12530. segment = [],
  12531. keys = [],
  12532. xAxis = this.xAxis,
  12533. yAxis = this.yAxis,
  12534. stack = yAxis.stacks[this.stackKey],
  12535. pointMap = {},
  12536. plotX,
  12537. plotY,
  12538. points = this.points,
  12539. i,
  12540. x;
  12541. if (this.options.stacking && !this.cropped) { // cropped causes artefacts in Stock, and perf issue
  12542. // Create a map where we can quickly look up the points by their X value.
  12543. for (i = 0; i < points.length; i++) {
  12544. pointMap[points[i].x] = points[i];
  12545. }
  12546. // Sort the keys (#1651)
  12547. for (x in stack) {
  12548. keys.push(+x);
  12549. }
  12550. keys.sort(function (a, b) {
  12551. return a - b;
  12552. });
  12553. each(keys, function (x) {
  12554. // The point exists, push it to the segment
  12555. if (pointMap[x]) {
  12556. segment.push(pointMap[x]);
  12557. // There is no point for this X value in this series, so we
  12558. // insert a dummy point in order for the areas to be drawn
  12559. // correctly.
  12560. } else {
  12561. plotX = xAxis.translate(x);
  12562. plotY = yAxis.toPixels(stack[x].cum, true);
  12563. segment.push({
  12564. y: null,
  12565. plotX: plotX,
  12566. clientX: plotX,
  12567. plotY: plotY,
  12568. yBottom: plotY,
  12569. onMouseOver: noop
  12570. });
  12571. }
  12572. });
  12573. if (segment.length) {
  12574. segments.push(segment);
  12575. }
  12576. } else {
  12577. Series.prototype.getSegments.call(this);
  12578. segments = this.segments;
  12579. }
  12580. this.segments = segments;
  12581. },
  12582. /**
  12583. * Extend the base Series getSegmentPath method by adding the path for the area.
  12584. * This path is pushed to the series.areaPath property.
  12585. */
  12586. getSegmentPath: function (segment) {
  12587. var segmentPath = Series.prototype.getSegmentPath.call(this, segment), // call base method
  12588. areaSegmentPath = [].concat(segmentPath), // work on a copy for the area path
  12589. i,
  12590. options = this.options,
  12591. segLength = segmentPath.length;
  12592. if (segLength === 3) { // for animation from 1 to two points
  12593. areaSegmentPath.push(L, segmentPath[1], segmentPath[2]);
  12594. }
  12595. if (options.stacking && !this.closedStacks) {
  12596. // Follow stack back. Todo: implement areaspline. A general solution could be to
  12597. // reverse the entire graphPath of the previous series, though may be hard with
  12598. // splines and with series with different extremes
  12599. for (i = segment.length - 1; i >= 0; i--) {
  12600. // step line?
  12601. if (i < segment.length - 1 && options.step) {
  12602. areaSegmentPath.push(segment[i + 1].plotX, segment[i].yBottom);
  12603. }
  12604. areaSegmentPath.push(segment[i].plotX, segment[i].yBottom);
  12605. }
  12606. } else { // follow zero line back
  12607. this.closeSegment(areaSegmentPath, segment);
  12608. }
  12609. this.areaPath = this.areaPath.concat(areaSegmentPath);
  12610. return segmentPath;
  12611. },
  12612. /**
  12613. * Extendable method to close the segment path of an area. This is overridden in polar
  12614. * charts.
  12615. */
  12616. closeSegment: function (path, segment) {
  12617. var translatedThreshold = this.yAxis.getThreshold(this.options.threshold);
  12618. path.push(
  12619. L,
  12620. segment[segment.length - 1].plotX,
  12621. translatedThreshold,
  12622. L,
  12623. segment[0].plotX,
  12624. translatedThreshold
  12625. );
  12626. },
  12627. /**
  12628. * Draw the graph and the underlying area. This method calls the Series base
  12629. * function and adds the area. The areaPath is calculated in the getSegmentPath
  12630. * method called from Series.prototype.drawGraph.
  12631. */
  12632. drawGraph: function () {
  12633. // Define or reset areaPath
  12634. this.areaPath = [];
  12635. // Call the base method
  12636. Series.prototype.drawGraph.apply(this);
  12637. // Define local variables
  12638. var series = this,
  12639. areaPath = this.areaPath,
  12640. options = this.options,
  12641. negativeColor = options.negativeColor,
  12642. props = [['area', this.color, options.fillColor]]; // area name, main color, fill color
  12643. if (negativeColor) {
  12644. props.push(['areaNeg', options.negativeColor, options.negativeFillColor]);
  12645. }
  12646. each(props, function (prop) {
  12647. var areaKey = prop[0],
  12648. area = series[areaKey];
  12649. // Create or update the area
  12650. if (area) { // update
  12651. area.animate({ d: areaPath });
  12652. } else { // create
  12653. series[areaKey] = series.chart.renderer.path(areaPath)
  12654. .attr({
  12655. fill: pick(
  12656. prop[2],
  12657. Color(prop[1]).setOpacity(options.fillOpacity || 0.75).get()
  12658. ),
  12659. zIndex: 0 // #1069
  12660. }).add(series.group);
  12661. }
  12662. });
  12663. },
  12664. /**
  12665. * Get the series' symbol in the legend
  12666. *
  12667. * @param {Object} legend The legend object
  12668. * @param {Object} item The series (this) or point
  12669. */
  12670. drawLegendSymbol: function (legend, item) {
  12671. item.legendSymbol = this.chart.renderer.rect(
  12672. 0,
  12673. legend.baseline - 11,
  12674. legend.options.symbolWidth,
  12675. 12,
  12676. 2
  12677. ).attr({
  12678. zIndex: 3
  12679. }).add(item.legendGroup);
  12680. }
  12681. });
  12682. seriesTypes.area = AreaSeries;/**
  12683. * Set the default options for spline
  12684. */
  12685. defaultPlotOptions.spline = merge(defaultSeriesOptions);
  12686. /**
  12687. * SplineSeries object
  12688. */
  12689. var SplineSeries = extendClass(Series, {
  12690. type: 'spline',
  12691. /**
  12692. * Get the spline segment from a given point's previous neighbour to the given point
  12693. */
  12694. getPointSpline: function (segment, point, i) {
  12695. var smoothing = 1.5, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc
  12696. denom = smoothing + 1,
  12697. plotX = point.plotX,
  12698. plotY = point.plotY,
  12699. lastPoint = segment[i - 1],
  12700. nextPoint = segment[i + 1],
  12701. leftContX,
  12702. leftContY,
  12703. rightContX,
  12704. rightContY,
  12705. ret;
  12706. // find control points
  12707. if (lastPoint && nextPoint) {
  12708. var lastX = lastPoint.plotX,
  12709. lastY = lastPoint.plotY,
  12710. nextX = nextPoint.plotX,
  12711. nextY = nextPoint.plotY,
  12712. correction;
  12713. leftContX = (smoothing * plotX + lastX) / denom;
  12714. leftContY = (smoothing * plotY + lastY) / denom;
  12715. rightContX = (smoothing * plotX + nextX) / denom;
  12716. rightContY = (smoothing * plotY + nextY) / denom;
  12717. // have the two control points make a straight line through main point
  12718. correction = ((rightContY - leftContY) * (rightContX - plotX)) /
  12719. (rightContX - leftContX) + plotY - rightContY;
  12720. leftContY += correction;
  12721. rightContY += correction;
  12722. // to prevent false extremes, check that control points are between
  12723. // neighbouring points' y values
  12724. if (leftContY > lastY && leftContY > plotY) {
  12725. leftContY = mathMax(lastY, plotY);
  12726. rightContY = 2 * plotY - leftContY; // mirror of left control point
  12727. } else if (leftContY < lastY && leftContY < plotY) {
  12728. leftContY = mathMin(lastY, plotY);
  12729. rightContY = 2 * plotY - leftContY;
  12730. }
  12731. if (rightContY > nextY && rightContY > plotY) {
  12732. rightContY = mathMax(nextY, plotY);
  12733. leftContY = 2 * plotY - rightContY;
  12734. } else if (rightContY < nextY && rightContY < plotY) {
  12735. rightContY = mathMin(nextY, plotY);
  12736. leftContY = 2 * plotY - rightContY;
  12737. }
  12738. // record for drawing in next point
  12739. point.rightContX = rightContX;
  12740. point.rightContY = rightContY;
  12741. }
  12742. // Visualize control points for debugging
  12743. /*
  12744. if (leftContX) {
  12745. this.chart.renderer.circle(leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 2)
  12746. .attr({
  12747. stroke: 'red',
  12748. 'stroke-width': 1,
  12749. fill: 'none'
  12750. })
  12751. .add();
  12752. this.chart.renderer.path(['M', leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop,
  12753. 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
  12754. .attr({
  12755. stroke: 'red',
  12756. 'stroke-width': 1
  12757. })
  12758. .add();
  12759. this.chart.renderer.circle(rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 2)
  12760. .attr({
  12761. stroke: 'green',
  12762. 'stroke-width': 1,
  12763. fill: 'none'
  12764. })
  12765. .add();
  12766. this.chart.renderer.path(['M', rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop,
  12767. 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
  12768. .attr({
  12769. stroke: 'green',
  12770. 'stroke-width': 1
  12771. })
  12772. .add();
  12773. }
  12774. */
  12775. // moveTo or lineTo
  12776. if (!i) {
  12777. ret = [M, plotX, plotY];
  12778. } else { // curve from last point to this
  12779. ret = [
  12780. 'C',
  12781. lastPoint.rightContX || lastPoint.plotX,
  12782. lastPoint.rightContY || lastPoint.plotY,
  12783. leftContX || plotX,
  12784. leftContY || plotY,
  12785. plotX,
  12786. plotY
  12787. ];
  12788. lastPoint.rightContX = lastPoint.rightContY = null; // reset for updating series later
  12789. }
  12790. return ret;
  12791. }
  12792. });
  12793. seriesTypes.spline = SplineSeries;
  12794. /**
  12795. * Set the default options for areaspline
  12796. */
  12797. defaultPlotOptions.areaspline = merge(defaultPlotOptions.area);
  12798. /**
  12799. * AreaSplineSeries object
  12800. */
  12801. var areaProto = AreaSeries.prototype,
  12802. AreaSplineSeries = extendClass(SplineSeries, {
  12803. type: 'areaspline',
  12804. closedStacks: true, // instead of following the previous graph back, follow the threshold back
  12805. // Mix in methods from the area series
  12806. getSegmentPath: areaProto.getSegmentPath,
  12807. closeSegment: areaProto.closeSegment,
  12808. drawGraph: areaProto.drawGraph
  12809. });
  12810. seriesTypes.areaspline = AreaSplineSeries;
  12811. /**
  12812. * Set the default options for column
  12813. */
  12814. defaultPlotOptions.column = merge(defaultSeriesOptions, {
  12815. borderColor: '#FFFFFF',
  12816. borderWidth: 1,
  12817. borderRadius: 0,
  12818. //colorByPoint: undefined,
  12819. groupPadding: 0.2,
  12820. //grouping: true,
  12821. marker: null, // point options are specified in the base options
  12822. pointPadding: 0.1,
  12823. //pointWidth: null,
  12824. minPointLength: 0,
  12825. cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes
  12826. pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories
  12827. states: {
  12828. hover: {
  12829. brightness: 0.1,
  12830. shadow: false
  12831. },
  12832. select: {
  12833. color: '#C0C0C0',
  12834. borderColor: '#000000',
  12835. shadow: false
  12836. }
  12837. },
  12838. dataLabels: {
  12839. align: null, // auto
  12840. verticalAlign: null, // auto
  12841. y: null
  12842. },
  12843. stickyTracking: false,
  12844. threshold: 0
  12845. });
  12846. /**
  12847. * ColumnSeries object
  12848. */
  12849. var ColumnSeries = extendClass(Series, {
  12850. type: 'column',
  12851. tooltipOutsidePlot: true,
  12852. requireSorting: false,
  12853. pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
  12854. stroke: 'borderColor',
  12855. 'stroke-width': 'borderWidth',
  12856. fill: 'color',
  12857. r: 'borderRadius'
  12858. },
  12859. trackerGroups: ['group', 'dataLabelsGroup'],
  12860. /**
  12861. * Initialize the series
  12862. */
  12863. init: function () {
  12864. Series.prototype.init.apply(this, arguments);
  12865. var series = this,
  12866. chart = series.chart;
  12867. // if the series is added dynamically, force redraw of other
  12868. // series affected by a new column
  12869. if (chart.hasRendered) {
  12870. each(chart.series, function (otherSeries) {
  12871. if (otherSeries.type === series.type) {
  12872. otherSeries.isDirty = true;
  12873. }
  12874. });
  12875. }
  12876. },
  12877. /**
  12878. * Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding,
  12879. * pointWidth etc.
  12880. */
  12881. getColumnMetrics: function () {
  12882. var series = this,
  12883. chart = series.chart,
  12884. options = series.options,
  12885. xAxis = this.xAxis,
  12886. reversedXAxis = xAxis.reversed,
  12887. stackKey,
  12888. stackGroups = {},
  12889. columnIndex,
  12890. columnCount = 0;
  12891. // Get the total number of column type series.
  12892. // This is called on every series. Consider moving this logic to a
  12893. // chart.orderStacks() function and call it on init, addSeries and removeSeries
  12894. if (options.grouping === false) {
  12895. columnCount = 1;
  12896. } else {
  12897. each(chart.series, function (otherSeries) {
  12898. var otherOptions = otherSeries.options;
  12899. if (otherSeries.type === series.type && otherSeries.visible &&
  12900. series.options.group === otherOptions.group) { // used in Stock charts navigator series
  12901. if (otherOptions.stacking) {
  12902. stackKey = otherSeries.stackKey;
  12903. if (stackGroups[stackKey] === UNDEFINED) {
  12904. stackGroups[stackKey] = columnCount++;
  12905. }
  12906. columnIndex = stackGroups[stackKey];
  12907. } else if (otherOptions.grouping !== false) { // #1162
  12908. columnIndex = columnCount++;
  12909. }
  12910. otherSeries.columnIndex = columnIndex;
  12911. }
  12912. });
  12913. }
  12914. var categoryWidth = mathMin(
  12915. mathAbs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || 1),
  12916. xAxis.len // #1535
  12917. ),
  12918. groupPadding = categoryWidth * options.groupPadding,
  12919. groupWidth = categoryWidth - 2 * groupPadding,
  12920. pointOffsetWidth = groupWidth / columnCount,
  12921. optionPointWidth = options.pointWidth,
  12922. pointPadding = defined(optionPointWidth) ? (pointOffsetWidth - optionPointWidth) / 2 :
  12923. pointOffsetWidth * options.pointPadding,
  12924. pointWidth = pick(optionPointWidth, pointOffsetWidth - 2 * pointPadding), // exact point width, used in polar charts
  12925. colIndex = (reversedXAxis ?
  12926. columnCount - (series.columnIndex || 0) : // #1251
  12927. series.columnIndex) || 0,
  12928. pointXOffset = pointPadding + (groupPadding + colIndex *
  12929. pointOffsetWidth - (categoryWidth / 2)) *
  12930. (reversedXAxis ? -1 : 1);
  12931. // Save it for reading in linked series (Error bars particularly)
  12932. return (series.columnMetrics = {
  12933. width: pointWidth,
  12934. offset: pointXOffset
  12935. });
  12936. },
  12937. /**
  12938. * Translate each point to the plot area coordinate system and find shape positions
  12939. */
  12940. translate: function () {
  12941. var series = this,
  12942. chart = series.chart,
  12943. options = series.options,
  12944. stacking = options.stacking,
  12945. borderWidth = options.borderWidth,
  12946. yAxis = series.yAxis,
  12947. threshold = options.threshold,
  12948. translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold),
  12949. minPointLength = pick(options.minPointLength, 5),
  12950. metrics = series.getColumnMetrics(),
  12951. pointWidth = metrics.width,
  12952. barW = mathCeil(mathMax(pointWidth, 1 + 2 * borderWidth)), // rounded and postprocessed for border width
  12953. pointXOffset = metrics.offset;
  12954. Series.prototype.translate.apply(series);
  12955. // record the new values
  12956. each(series.points, function (point) {
  12957. var plotY = mathMin(mathMax(-999, point.plotY), yAxis.len + 999), // Don't draw too far outside plot area (#1303)
  12958. yBottom = pick(point.yBottom, translatedThreshold),
  12959. barX = point.plotX + pointXOffset,
  12960. barY = mathCeil(mathMin(plotY, yBottom)),
  12961. barH = mathCeil(mathMax(plotY, yBottom) - barY),
  12962. stack = yAxis.stacks[(point.y < 0 ? '-' : '') + series.stackKey],
  12963. shapeArgs;
  12964. // Record the offset'ed position and width of the bar to be able to align the stacking total correctly
  12965. if (stacking && series.visible && stack && stack[point.x]) {
  12966. stack[point.x].setOffset(pointXOffset, barW);
  12967. }
  12968. // handle options.minPointLength
  12969. if (mathAbs(barH) < minPointLength) {
  12970. if (minPointLength) {
  12971. barH = minPointLength;
  12972. barY =
  12973. mathAbs(barY - translatedThreshold) > minPointLength ? // stacked
  12974. yBottom - minPointLength : // keep position
  12975. translatedThreshold - (yAxis.translate(point.y, 0, 1, 0, 1) <= translatedThreshold ? minPointLength : 0); // use exact yAxis.translation (#1485)
  12976. }
  12977. }
  12978. point.barX = barX;
  12979. point.pointWidth = pointWidth;
  12980. // create shape type and shape args that are reused in drawPoints and drawTracker
  12981. point.shapeType = 'rect';
  12982. point.shapeArgs = shapeArgs = chart.renderer.Element.prototype.crisp.call(0, borderWidth, barX, barY, barW, barH);
  12983. if (borderWidth % 2) { // correct for shorting in crisp method, visible in stacked columns with 1px border
  12984. shapeArgs.y -= 1;
  12985. shapeArgs.height += 1;
  12986. }
  12987. });
  12988. },
  12989. getSymbol: noop,
  12990. /**
  12991. * Use a solid rectangle like the area series types
  12992. */
  12993. drawLegendSymbol: AreaSeries.prototype.drawLegendSymbol,
  12994. /**
  12995. * Columns have no graph
  12996. */
  12997. drawGraph: noop,
  12998. /**
  12999. * Draw the columns. For bars, the series.group is rotated, so the same coordinates
  13000. * apply for columns and bars. This method is inherited by scatter series.
  13001. *
  13002. */
  13003. drawPoints: function () {
  13004. var series = this,
  13005. options = series.options,
  13006. renderer = series.chart.renderer,
  13007. shapeArgs;
  13008. // draw the columns
  13009. each(series.points, function (point) {
  13010. var plotY = point.plotY,
  13011. graphic = point.graphic;
  13012. if (plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) {
  13013. shapeArgs = point.shapeArgs;
  13014. if (graphic) { // update
  13015. stop(graphic);
  13016. graphic.animate(merge(shapeArgs));
  13017. } else {
  13018. point.graphic = graphic = renderer[point.shapeType](shapeArgs)
  13019. .attr(point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE])
  13020. .add(series.group)
  13021. .shadow(options.shadow, null, options.stacking && !options.borderRadius);
  13022. }
  13023. } else if (graphic) {
  13024. point.graphic = graphic.destroy(); // #1269
  13025. }
  13026. });
  13027. },
  13028. /**
  13029. * Add tracking event listener to the series group, so the point graphics
  13030. * themselves act as trackers
  13031. */
  13032. drawTracker: function () {
  13033. var series = this,
  13034. pointer = series.chart.pointer,
  13035. cursor = series.options.cursor,
  13036. css = cursor && { cursor: cursor },
  13037. onMouseOver = function (e) {
  13038. var target = e.target,
  13039. point;
  13040. series.onMouseOver();
  13041. while (target && !point) {
  13042. point = target.point;
  13043. target = target.parentNode;
  13044. }
  13045. if (point !== UNDEFINED) { // undefined on graph in scatterchart
  13046. point.onMouseOver(e);
  13047. }
  13048. };
  13049. // Add reference to the point
  13050. each(series.points, function (point) {
  13051. if (point.graphic) {
  13052. point.graphic.element.point = point;
  13053. }
  13054. if (point.dataLabel) {
  13055. point.dataLabel.element.point = point;
  13056. }
  13057. });
  13058. // Add the event listeners, we need to do this only once
  13059. if (!series._hasTracking) {
  13060. each(series.trackerGroups, function (key) {
  13061. if (series[key]) { // we don't always have dataLabelsGroup
  13062. series[key]
  13063. .addClass(PREFIX + 'tracker')
  13064. .on('mouseover', onMouseOver)
  13065. .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); })
  13066. .css(css);
  13067. if (hasTouch) {
  13068. series[key].on('touchstart', onMouseOver);
  13069. }
  13070. }
  13071. });
  13072. } else {
  13073. series._hasTracking = true;
  13074. }
  13075. },
  13076. /**
  13077. * Override the basic data label alignment by adjusting for the position of the column
  13078. */
  13079. alignDataLabel: function (point, dataLabel, options, alignTo, isNew) {
  13080. var chart = this.chart,
  13081. inverted = chart.inverted,
  13082. dlBox = point.dlBox || point.shapeArgs, // data label box for alignment
  13083. below = point.below || (point.plotY > pick(this.translatedThreshold, chart.plotSizeY)),
  13084. inside = pick(options.inside, !!this.options.stacking); // draw it inside the box?
  13085. // Align to the column itself, or the top of it
  13086. if (dlBox) { // Area range uses this method but not alignTo
  13087. alignTo = merge(dlBox);
  13088. if (inverted) {
  13089. alignTo = {
  13090. x: chart.plotWidth - alignTo.y - alignTo.height,
  13091. y: chart.plotHeight - alignTo.x - alignTo.width,
  13092. width: alignTo.height,
  13093. height: alignTo.width
  13094. };
  13095. }
  13096. // Compute the alignment box
  13097. if (!inside) {
  13098. if (inverted) {
  13099. alignTo.x += below ? 0 : alignTo.width;
  13100. alignTo.width = 0;
  13101. } else {
  13102. alignTo.y += below ? alignTo.height : 0;
  13103. alignTo.height = 0;
  13104. }
  13105. }
  13106. }
  13107. // When alignment is undefined (typically columns and bars), display the individual
  13108. // point below or above the point depending on the threshold
  13109. options.align = pick(
  13110. options.align,
  13111. !inverted || inside ? 'center' : below ? 'right' : 'left'
  13112. );
  13113. options.verticalAlign = pick(
  13114. options.verticalAlign,
  13115. inverted || inside ? 'middle' : below ? 'top' : 'bottom'
  13116. );
  13117. // Call the parent method
  13118. Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew);
  13119. },
  13120. /**
  13121. * Animate the column heights one by one from zero
  13122. * @param {Boolean} init Whether to initialize the animation or run it
  13123. */
  13124. animate: function (init) {
  13125. var series = this,
  13126. yAxis = this.yAxis,
  13127. options = series.options,
  13128. inverted = this.chart.inverted,
  13129. attr = {},
  13130. translatedThreshold;
  13131. if (hasSVG) { // VML is too slow anyway
  13132. if (init) {
  13133. attr.scaleY = 0.001;
  13134. translatedThreshold = mathMin(yAxis.pos + yAxis.len, mathMax(yAxis.pos, yAxis.toPixels(options.threshold)));
  13135. if (inverted) {
  13136. attr.translateX = translatedThreshold - yAxis.len;
  13137. } else {
  13138. attr.translateY = translatedThreshold;
  13139. }
  13140. series.group.attr(attr);
  13141. } else { // run the animation
  13142. attr.scaleY = 1;
  13143. attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos;
  13144. series.group.animate(attr, series.options.animation);
  13145. // delete this function to allow it only once
  13146. series.animate = null;
  13147. }
  13148. }
  13149. },
  13150. /**
  13151. * Remove this series from the chart
  13152. */
  13153. remove: function () {
  13154. var series = this,
  13155. chart = series.chart;
  13156. // column and bar series affects other series of the same type
  13157. // as they are either stacked or grouped
  13158. if (chart.hasRendered) {
  13159. each(chart.series, function (otherSeries) {
  13160. if (otherSeries.type === series.type) {
  13161. otherSeries.isDirty = true;
  13162. }
  13163. });
  13164. }
  13165. Series.prototype.remove.apply(series, arguments);
  13166. }
  13167. });
  13168. seriesTypes.column = ColumnSeries;
  13169. /**
  13170. * Set the default options for bar
  13171. */
  13172. defaultPlotOptions.bar = merge(defaultPlotOptions.column);
  13173. /**
  13174. * The Bar series class
  13175. */
  13176. var BarSeries = extendClass(ColumnSeries, {
  13177. type: 'bar',
  13178. inverted: true
  13179. });
  13180. seriesTypes.bar = BarSeries;
  13181. /**
  13182. * Set the default options for scatter
  13183. */
  13184. defaultPlotOptions.scatter = merge(defaultSeriesOptions, {
  13185. lineWidth: 0,
  13186. tooltip: {
  13187. headerFormat: '<span style="font-size: 10px; color:{series.color}">{series.name}</span><br/>',
  13188. pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>',
  13189. followPointer: true
  13190. },
  13191. stickyTracking: false
  13192. });
  13193. /**
  13194. * The scatter series class
  13195. */
  13196. var ScatterSeries = extendClass(Series, {
  13197. type: 'scatter',
  13198. sorted: false,
  13199. requireSorting: false,
  13200. noSharedTooltip: true,
  13201. trackerGroups: ['markerGroup'],
  13202. drawTracker: ColumnSeries.prototype.drawTracker,
  13203. setTooltipPoints: noop
  13204. });
  13205. seriesTypes.scatter = ScatterSeries;
  13206. /**
  13207. * Set the default options for pie
  13208. */
  13209. defaultPlotOptions.pie = merge(defaultSeriesOptions, {
  13210. borderColor: '#FFFFFF',
  13211. borderWidth: 1,
  13212. center: [null, null],
  13213. clip: false,
  13214. colorByPoint: true, // always true for pies
  13215. dataLabels: {
  13216. // align: null,
  13217. // connectorWidth: 1,
  13218. // connectorColor: point.color,
  13219. // connectorPadding: 5,
  13220. distance: 30,
  13221. enabled: true,
  13222. formatter: function () {
  13223. return this.point.name;
  13224. }
  13225. // softConnector: true,
  13226. //y: 0
  13227. },
  13228. ignoreHiddenPoint: true,
  13229. //innerSize: 0,
  13230. legendType: 'point',
  13231. marker: null, // point options are specified in the base options
  13232. size: null,
  13233. showInLegend: false,
  13234. slicedOffset: 10,
  13235. states: {
  13236. hover: {
  13237. brightness: 0.1,
  13238. shadow: false
  13239. }
  13240. },
  13241. stickyTracking: false,
  13242. tooltip: {
  13243. followPointer: true
  13244. }
  13245. });
  13246. /**
  13247. * Extended point object for pies
  13248. */
  13249. var PiePoint = extendClass(Point, {
  13250. /**
  13251. * Initiate the pie slice
  13252. */
  13253. init: function () {
  13254. Point.prototype.init.apply(this, arguments);
  13255. var point = this,
  13256. toggleSlice;
  13257. // Disallow negative values (#1530)
  13258. if (point.y < 0) {
  13259. point.y = null;
  13260. }
  13261. //visible: options.visible !== false,
  13262. extend(point, {
  13263. visible: point.visible !== false,
  13264. name: pick(point.name, 'Slice')
  13265. });
  13266. // add event listener for select
  13267. toggleSlice = function () {
  13268. point.slice();
  13269. };
  13270. addEvent(point, 'select', toggleSlice);
  13271. addEvent(point, 'unselect', toggleSlice);
  13272. return point;
  13273. },
  13274. /**
  13275. * Toggle the visibility of the pie slice
  13276. * @param {Boolean} vis Whether to show the slice or not. If undefined, the
  13277. * visibility is toggled
  13278. */
  13279. setVisible: function (vis) {
  13280. var point = this,
  13281. series = point.series,
  13282. chart = series.chart,
  13283. method;
  13284. // if called without an argument, toggle visibility
  13285. point.visible = point.options.visible = vis = vis === UNDEFINED ? !point.visible : vis;
  13286. series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data
  13287. method = vis ? 'show' : 'hide';
  13288. // Show and hide associated elements
  13289. each(['graphic', 'dataLabel', 'connector', 'shadowGroup'], function (key) {
  13290. if (point[key]) {
  13291. point[key][method]();
  13292. }
  13293. });
  13294. if (point.legendItem) {
  13295. chart.legend.colorizeItem(point, vis);
  13296. }
  13297. // Handle ignore hidden slices
  13298. if (!series.isDirty && series.options.ignoreHiddenPoint) {
  13299. series.isDirty = true;
  13300. chart.redraw();
  13301. }
  13302. },
  13303. /**
  13304. * Set or toggle whether the slice is cut out from the pie
  13305. * @param {Boolean} sliced When undefined, the slice state is toggled
  13306. * @param {Boolean} redraw Whether to redraw the chart. True by default.
  13307. */
  13308. slice: function (sliced, redraw, animation) {
  13309. var point = this,
  13310. series = point.series,
  13311. chart = series.chart,
  13312. translation;
  13313. setAnimation(animation, chart);
  13314. // redraw is true by default
  13315. redraw = pick(redraw, true);
  13316. // if called without an argument, toggle
  13317. point.sliced = point.options.sliced = sliced = defined(sliced) ? sliced : !point.sliced;
  13318. series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data
  13319. translation = sliced ? point.slicedTranslation : {
  13320. translateX: 0,
  13321. translateY: 0
  13322. };
  13323. point.graphic.animate(translation);
  13324. if (point.shadowGroup) {
  13325. point.shadowGroup.animate(translation);
  13326. }
  13327. }
  13328. });
  13329. /**
  13330. * The Pie series class
  13331. */
  13332. var PieSeries = {
  13333. type: 'pie',
  13334. isCartesian: false,
  13335. pointClass: PiePoint,
  13336. requireSorting: false,
  13337. noSharedTooltip: true,
  13338. trackerGroups: ['group', 'dataLabelsGroup'],
  13339. pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
  13340. stroke: 'borderColor',
  13341. 'stroke-width': 'borderWidth',
  13342. fill: 'color'
  13343. },
  13344. /**
  13345. * Pies have one color each point
  13346. */
  13347. getColor: noop,
  13348. /**
  13349. * Animate the pies in
  13350. */
  13351. animate: function (init) {
  13352. var series = this,
  13353. points = series.points,
  13354. startAngleRad = series.startAngleRad;
  13355. if (!init) {
  13356. each(points, function (point) {
  13357. var graphic = point.graphic,
  13358. args = point.shapeArgs;
  13359. if (graphic) {
  13360. // start values
  13361. graphic.attr({
  13362. r: series.center[3] / 2, // animate from inner radius (#779)
  13363. start: startAngleRad,
  13364. end: startAngleRad
  13365. });
  13366. // animate
  13367. graphic.animate({
  13368. r: args.r,
  13369. start: args.start,
  13370. end: args.end
  13371. }, series.options.animation);
  13372. }
  13373. });
  13374. // delete this function to allow it only once
  13375. series.animate = null;
  13376. }
  13377. },
  13378. /**
  13379. * Extend the basic setData method by running processData and generatePoints immediately,
  13380. * in order to access the points from the legend.
  13381. */
  13382. setData: function (data, redraw) {
  13383. Series.prototype.setData.call(this, data, false);
  13384. this.processData();
  13385. this.generatePoints();
  13386. if (pick(redraw, true)) {
  13387. this.chart.redraw();
  13388. }
  13389. },
  13390. /**
  13391. * Get the center of the pie based on the size and center options relative to the
  13392. * plot area. Borrowed by the polar and gauge series types.
  13393. */
  13394. getCenter: function () {
  13395. var options = this.options,
  13396. chart = this.chart,
  13397. slicingRoom = 2 * (options.slicedOffset || 0),
  13398. handleSlicingRoom,
  13399. plotWidth = chart.plotWidth - 2 * slicingRoom,
  13400. plotHeight = chart.plotHeight - 2 * slicingRoom,
  13401. centerOption = options.center,
  13402. positions = [pick(centerOption[0], '50%'), pick(centerOption[1], '50%'), options.size || '100%', options.innerSize || 0],
  13403. smallestSize = mathMin(plotWidth, plotHeight),
  13404. isPercent;
  13405. return map(positions, function (length, i) {
  13406. isPercent = /%$/.test(length);
  13407. handleSlicingRoom = i < 2 || (i === 2 && isPercent);
  13408. return (isPercent ?
  13409. // i == 0: centerX, relative to width
  13410. // i == 1: centerY, relative to height
  13411. // i == 2: size, relative to smallestSize
  13412. // i == 4: innerSize, relative to smallestSize
  13413. [plotWidth, plotHeight, smallestSize, smallestSize][i] *
  13414. pInt(length) / 100 :
  13415. length) + (handleSlicingRoom ? slicingRoom : 0);
  13416. });
  13417. },
  13418. /**
  13419. * Do translation for pie slices
  13420. */
  13421. translate: function (positions) {
  13422. this.generatePoints();
  13423. var total = 0,
  13424. series = this,
  13425. cumulative = 0,
  13426. precision = 1000, // issue #172
  13427. options = series.options,
  13428. slicedOffset = options.slicedOffset,
  13429. connectorOffset = slicedOffset + options.borderWidth,
  13430. start,
  13431. end,
  13432. angle,
  13433. startAngleRad = series.startAngleRad = mathPI / 180 * ((options.startAngle || 0) % 360 - 90),
  13434. points = series.points,
  13435. circ = 2 * mathPI,
  13436. fraction,
  13437. radiusX, // the x component of the radius vector for a given point
  13438. radiusY,
  13439. labelDistance = options.dataLabels.distance,
  13440. ignoreHiddenPoint = options.ignoreHiddenPoint,
  13441. i,
  13442. len = points.length,
  13443. point;
  13444. // Get positions - either an integer or a percentage string must be given.
  13445. // If positions are passed as a parameter, we're in a recursive loop for adjusting
  13446. // space for data labels.
  13447. if (!positions) {
  13448. series.center = positions = series.getCenter();
  13449. }
  13450. // utility for getting the x value from a given y, used for anticollision logic in data labels
  13451. series.getX = function (y, left) {
  13452. angle = math.asin((y - positions[1]) / (positions[2] / 2 + labelDistance));
  13453. return positions[0] +
  13454. (left ? -1 : 1) *
  13455. (mathCos(angle) * (positions[2] / 2 + labelDistance));
  13456. };
  13457. // get the total sum
  13458. for (i = 0; i < len; i++) {
  13459. point = points[i];
  13460. total += (ignoreHiddenPoint && !point.visible) ? 0 : point.y;
  13461. }
  13462. // Calculate the geometry for each point
  13463. for (i = 0; i < len; i++) {
  13464. point = points[i];
  13465. // set start and end angle
  13466. fraction = total ? point.y / total : 0;
  13467. start = mathRound((startAngleRad + (cumulative * circ)) * precision) / precision;
  13468. if (!ignoreHiddenPoint || point.visible) {
  13469. cumulative += fraction;
  13470. }
  13471. end = mathRound((startAngleRad + (cumulative * circ)) * precision) / precision;
  13472. // set the shape
  13473. point.shapeType = 'arc';
  13474. point.shapeArgs = {
  13475. x: positions[0],
  13476. y: positions[1],
  13477. r: positions[2] / 2,
  13478. innerR: positions[3] / 2,
  13479. start: start,
  13480. end: end
  13481. };
  13482. // center for the sliced out slice
  13483. angle = (end + start) / 2;
  13484. if (angle > 0.75 * circ) {
  13485. angle -= 2 * mathPI;
  13486. }
  13487. point.slicedTranslation = {
  13488. translateX: mathRound(mathCos(angle) * slicedOffset),
  13489. translateY: mathRound(mathSin(angle) * slicedOffset)
  13490. };
  13491. // set the anchor point for tooltips
  13492. radiusX = mathCos(angle) * positions[2] / 2;
  13493. radiusY = mathSin(angle) * positions[2] / 2;
  13494. point.tooltipPos = [
  13495. positions[0] + radiusX * 0.7,
  13496. positions[1] + radiusY * 0.7
  13497. ];
  13498. point.half = angle < circ / 4 ? 0 : 1;
  13499. point.angle = angle;
  13500. // set the anchor point for data labels
  13501. connectorOffset = mathMin(connectorOffset, labelDistance / 2); // #1678
  13502. point.labelPos = [
  13503. positions[0] + radiusX + mathCos(angle) * labelDistance, // first break of connector
  13504. positions[1] + radiusY + mathSin(angle) * labelDistance, // a/a
  13505. positions[0] + radiusX + mathCos(angle) * connectorOffset, // second break, right outside pie
  13506. positions[1] + radiusY + mathSin(angle) * connectorOffset, // a/a
  13507. positions[0] + radiusX, // landing point for connector
  13508. positions[1] + radiusY, // a/a
  13509. labelDistance < 0 ? // alignment
  13510. 'center' :
  13511. point.half ? 'right' : 'left', // alignment
  13512. angle // center angle
  13513. ];
  13514. // API properties
  13515. point.percentage = fraction * 100;
  13516. point.total = total;
  13517. }
  13518. this.setTooltipPoints();
  13519. },
  13520. drawGraph: null,
  13521. /**
  13522. * Draw the data points
  13523. */
  13524. drawPoints: function () {
  13525. var series = this,
  13526. chart = series.chart,
  13527. renderer = chart.renderer,
  13528. groupTranslation,
  13529. //center,
  13530. graphic,
  13531. //group,
  13532. shadow = series.options.shadow,
  13533. shadowGroup,
  13534. shapeArgs;
  13535. if (shadow && !series.shadowGroup) {
  13536. series.shadowGroup = renderer.g('shadow')
  13537. .add(series.group);
  13538. }
  13539. // draw the slices
  13540. each(series.points, function (point) {
  13541. graphic = point.graphic;
  13542. shapeArgs = point.shapeArgs;
  13543. shadowGroup = point.shadowGroup;
  13544. // put the shadow behind all points
  13545. if (shadow && !shadowGroup) {
  13546. shadowGroup = point.shadowGroup = renderer.g('shadow')
  13547. .add(series.shadowGroup);
  13548. }
  13549. // if the point is sliced, use special translation, else use plot area traslation
  13550. groupTranslation = point.sliced ? point.slicedTranslation : {
  13551. translateX: 0,
  13552. translateY: 0
  13553. };
  13554. //group.translate(groupTranslation[0], groupTranslation[1]);
  13555. if (shadowGroup) {
  13556. shadowGroup.attr(groupTranslation);
  13557. }
  13558. // draw the slice
  13559. if (graphic) {
  13560. graphic.animate(extend(shapeArgs, groupTranslation));
  13561. } else {
  13562. point.graphic = graphic = renderer.arc(shapeArgs)
  13563. .setRadialReference(series.center)
  13564. .attr(
  13565. point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE]
  13566. )
  13567. .attr({ 'stroke-linejoin': 'round' })
  13568. .attr(groupTranslation)
  13569. .add(series.group)
  13570. .shadow(shadow, shadowGroup);
  13571. }
  13572. // detect point specific visibility
  13573. if (point.visible === false) {
  13574. point.setVisible(false);
  13575. }
  13576. });
  13577. },
  13578. /**
  13579. * Override the base drawDataLabels method by pie specific functionality
  13580. */
  13581. drawDataLabels: function () {
  13582. var series = this,
  13583. data = series.data,
  13584. point,
  13585. chart = series.chart,
  13586. options = series.options.dataLabels,
  13587. connectorPadding = pick(options.connectorPadding, 10),
  13588. connectorWidth = pick(options.connectorWidth, 1),
  13589. plotWidth = chart.plotWidth,
  13590. plotHeight = chart.plotHeight,
  13591. connector,
  13592. connectorPath,
  13593. softConnector = pick(options.softConnector, true),
  13594. distanceOption = options.distance,
  13595. seriesCenter = series.center,
  13596. radius = seriesCenter[2] / 2,
  13597. centerY = seriesCenter[1],
  13598. outside = distanceOption > 0,
  13599. dataLabel,
  13600. dataLabelWidth,
  13601. labelPos,
  13602. labelHeight,
  13603. halves = [// divide the points into right and left halves for anti collision
  13604. [], // right
  13605. [] // left
  13606. ],
  13607. x,
  13608. y,
  13609. visibility,
  13610. rankArr,
  13611. i,
  13612. j,
  13613. overflow = [0, 0, 0, 0], // top, right, bottom, left
  13614. sort = function (a, b) {
  13615. return b.y - a.y;
  13616. },
  13617. sortByAngle = function (points, sign) {
  13618. points.sort(function (a, b) {
  13619. return a.angle !== undefined && (b.angle - a.angle) * sign;
  13620. });
  13621. };
  13622. // get out if not enabled
  13623. if (!options.enabled && !series._hasPointLabels) {
  13624. return;
  13625. }
  13626. // run parent method
  13627. Series.prototype.drawDataLabels.apply(series);
  13628. // arrange points for detection collision
  13629. each(data, function (point) {
  13630. if (point.dataLabel) { // it may have been cancelled in the base method (#407)
  13631. halves[point.half].push(point);
  13632. }
  13633. });
  13634. // assume equal label heights
  13635. i = 0;
  13636. while (!labelHeight && data[i]) { // #1569
  13637. labelHeight = data[i] && data[i].dataLabel && (data[i].dataLabel.getBBox().height || 21); // 21 is for #968
  13638. i++;
  13639. }
  13640. /* Loop over the points in each half, starting from the top and bottom
  13641. * of the pie to detect overlapping labels.
  13642. */
  13643. i = 2;
  13644. while (i--) {
  13645. var slots = [],
  13646. slotsLength,
  13647. usedSlots = [],
  13648. points = halves[i],
  13649. pos,
  13650. length = points.length,
  13651. slotIndex;
  13652. // Sort by angle
  13653. sortByAngle(points, i - 0.5);
  13654. // Only do anti-collision when we are outside the pie and have connectors (#856)
  13655. if (distanceOption > 0) {
  13656. // build the slots
  13657. for (pos = centerY - radius - distanceOption; pos <= centerY + radius + distanceOption; pos += labelHeight) {
  13658. slots.push(pos);
  13659. // visualize the slot
  13660. /*
  13661. var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0),
  13662. slotY = pos + chart.plotTop;
  13663. if (!isNaN(slotX)) {
  13664. chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1)
  13665. .attr({
  13666. 'stroke-width': 1,
  13667. stroke: 'silver'
  13668. })
  13669. .add();
  13670. chart.renderer.text('Slot '+ (slots.length - 1), slotX, slotY + 4)
  13671. .attr({
  13672. fill: 'silver'
  13673. }).add();
  13674. }
  13675. */
  13676. }
  13677. slotsLength = slots.length;
  13678. // if there are more values than available slots, remove lowest values
  13679. if (length > slotsLength) {
  13680. // create an array for sorting and ranking the points within each quarter
  13681. rankArr = [].concat(points);
  13682. rankArr.sort(sort);
  13683. j = length;
  13684. while (j--) {
  13685. rankArr[j].rank = j;
  13686. }
  13687. j = length;
  13688. while (j--) {
  13689. if (points[j].rank >= slotsLength) {
  13690. points.splice(j, 1);
  13691. }
  13692. }
  13693. length = points.length;
  13694. }
  13695. // The label goes to the nearest open slot, but not closer to the edge than
  13696. // the label's index.
  13697. for (j = 0; j < length; j++) {
  13698. point = points[j];
  13699. labelPos = point.labelPos;
  13700. var closest = 9999,
  13701. distance,
  13702. slotI;
  13703. // find the closest slot index
  13704. for (slotI = 0; slotI < slotsLength; slotI++) {
  13705. distance = mathAbs(slots[slotI] - labelPos[1]);
  13706. if (distance < closest) {
  13707. closest = distance;
  13708. slotIndex = slotI;
  13709. }
  13710. }
  13711. // if that slot index is closer to the edges of the slots, move it
  13712. // to the closest appropriate slot
  13713. if (slotIndex < j && slots[j] !== null) { // cluster at the top
  13714. slotIndex = j;
  13715. } else if (slotsLength < length - j + slotIndex && slots[j] !== null) { // cluster at the bottom
  13716. slotIndex = slotsLength - length + j;
  13717. while (slots[slotIndex] === null) { // make sure it is not taken
  13718. slotIndex++;
  13719. }
  13720. } else {
  13721. // Slot is taken, find next free slot below. In the next run, the next slice will find the
  13722. // slot above these, because it is the closest one
  13723. while (slots[slotIndex] === null) { // make sure it is not taken
  13724. slotIndex++;
  13725. }
  13726. }
  13727. usedSlots.push({ i: slotIndex, y: slots[slotIndex] });
  13728. slots[slotIndex] = null; // mark as taken
  13729. }
  13730. // sort them in order to fill in from the top
  13731. usedSlots.sort(sort);
  13732. }
  13733. // now the used slots are sorted, fill them up sequentially
  13734. for (j = 0; j < length; j++) {
  13735. var slot, naturalY;
  13736. point = points[j];
  13737. labelPos = point.labelPos;
  13738. dataLabel = point.dataLabel;
  13739. visibility = point.visible === false ? HIDDEN : VISIBLE;
  13740. naturalY = labelPos[1];
  13741. if (distanceOption > 0) {
  13742. slot = usedSlots.pop();
  13743. slotIndex = slot.i;
  13744. // if the slot next to currrent slot is free, the y value is allowed
  13745. // to fall back to the natural position
  13746. y = slot.y;
  13747. if ((naturalY > y && slots[slotIndex + 1] !== null) ||
  13748. (naturalY < y && slots[slotIndex - 1] !== null)) {
  13749. y = naturalY;
  13750. }
  13751. } else {
  13752. y = naturalY;
  13753. }
  13754. // get the x - use the natural x position for first and last slot, to prevent the top
  13755. // and botton slice connectors from touching each other on either side
  13756. x = options.justify ?
  13757. seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption) :
  13758. series.getX(slotIndex === 0 || slotIndex === slots.length - 1 ? naturalY : y, i);
  13759. // Record the placement and visibility
  13760. dataLabel._attr = {
  13761. visibility: visibility,
  13762. align: labelPos[6]
  13763. };
  13764. dataLabel._pos = {
  13765. x: x + options.x +
  13766. ({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0),
  13767. y: y + options.y - 10 // 10 is for the baseline (label vs text)
  13768. };
  13769. dataLabel.connX = x;
  13770. dataLabel.connY = y;
  13771. // Detect overflowing data labels
  13772. if (this.options.size === null) {
  13773. dataLabelWidth = dataLabel.width;
  13774. // Overflow left
  13775. if (x - dataLabelWidth < connectorPadding) {
  13776. overflow[3] = mathMax(mathRound(dataLabelWidth - x + connectorPadding), overflow[3]);
  13777. // Overflow right
  13778. } else if (x + dataLabelWidth > plotWidth - connectorPadding) {
  13779. overflow[1] = mathMax(mathRound(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]);
  13780. }
  13781. // Overflow top
  13782. if (y - labelHeight / 2 < 0) {
  13783. overflow[0] = mathMax(mathRound(-y + labelHeight / 2), overflow[0]);
  13784. // Overflow left
  13785. } else if (y + labelHeight / 2 > plotHeight) {
  13786. overflow[2] = mathMax(mathRound(y + labelHeight / 2 - plotHeight), overflow[2]);
  13787. }
  13788. }
  13789. } // for each point
  13790. } // for each half
  13791. // Do not apply the final placement and draw the connectors until we have verified
  13792. // that labels are not spilling over.
  13793. if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) {
  13794. // Place the labels in the final position
  13795. this.placeDataLabels();
  13796. // Draw the connectors
  13797. if (outside && connectorWidth) {
  13798. each(this.points, function (point) {
  13799. connector = point.connector;
  13800. labelPos = point.labelPos;
  13801. dataLabel = point.dataLabel;
  13802. if (dataLabel && dataLabel._pos) {
  13803. x = dataLabel.connX;
  13804. y = dataLabel.connY;
  13805. connectorPath = softConnector ? [
  13806. M,
  13807. x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
  13808. 'C',
  13809. x, y, // first break, next to the label
  13810. 2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5],
  13811. labelPos[2], labelPos[3], // second break
  13812. L,
  13813. labelPos[4], labelPos[5] // base
  13814. ] : [
  13815. M,
  13816. x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
  13817. L,
  13818. labelPos[2], labelPos[3], // second break
  13819. L,
  13820. labelPos[4], labelPos[5] // base
  13821. ];
  13822. if (connector) {
  13823. connector.animate({ d: connectorPath });
  13824. connector.attr('visibility', visibility);
  13825. } else {
  13826. point.connector = connector = series.chart.renderer.path(connectorPath).attr({
  13827. 'stroke-width': connectorWidth,
  13828. stroke: options.connectorColor || point.color || '#606060',
  13829. visibility: visibility
  13830. })
  13831. .add(series.group);
  13832. }
  13833. } else if (connector) {
  13834. point.connector = connector.destroy();
  13835. }
  13836. });
  13837. }
  13838. }
  13839. },
  13840. /**
  13841. * Verify whether the data labels are allowed to draw, or we should run more translation and data
  13842. * label positioning to keep them inside the plot area. Returns true when data labels are ready
  13843. * to draw.
  13844. */
  13845. verifyDataLabelOverflow: function (overflow) {
  13846. var center = this.center,
  13847. options = this.options,
  13848. centerOption = options.center,
  13849. minSize = options.minSize || 80,
  13850. newSize = minSize,
  13851. ret;
  13852. // Handle horizontal size and center
  13853. if (centerOption[0] !== null) { // Fixed center
  13854. newSize = mathMax(center[2] - mathMax(overflow[1], overflow[3]), minSize);
  13855. } else { // Auto center
  13856. newSize = mathMax(
  13857. center[2] - overflow[1] - overflow[3], // horizontal overflow
  13858. minSize
  13859. );
  13860. center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center
  13861. }
  13862. // Handle vertical size and center
  13863. if (centerOption[1] !== null) { // Fixed center
  13864. newSize = mathMax(mathMin(newSize, center[2] - mathMax(overflow[0], overflow[2])), minSize);
  13865. } else { // Auto center
  13866. newSize = mathMax(
  13867. mathMin(
  13868. newSize,
  13869. center[2] - overflow[0] - overflow[2] // vertical overflow
  13870. ),
  13871. minSize
  13872. );
  13873. center[1] += (overflow[0] - overflow[2]) / 2; // vertical center
  13874. }
  13875. // If the size must be decreased, we need to run translate and drawDataLabels again
  13876. if (newSize < center[2]) {
  13877. center[2] = newSize;
  13878. this.translate(center);
  13879. each(this.points, function (point) {
  13880. if (point.dataLabel) {
  13881. point.dataLabel._pos = null; // reset
  13882. }
  13883. });
  13884. this.drawDataLabels();
  13885. // Else, return true to indicate that the pie and its labels is within the plot area
  13886. } else {
  13887. ret = true;
  13888. }
  13889. return ret;
  13890. },
  13891. /**
  13892. * Perform the final placement of the data labels after we have verified that they
  13893. * fall within the plot area.
  13894. */
  13895. placeDataLabels: function () {
  13896. each(this.points, function (point) {
  13897. var dataLabel = point.dataLabel,
  13898. _pos;
  13899. if (dataLabel) {
  13900. _pos = dataLabel._pos;
  13901. if (_pos) {
  13902. dataLabel.attr(dataLabel._attr);
  13903. dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos);
  13904. dataLabel.moved = true;
  13905. } else if (dataLabel) {
  13906. dataLabel.attr({ y: -999 });
  13907. }
  13908. }
  13909. });
  13910. },
  13911. alignDataLabel: noop,
  13912. /**
  13913. * Draw point specific tracker objects. Inherit directly from column series.
  13914. */
  13915. drawTracker: ColumnSeries.prototype.drawTracker,
  13916. /**
  13917. * Use a simple symbol from column prototype
  13918. */
  13919. drawLegendSymbol: AreaSeries.prototype.drawLegendSymbol,
  13920. /**
  13921. * Pies don't have point marker symbols
  13922. */
  13923. getSymbol: noop
  13924. };
  13925. PieSeries = extendClass(Series, PieSeries);
  13926. seriesTypes.pie = PieSeries;
  13927. // global variables
  13928. extend(Highcharts, {
  13929. // Constructors
  13930. Axis: Axis,
  13931. Chart: Chart,
  13932. Color: Color,
  13933. Legend: Legend,
  13934. Pointer: Pointer,
  13935. Point: Point,
  13936. Tick: Tick,
  13937. Tooltip: Tooltip,
  13938. Renderer: Renderer,
  13939. Series: Series,
  13940. SVGElement: SVGElement,
  13941. SVGRenderer: SVGRenderer,
  13942. // Various
  13943. arrayMin: arrayMin,
  13944. arrayMax: arrayMax,
  13945. charts: charts,
  13946. dateFormat: dateFormat,
  13947. format: format,
  13948. pathAnim: pathAnim,
  13949. getOptions: getOptions,
  13950. hasBidiBug: hasBidiBug,
  13951. isTouchDevice: isTouchDevice,
  13952. numberFormat: numberFormat,
  13953. seriesTypes: seriesTypes,
  13954. setOptions: setOptions,
  13955. addEvent: addEvent,
  13956. removeEvent: removeEvent,
  13957. createElement: createElement,
  13958. discardElement: discardElement,
  13959. css: css,
  13960. each: each,
  13961. extend: extend,
  13962. map: map,
  13963. merge: merge,
  13964. pick: pick,
  13965. splat: splat,
  13966. extendClass: extendClass,
  13967. pInt: pInt,
  13968. wrap: wrap,
  13969. svg: hasSVG,
  13970. canvas: useCanVG,
  13971. vml: !hasSVG && !useCanVG,
  13972. product: PRODUCT,
  13973. version: VERSION
  13974. });
  13975. }());