highcharts.src.js 488 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555
  1. // ==ClosureCompiler==
  2. // @compilation_level SIMPLE_OPTIMIZATIONS
  3. /**
  4. * @license Highcharts JS v4.1.5 (2015-04-13)
  5. *
  6. * (c) 2009-2014 Torstein Honsi
  7. *
  8. * License: www.highcharts.com/license
  9. */
  10. // JSLint options:
  11. /*global Highcharts, HighchartsAdapter, document, window, navigator, setInterval, clearInterval, clearTimeout, setTimeout, location, jQuery, $, console, each, grep */
  12. /*jslint ass: true, sloppy: true, forin: true, plusplus: true, nomen: true, vars: true, regexp: true, newcap: true, browser: true, continue: true, white: true */
  13. (function () {
  14. // encapsulated variables
  15. var UNDEFINED,
  16. doc = document,
  17. win = window,
  18. math = Math,
  19. mathRound = math.round,
  20. mathFloor = math.floor,
  21. mathCeil = math.ceil,
  22. mathMax = math.max,
  23. mathMin = math.min,
  24. mathAbs = math.abs,
  25. mathCos = math.cos,
  26. mathSin = math.sin,
  27. mathPI = math.PI,
  28. deg2rad = mathPI * 2 / 360,
  29. // some variables
  30. userAgent = navigator.userAgent,
  31. isOpera = win.opera,
  32. isIE = /(msie|trident)/i.test(userAgent) && !isOpera,
  33. docMode8 = doc.documentMode === 8,
  34. isWebKit = /AppleWebKit/.test(userAgent),
  35. isFirefox = /Firefox/.test(userAgent),
  36. isTouchDevice = /(Mobile|Android|Windows Phone)/.test(userAgent),
  37. SVG_NS = 'http://www.w3.org/2000/svg',
  38. hasSVG = !!doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect,
  39. hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4, // issue #38
  40. useCanVG = !hasSVG && !isIE && !!doc.createElement('canvas').getContext,
  41. Renderer,
  42. hasTouch,
  43. symbolSizes = {},
  44. idCounter = 0,
  45. garbageBin,
  46. defaultOptions,
  47. dateFormat, // function
  48. globalAnimation,
  49. pathAnim,
  50. timeUnits,
  51. noop = function () { return UNDEFINED; },
  52. charts = [],
  53. chartCount = 0,
  54. PRODUCT = 'Highcharts',
  55. VERSION = '4.1.5',
  56. // some constants for frequently used strings
  57. DIV = 'div',
  58. ABSOLUTE = 'absolute',
  59. RELATIVE = 'relative',
  60. HIDDEN = 'hidden',
  61. PREFIX = 'highcharts-',
  62. VISIBLE = 'visible',
  63. PX = 'px',
  64. NONE = 'none',
  65. M = 'M',
  66. L = 'L',
  67. numRegex = /^[0-9]+$/,
  68. NORMAL_STATE = '',
  69. HOVER_STATE = 'hover',
  70. SELECT_STATE = 'select',
  71. marginNames = ['plotTop', 'marginRight', 'marginBottom', 'plotLeft'],
  72. // Object for extending Axis
  73. AxisPlotLineOrBandExtension,
  74. // constants for attributes
  75. STROKE_WIDTH = 'stroke-width',
  76. // time methods, changed based on whether or not UTC is used
  77. Date, // Allow using a different Date class
  78. makeTime,
  79. timezoneOffset,
  80. getTimezoneOffset,
  81. getMinutes,
  82. getHours,
  83. getDay,
  84. getDate,
  85. getMonth,
  86. getFullYear,
  87. setMilliseconds,
  88. setSeconds,
  89. setMinutes,
  90. setHours,
  91. setDate,
  92. setMonth,
  93. setFullYear,
  94. // lookup over the types and the associated classes
  95. seriesTypes = {},
  96. Highcharts;
  97. // The Highcharts namespace
  98. Highcharts = win.Highcharts = win.Highcharts ? error(16, true) : {};
  99. Highcharts.seriesTypes = seriesTypes;
  100. /**
  101. * Extend an object with the members of another
  102. * @param {Object} a The object to be extended
  103. * @param {Object} b The object to add to the first one
  104. */
  105. var extend = Highcharts.extend = function (a, b) {
  106. var n;
  107. if (!a) {
  108. a = {};
  109. }
  110. for (n in b) {
  111. a[n] = b[n];
  112. }
  113. return a;
  114. };
  115. /**
  116. * Deep merge two or more objects and return a third object. If the first argument is
  117. * true, the contents of the second object is copied into the first object.
  118. * Previously this function redirected to jQuery.extend(true), but this had two limitations.
  119. * First, it deep merged arrays, which lead to workarounds in Highcharts. Second,
  120. * it copied properties from extended prototypes.
  121. */
  122. function merge() {
  123. var i,
  124. args = arguments,
  125. len,
  126. ret = {},
  127. doCopy = function (copy, original) {
  128. var value, key;
  129. // An object is replacing a primitive
  130. if (typeof copy !== 'object') {
  131. copy = {};
  132. }
  133. for (key in original) {
  134. if (original.hasOwnProperty(key)) {
  135. value = original[key];
  136. // Copy the contents of objects, but not arrays or DOM nodes
  137. if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]' &&
  138. key !== 'renderTo' && typeof value.nodeType !== 'number') {
  139. copy[key] = doCopy(copy[key] || {}, value);
  140. // Primitives and arrays are copied over directly
  141. } else {
  142. copy[key] = original[key];
  143. }
  144. }
  145. }
  146. return copy;
  147. };
  148. // If first argument is true, copy into the existing object. Used in setOptions.
  149. if (args[0] === true) {
  150. ret = args[1];
  151. args = Array.prototype.slice.call(args, 2);
  152. }
  153. // For each argument, extend the return
  154. len = args.length;
  155. for (i = 0; i < len; i++) {
  156. ret = doCopy(ret, args[i]);
  157. }
  158. return ret;
  159. }
  160. /**
  161. * Shortcut for parseInt
  162. * @param {Object} s
  163. * @param {Number} mag Magnitude
  164. */
  165. function pInt(s, mag) {
  166. return parseInt(s, mag || 10);
  167. }
  168. /**
  169. * Check for string
  170. * @param {Object} s
  171. */
  172. function isString(s) {
  173. return typeof s === 'string';
  174. }
  175. /**
  176. * Check for object
  177. * @param {Object} obj
  178. */
  179. function isObject(obj) {
  180. return obj && typeof obj === 'object';
  181. }
  182. /**
  183. * Check for array
  184. * @param {Object} obj
  185. */
  186. function isArray(obj) {
  187. return Object.prototype.toString.call(obj) === '[object Array]';
  188. }
  189. /**
  190. * Check for number
  191. * @param {Object} n
  192. */
  193. function isNumber(n) {
  194. return typeof n === 'number';
  195. }
  196. function log2lin(num) {
  197. return math.log(num) / math.LN10;
  198. }
  199. function lin2log(num) {
  200. return math.pow(10, num);
  201. }
  202. /**
  203. * Remove last occurence of an item from an array
  204. * @param {Array} arr
  205. * @param {Mixed} item
  206. */
  207. function erase(arr, item) {
  208. var i = arr.length;
  209. while (i--) {
  210. if (arr[i] === item) {
  211. arr.splice(i, 1);
  212. break;
  213. }
  214. }
  215. //return arr;
  216. }
  217. /**
  218. * Returns true if the object is not null or undefined. Like MooTools' $.defined.
  219. * @param {Object} obj
  220. */
  221. function defined(obj) {
  222. return obj !== UNDEFINED && obj !== null;
  223. }
  224. /**
  225. * Set or get an attribute or an object of attributes. Can't use jQuery attr because
  226. * it attempts to set expando properties on the SVG element, which is not allowed.
  227. *
  228. * @param {Object} elem The DOM element to receive the attribute(s)
  229. * @param {String|Object} prop The property or an abject of key-value pairs
  230. * @param {String} value The value if a single property is set
  231. */
  232. function attr(elem, prop, value) {
  233. var key,
  234. ret;
  235. // if the prop is a string
  236. if (isString(prop)) {
  237. // set the value
  238. if (defined(value)) {
  239. elem.setAttribute(prop, value);
  240. // get the value
  241. } else if (elem && elem.getAttribute) { // elem not defined when printing pie demo...
  242. ret = elem.getAttribute(prop);
  243. }
  244. // else if prop is defined, it is a hash of key/value pairs
  245. } else if (defined(prop) && isObject(prop)) {
  246. for (key in prop) {
  247. elem.setAttribute(key, prop[key]);
  248. }
  249. }
  250. return ret;
  251. }
  252. /**
  253. * Check if an element is an array, and if not, make it into an array. Like
  254. * MooTools' $.splat.
  255. */
  256. function splat(obj) {
  257. return isArray(obj) ? obj : [obj];
  258. }
  259. /**
  260. * Return the first value that is defined. Like MooTools' $.pick.
  261. */
  262. var pick = Highcharts.pick = function () {
  263. var args = arguments,
  264. i,
  265. arg,
  266. length = args.length;
  267. for (i = 0; i < length; i++) {
  268. arg = args[i];
  269. if (arg !== UNDEFINED && arg !== null) {
  270. return arg;
  271. }
  272. }
  273. };
  274. /**
  275. * Set CSS on a given element
  276. * @param {Object} el
  277. * @param {Object} styles Style object with camel case property names
  278. */
  279. function css(el, styles) {
  280. if (isIE && !hasSVG) { // #2686
  281. if (styles && styles.opacity !== UNDEFINED) {
  282. styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')';
  283. }
  284. }
  285. extend(el.style, styles);
  286. }
  287. /**
  288. * Utility function to create element with attributes and styles
  289. * @param {Object} tag
  290. * @param {Object} attribs
  291. * @param {Object} styles
  292. * @param {Object} parent
  293. * @param {Object} nopad
  294. */
  295. function createElement(tag, attribs, styles, parent, nopad) {
  296. var el = doc.createElement(tag);
  297. if (attribs) {
  298. extend(el, attribs);
  299. }
  300. if (nopad) {
  301. css(el, {padding: 0, border: NONE, margin: 0});
  302. }
  303. if (styles) {
  304. css(el, styles);
  305. }
  306. if (parent) {
  307. parent.appendChild(el);
  308. }
  309. return el;
  310. }
  311. /**
  312. * Extend a prototyped class by new members
  313. * @param {Object} parent
  314. * @param {Object} members
  315. */
  316. function extendClass(parent, members) {
  317. var object = function () { return UNDEFINED; };
  318. object.prototype = new parent();
  319. extend(object.prototype, members);
  320. return object;
  321. }
  322. /**
  323. * Pad a string to a given length by adding 0 to the beginning
  324. * @param {Number} number
  325. * @param {Number} length
  326. */
  327. function pad(number, length) {
  328. // Create an array of the remaining length +1 and join it with 0's
  329. return new Array((length || 2) + 1 - String(number).length).join(0) + number;
  330. }
  331. /**
  332. * Wrap a method with extended functionality, preserving the original function
  333. * @param {Object} obj The context object that the method belongs to
  334. * @param {String} method The name of the method to extend
  335. * @param {Function} func A wrapper function callback. This function is called with the same arguments
  336. * as the original function, except that the original function is unshifted and passed as the first
  337. * argument.
  338. */
  339. var wrap = Highcharts.wrap = function (obj, method, func) {
  340. var proceed = obj[method];
  341. obj[method] = function () {
  342. var args = Array.prototype.slice.call(arguments);
  343. args.unshift(proceed);
  344. return func.apply(this, args);
  345. };
  346. };
  347. function getTZOffset(timestamp) {
  348. return ((getTimezoneOffset && getTimezoneOffset(timestamp)) || timezoneOffset || 0) * 60000;
  349. }
  350. /**
  351. * Based on http://www.php.net/manual/en/function.strftime.php
  352. * @param {String} format
  353. * @param {Number} timestamp
  354. * @param {Boolean} capitalize
  355. */
  356. dateFormat = function (format, timestamp, capitalize) {
  357. if (!defined(timestamp) || isNaN(timestamp)) {
  358. return 'Invalid date';
  359. }
  360. format = pick(format, '%Y-%m-%d %H:%M:%S');
  361. var date = new Date(timestamp - getTZOffset(timestamp)),
  362. key, // used in for constuct below
  363. // get the basic time values
  364. hours = date[getHours](),
  365. day = date[getDay](),
  366. dayOfMonth = date[getDate](),
  367. month = date[getMonth](),
  368. fullYear = date[getFullYear](),
  369. lang = defaultOptions.lang,
  370. langWeekdays = lang.weekdays,
  371. // List all format keys. Custom formats can be added from the outside.
  372. replacements = extend({
  373. // Day
  374. 'a': langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon'
  375. 'A': langWeekdays[day], // Long weekday, like 'Monday'
  376. 'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31
  377. 'e': dayOfMonth, // Day of the month, 1 through 31
  378. 'w': day,
  379. // Week (none implemented)
  380. //'W': weekNumber(),
  381. // Month
  382. 'b': lang.shortMonths[month], // Short month, like 'Jan'
  383. 'B': lang.months[month], // Long month, like 'January'
  384. 'm': pad(month + 1), // Two digit month number, 01 through 12
  385. // Year
  386. 'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009
  387. 'Y': fullYear, // Four digits year, like 2009
  388. // Time
  389. 'H': pad(hours), // Two digits hours in 24h format, 00 through 23
  390. 'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11
  391. 'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12
  392. 'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59
  393. 'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM
  394. 'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM
  395. 'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59
  396. 'L': pad(mathRound(timestamp % 1000), 3) // Milliseconds (naming from Ruby)
  397. }, Highcharts.dateFormats);
  398. // do the replaces
  399. for (key in replacements) {
  400. while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster
  401. format = format.replace('%' + key, typeof replacements[key] === 'function' ? replacements[key](timestamp) : replacements[key]);
  402. }
  403. }
  404. // Optionally capitalize the string and return
  405. return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format;
  406. };
  407. /**
  408. * Format a single variable. Similar to sprintf, without the % prefix.
  409. */
  410. function formatSingle(format, val) {
  411. var floatRegex = /f$/,
  412. decRegex = /\.([0-9])/,
  413. lang = defaultOptions.lang,
  414. decimals;
  415. if (floatRegex.test(format)) { // float
  416. decimals = format.match(decRegex);
  417. decimals = decimals ? decimals[1] : -1;
  418. if (val !== null) {
  419. val = Highcharts.numberFormat(
  420. val,
  421. decimals,
  422. lang.decimalPoint,
  423. format.indexOf(',') > -1 ? lang.thousandsSep : ''
  424. );
  425. }
  426. } else {
  427. val = dateFormat(format, val);
  428. }
  429. return val;
  430. }
  431. /**
  432. * Format a string according to a subset of the rules of Python's String.format method.
  433. */
  434. function format(str, ctx) {
  435. var splitter = '{',
  436. isInside = false,
  437. segment,
  438. valueAndFormat,
  439. path,
  440. i,
  441. len,
  442. ret = [],
  443. val,
  444. index;
  445. while ((index = str.indexOf(splitter)) !== -1) {
  446. segment = str.slice(0, index);
  447. if (isInside) { // we're on the closing bracket looking back
  448. valueAndFormat = segment.split(':');
  449. path = valueAndFormat.shift().split('.'); // get first and leave format
  450. len = path.length;
  451. val = ctx;
  452. // Assign deeper paths
  453. for (i = 0; i < len; i++) {
  454. val = val[path[i]];
  455. }
  456. // Format the replacement
  457. if (valueAndFormat.length) {
  458. val = formatSingle(valueAndFormat.join(':'), val);
  459. }
  460. // Push the result and advance the cursor
  461. ret.push(val);
  462. } else {
  463. ret.push(segment);
  464. }
  465. str = str.slice(index + 1); // the rest
  466. isInside = !isInside; // toggle
  467. splitter = isInside ? '}' : '{'; // now look for next matching bracket
  468. }
  469. ret.push(str);
  470. return ret.join('');
  471. }
  472. /**
  473. * Get the magnitude of a number
  474. */
  475. function getMagnitude(num) {
  476. return math.pow(10, mathFloor(math.log(num) / math.LN10));
  477. }
  478. /**
  479. * Take an interval and normalize it to multiples of 1, 2, 2.5 and 5
  480. * @param {Number} interval
  481. * @param {Array} multiples
  482. * @param {Number} magnitude
  483. * @param {Object} options
  484. */
  485. function normalizeTickInterval(interval, multiples, magnitude, allowDecimals, preventExceed) {
  486. var normalized,
  487. i,
  488. retInterval = interval;
  489. // round to a tenfold of 1, 2, 2.5 or 5
  490. magnitude = pick(magnitude, 1);
  491. normalized = interval / magnitude;
  492. // multiples for a linear scale
  493. if (!multiples) {
  494. multiples = [1, 2, 2.5, 5, 10];
  495. // the allowDecimals option
  496. if (allowDecimals === false) {
  497. if (magnitude === 1) {
  498. multiples = [1, 2, 5, 10];
  499. } else if (magnitude <= 0.1) {
  500. multiples = [1 / magnitude];
  501. }
  502. }
  503. }
  504. // normalize the interval to the nearest multiple
  505. for (i = 0; i < multiples.length; i++) {
  506. retInterval = multiples[i];
  507. if ((preventExceed && retInterval * magnitude >= interval) || // only allow tick amounts smaller than natural
  508. (!preventExceed && (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2))) {
  509. break;
  510. }
  511. }
  512. // multiply back to the correct magnitude
  513. retInterval *= magnitude;
  514. return retInterval;
  515. }
  516. /**
  517. * Utility method that sorts an object array and keeping the order of equal items.
  518. * ECMA script standard does not specify the behaviour when items are equal.
  519. */
  520. function stableSort(arr, sortFunction) {
  521. var length = arr.length,
  522. sortValue,
  523. i;
  524. // Add index to each item
  525. for (i = 0; i < length; i++) {
  526. arr[i].ss_i = i; // stable sort index
  527. }
  528. arr.sort(function (a, b) {
  529. sortValue = sortFunction(a, b);
  530. return sortValue === 0 ? a.ss_i - b.ss_i : sortValue;
  531. });
  532. // Remove index from items
  533. for (i = 0; i < length; i++) {
  534. delete arr[i].ss_i; // stable sort index
  535. }
  536. }
  537. /**
  538. * Non-recursive method to find the lowest member of an array. Math.min raises a maximum
  539. * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
  540. * method is slightly slower, but safe.
  541. */
  542. function arrayMin(data) {
  543. var i = data.length,
  544. min = data[0];
  545. while (i--) {
  546. if (data[i] < min) {
  547. min = data[i];
  548. }
  549. }
  550. return min;
  551. }
  552. /**
  553. * Non-recursive method to find the lowest member of an array. Math.min raises a maximum
  554. * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
  555. * method is slightly slower, but safe.
  556. */
  557. function arrayMax(data) {
  558. var i = data.length,
  559. max = data[0];
  560. while (i--) {
  561. if (data[i] > max) {
  562. max = data[i];
  563. }
  564. }
  565. return max;
  566. }
  567. /**
  568. * Utility method that destroys any SVGElement or VMLElement that are properties on the given object.
  569. * It loops all properties and invokes destroy if there is a destroy method. The property is
  570. * then delete'ed.
  571. * @param {Object} The object to destroy properties on
  572. * @param {Object} Exception, do not destroy this property, only delete it.
  573. */
  574. function destroyObjectProperties(obj, except) {
  575. var n;
  576. for (n in obj) {
  577. // If the object is non-null and destroy is defined
  578. if (obj[n] && obj[n] !== except && obj[n].destroy) {
  579. // Invoke the destroy
  580. obj[n].destroy();
  581. }
  582. // Delete the property from the object.
  583. delete obj[n];
  584. }
  585. }
  586. /**
  587. * Discard an element by moving it to the bin and delete
  588. * @param {Object} The HTML node to discard
  589. */
  590. function discardElement(element) {
  591. // create a garbage bin element, not part of the DOM
  592. if (!garbageBin) {
  593. garbageBin = createElement(DIV);
  594. }
  595. // move the node and empty bin
  596. if (element) {
  597. garbageBin.appendChild(element);
  598. }
  599. garbageBin.innerHTML = '';
  600. }
  601. /**
  602. * Provide error messages for debugging, with links to online explanation
  603. */
  604. function error (code, stop) {
  605. var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code;
  606. if (stop) {
  607. throw msg;
  608. }
  609. // else ...
  610. if (win.console) {
  611. console.log(msg);
  612. }
  613. }
  614. /**
  615. * Fix JS round off float errors
  616. * @param {Number} num
  617. */
  618. function correctFloat(num) {
  619. return parseFloat(
  620. num.toPrecision(14)
  621. );
  622. }
  623. /**
  624. * Set the global animation to either a given value, or fall back to the
  625. * given chart's animation option
  626. * @param {Object} animation
  627. * @param {Object} chart
  628. */
  629. function setAnimation(animation, chart) {
  630. globalAnimation = pick(animation, chart.animation);
  631. }
  632. /**
  633. * The time unit lookup
  634. */
  635. timeUnits = {
  636. millisecond: 1,
  637. second: 1000,
  638. minute: 60000,
  639. hour: 3600000,
  640. day: 24 * 3600000,
  641. week: 7 * 24 * 3600000,
  642. month: 28 * 24 * 3600000,
  643. year: 364 * 24 * 3600000
  644. };
  645. /**
  646. * Format a number and return a string based on input settings
  647. * @param {Number} number The input number to format
  648. * @param {Number} decimals The amount of decimals
  649. * @param {String} decPoint The decimal point, defaults to the one given in the lang options
  650. * @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options
  651. */
  652. Highcharts.numberFormat = function (number, decimals, decPoint, thousandsSep) {
  653. var lang = defaultOptions.lang,
  654. // http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/
  655. n = +number || 0,
  656. c = decimals === -1 ?
  657. mathMin((n.toString().split('.')[1] || '').length, 20) : // Preserve decimals. Not huge numbers (#3793).
  658. (isNaN(decimals = mathAbs(decimals)) ? 2 : decimals),
  659. d = decPoint === undefined ? lang.decimalPoint : decPoint,
  660. t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep,
  661. s = n < 0 ? "-" : "",
  662. i = String(pInt(n = mathAbs(n).toFixed(c))),
  663. j = i.length > 3 ? i.length % 3 : 0;
  664. return (s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) +
  665. (c ? d + mathAbs(n - i).toFixed(c).slice(2) : ""));
  666. };
  667. /**
  668. * Path interpolation algorithm used across adapters
  669. */
  670. pathAnim = {
  671. /**
  672. * Prepare start and end values so that the path can be animated one to one
  673. */
  674. init: function (elem, fromD, toD) {
  675. fromD = fromD || '';
  676. var shift = elem.shift,
  677. bezier = fromD.indexOf('C') > -1,
  678. numParams = bezier ? 7 : 3,
  679. endLength,
  680. slice,
  681. i,
  682. start = fromD.split(' '),
  683. end = [].concat(toD), // copy
  684. startBaseLine,
  685. endBaseLine,
  686. sixify = function (arr) { // in splines make move points have six parameters like bezier curves
  687. i = arr.length;
  688. while (i--) {
  689. if (arr[i] === M) {
  690. arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]);
  691. }
  692. }
  693. };
  694. if (bezier) {
  695. sixify(start);
  696. sixify(end);
  697. }
  698. // pull out the base lines before padding
  699. if (elem.isArea) {
  700. startBaseLine = start.splice(start.length - 6, 6);
  701. endBaseLine = end.splice(end.length - 6, 6);
  702. }
  703. // if shifting points, prepend a dummy point to the end path
  704. if (shift <= end.length / numParams && start.length === end.length) {
  705. while (shift--) {
  706. end = [].concat(end).splice(0, numParams).concat(end);
  707. }
  708. }
  709. elem.shift = 0; // reset for following animations
  710. // copy and append last point until the length matches the end length
  711. if (start.length) {
  712. endLength = end.length;
  713. while (start.length < endLength) {
  714. //bezier && sixify(start);
  715. slice = [].concat(start).splice(start.length - numParams, numParams);
  716. if (bezier) { // disable first control point
  717. slice[numParams - 6] = slice[numParams - 2];
  718. slice[numParams - 5] = slice[numParams - 1];
  719. }
  720. start = start.concat(slice);
  721. }
  722. }
  723. if (startBaseLine) { // append the base lines for areas
  724. start = start.concat(startBaseLine);
  725. end = end.concat(endBaseLine);
  726. }
  727. return [start, end];
  728. },
  729. /**
  730. * Interpolate each value of the path and return the array
  731. */
  732. step: function (start, end, pos, complete) {
  733. var ret = [],
  734. i = start.length,
  735. startVal;
  736. if (pos === 1) { // land on the final path without adjustment points appended in the ends
  737. ret = complete;
  738. } else if (i === end.length && pos < 1) {
  739. while (i--) {
  740. startVal = parseFloat(start[i]);
  741. ret[i] =
  742. isNaN(startVal) ? // a letter instruction like M or L
  743. start[i] :
  744. pos * (parseFloat(end[i] - startVal)) + startVal;
  745. }
  746. } else { // if animation is finished or length not matching, land on right value
  747. ret = end;
  748. }
  749. return ret;
  750. }
  751. };
  752. (function ($) {
  753. /**
  754. * The default HighchartsAdapter for jQuery
  755. */
  756. win.HighchartsAdapter = win.HighchartsAdapter || ($ && {
  757. /**
  758. * Initialize the adapter by applying some extensions to jQuery
  759. */
  760. init: function (pathAnim) {
  761. // extend the animate function to allow SVG animations
  762. var Fx = $.fx;
  763. /*jslint unparam: true*//* allow unused param x in this function */
  764. $.extend($.easing, {
  765. easeOutQuad: function (x, t, b, c, d) {
  766. return -c * (t /= d) * (t - 2) + b;
  767. }
  768. });
  769. /*jslint unparam: false*/
  770. // extend some methods to check for elem.attr, which means it is a Highcharts SVG object
  771. $.each(['cur', '_default', 'width', 'height', 'opacity'], function (i, fn) {
  772. var obj = Fx.step,
  773. base;
  774. // Handle different parent objects
  775. if (fn === 'cur') {
  776. obj = Fx.prototype; // 'cur', the getter, relates to Fx.prototype
  777. } else if (fn === '_default' && $.Tween) { // jQuery 1.8 model
  778. obj = $.Tween.propHooks[fn];
  779. fn = 'set';
  780. }
  781. // Overwrite the method
  782. base = obj[fn];
  783. if (base) { // step.width and step.height don't exist in jQuery < 1.7
  784. // create the extended function replacement
  785. obj[fn] = function (fx) {
  786. var elem;
  787. // Fx.prototype.cur does not use fx argument
  788. fx = i ? fx : this;
  789. // Don't run animations on textual properties like align (#1821)
  790. if (fx.prop === 'align') {
  791. return;
  792. }
  793. // shortcut
  794. elem = fx.elem;
  795. // Fx.prototype.cur returns the current value. The other ones are setters
  796. // and returning a value has no effect.
  797. return elem.attr ? // is SVG element wrapper
  798. elem.attr(fx.prop, fn === 'cur' ? UNDEFINED : fx.now) : // apply the SVG wrapper's method
  799. base.apply(this, arguments); // use jQuery's built-in method
  800. };
  801. }
  802. });
  803. // Extend the opacity getter, needed for fading opacity with IE9 and jQuery 1.10+
  804. wrap($.cssHooks.opacity, 'get', function (proceed, elem, computed) {
  805. return elem.attr ? (elem.opacity || 0) : proceed.call(this, elem, computed);
  806. });
  807. // Define the setter function for d (path definitions)
  808. this.addAnimSetter('d', function (fx) {
  809. var elem = fx.elem,
  810. ends;
  811. // Normally start and end should be set in state == 0, but sometimes,
  812. // for reasons unknown, this doesn't happen. Perhaps state == 0 is skipped
  813. // in these cases
  814. if (!fx.started) {
  815. ends = pathAnim.init(elem, elem.d, elem.toD);
  816. fx.start = ends[0];
  817. fx.end = ends[1];
  818. fx.started = true;
  819. }
  820. // Interpolate each value of the path
  821. elem.attr('d', pathAnim.step(fx.start, fx.end, fx.pos, elem.toD));
  822. });
  823. /**
  824. * Utility for iterating over an array. Parameters are reversed compared to jQuery.
  825. * @param {Array} arr
  826. * @param {Function} fn
  827. */
  828. this.each = Array.prototype.forEach ?
  829. function (arr, fn) { // modern browsers
  830. return Array.prototype.forEach.call(arr, fn);
  831. } :
  832. function (arr, fn) { // legacy
  833. var i,
  834. len = arr.length;
  835. for (i = 0; i < len; i++) {
  836. if (fn.call(arr[i], arr[i], i, arr) === false) {
  837. return i;
  838. }
  839. }
  840. };
  841. /**
  842. * Register Highcharts as a plugin in the respective framework
  843. */
  844. $.fn.highcharts = function () {
  845. var constr = 'Chart', // default constructor
  846. args = arguments,
  847. options,
  848. ret,
  849. chart;
  850. if (this[0]) {
  851. if (isString(args[0])) {
  852. constr = args[0];
  853. args = Array.prototype.slice.call(args, 1);
  854. }
  855. options = args[0];
  856. // Create the chart
  857. if (options !== UNDEFINED) {
  858. /*jslint unused:false*/
  859. options.chart = options.chart || {};
  860. options.chart.renderTo = this[0];
  861. chart = new Highcharts[constr](options, args[1]);
  862. ret = this;
  863. /*jslint unused:true*/
  864. }
  865. // When called without parameters or with the return argument, get a predefined chart
  866. if (options === UNDEFINED) {
  867. ret = charts[attr(this[0], 'data-highcharts-chart')];
  868. }
  869. }
  870. return ret;
  871. };
  872. },
  873. /**
  874. * Add an animation setter for a specific property
  875. */
  876. addAnimSetter: function (prop, setter) {
  877. // jQuery 1.8 style
  878. if ($.Tween) {
  879. $.Tween.propHooks[prop] = {
  880. set: setter
  881. };
  882. // pre 1.8
  883. } else {
  884. $.fx.step[prop] = setter;
  885. }
  886. },
  887. /**
  888. * Downloads a script and executes a callback when done.
  889. * @param {String} scriptLocation
  890. * @param {Function} callback
  891. */
  892. getScript: $.getScript,
  893. /**
  894. * Return the index of an item in an array, or -1 if not found
  895. */
  896. inArray: $.inArray,
  897. /**
  898. * A direct link to jQuery methods. MooTools and Prototype adapters must be implemented for each case of method.
  899. * @param {Object} elem The HTML element
  900. * @param {String} method Which method to run on the wrapped element
  901. */
  902. adapterRun: function (elem, method) {
  903. return $(elem)[method]();
  904. },
  905. /**
  906. * Filter an array
  907. */
  908. grep: $.grep,
  909. /**
  910. * Map an array
  911. * @param {Array} arr
  912. * @param {Function} fn
  913. */
  914. map: function (arr, fn) {
  915. //return jQuery.map(arr, fn);
  916. var results = [],
  917. i = 0,
  918. len = arr.length;
  919. for (; i < len; i++) {
  920. results[i] = fn.call(arr[i], arr[i], i, arr);
  921. }
  922. return results;
  923. },
  924. /**
  925. * Get the position of an element relative to the top left of the page
  926. */
  927. offset: function (el) {
  928. return $(el).offset();
  929. },
  930. /**
  931. * Add an event listener
  932. * @param {Object} el A HTML element or custom object
  933. * @param {String} event The event type
  934. * @param {Function} fn The event handler
  935. */
  936. addEvent: function (el, event, fn) {
  937. $(el).bind(event, fn);
  938. },
  939. /**
  940. * Remove event added with addEvent
  941. * @param {Object} el The object
  942. * @param {String} eventType The event type. Leave blank to remove all events.
  943. * @param {Function} handler The function to remove
  944. */
  945. removeEvent: function (el, eventType, handler) {
  946. // workaround for jQuery issue with unbinding custom events:
  947. // http://forum.jQuery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jQuery-1-4-2
  948. var func = doc.removeEventListener ? 'removeEventListener' : 'detachEvent';
  949. if (doc[func] && el && !el[func]) {
  950. el[func] = function () {};
  951. }
  952. $(el).unbind(eventType, handler);
  953. },
  954. /**
  955. * Fire an event on a custom object
  956. * @param {Object} el
  957. * @param {String} type
  958. * @param {Object} eventArguments
  959. * @param {Function} defaultFunction
  960. */
  961. fireEvent: function (el, type, eventArguments, defaultFunction) {
  962. var event = $.Event(type),
  963. detachedType = 'detached' + type,
  964. defaultPrevented;
  965. // Remove warnings in Chrome when accessing returnValue (#2790), layerX and layerY. Although Highcharts
  966. // never uses these properties, Chrome includes them in the default click event and
  967. // raises the warning when they are copied over in the extend statement below.
  968. //
  969. // To avoid problems in IE (see #1010) where we cannot delete the properties and avoid
  970. // testing if they are there (warning in chrome) the only option is to test if running IE.
  971. if (!isIE && eventArguments) {
  972. delete eventArguments.layerX;
  973. delete eventArguments.layerY;
  974. delete eventArguments.returnValue;
  975. }
  976. extend(event, eventArguments);
  977. // Prevent jQuery from triggering the object method that is named the
  978. // same as the event. For example, if the event is 'select', jQuery
  979. // attempts calling el.select and it goes into a loop.
  980. if (el[type]) {
  981. el[detachedType] = el[type];
  982. el[type] = null;
  983. }
  984. // Wrap preventDefault and stopPropagation in try/catch blocks in
  985. // order to prevent JS errors when cancelling events on non-DOM
  986. // objects. #615.
  987. /*jslint unparam: true*/
  988. $.each(['preventDefault', 'stopPropagation'], function (i, fn) {
  989. var base = event[fn];
  990. event[fn] = function () {
  991. try {
  992. base.call(event);
  993. } catch (e) {
  994. if (fn === 'preventDefault') {
  995. defaultPrevented = true;
  996. }
  997. }
  998. };
  999. });
  1000. /*jslint unparam: false*/
  1001. // trigger it
  1002. $(el).trigger(event);
  1003. // attach the method
  1004. if (el[detachedType]) {
  1005. el[type] = el[detachedType];
  1006. el[detachedType] = null;
  1007. }
  1008. if (defaultFunction && !event.isDefaultPrevented() && !defaultPrevented) {
  1009. defaultFunction(event);
  1010. }
  1011. },
  1012. /**
  1013. * Extension method needed for MooTools
  1014. */
  1015. washMouseEvent: function (e) {
  1016. var ret = e.originalEvent || e;
  1017. // computed by jQuery, needed by IE8
  1018. if (ret.pageX === UNDEFINED) { // #1236
  1019. ret.pageX = e.pageX;
  1020. ret.pageY = e.pageY;
  1021. }
  1022. return ret;
  1023. },
  1024. /**
  1025. * Animate a HTML element or SVG element wrapper
  1026. * @param {Object} el
  1027. * @param {Object} params
  1028. * @param {Object} options jQuery-like animation options: duration, easing, callback
  1029. */
  1030. animate: function (el, params, options) {
  1031. var $el = $(el);
  1032. if (!el.style) {
  1033. el.style = {}; // #1881
  1034. }
  1035. if (params.d) {
  1036. el.toD = params.d; // keep the array form for paths, used in $.fx.step.d
  1037. params.d = 1; // because in jQuery, animating to an array has a different meaning
  1038. }
  1039. $el.stop();
  1040. if (params.opacity !== UNDEFINED && el.attr) {
  1041. params.opacity += 'px'; // force jQuery to use same logic as width and height (#2161)
  1042. }
  1043. el.hasAnim = 1; // #3342
  1044. $el.animate(params, options);
  1045. },
  1046. /**
  1047. * Stop running animation
  1048. */
  1049. stop: function (el) {
  1050. if (el.hasAnim) { // #3342, memory leak on calling $(el) from destroy
  1051. $(el).stop();
  1052. }
  1053. }
  1054. });
  1055. }(win.jQuery));
  1056. // check for a custom HighchartsAdapter defined prior to this file
  1057. var globalAdapter = win.HighchartsAdapter,
  1058. adapter = globalAdapter || {};
  1059. // Initialize the adapter
  1060. if (globalAdapter) {
  1061. globalAdapter.init.call(globalAdapter, pathAnim);
  1062. }
  1063. // Utility functions. If the HighchartsAdapter is not defined, adapter is an empty object
  1064. // and all the utility functions will be null. In that case they are populated by the
  1065. // default adapters below.
  1066. var adapterRun = adapter.adapterRun,
  1067. getScript = adapter.getScript,
  1068. inArray = adapter.inArray,
  1069. each = Highcharts.each = adapter.each,
  1070. grep = adapter.grep,
  1071. offset = adapter.offset,
  1072. map = adapter.map,
  1073. addEvent = adapter.addEvent,
  1074. removeEvent = adapter.removeEvent,
  1075. fireEvent = adapter.fireEvent,
  1076. washMouseEvent = adapter.washMouseEvent,
  1077. animate = adapter.animate,
  1078. stop = adapter.stop;
  1079. /* ****************************************************************************
  1080. * Handle the options *
  1081. *****************************************************************************/
  1082. defaultOptions = {
  1083. colors: ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c',
  1084. '#8085e9', '#f15c80', '#e4d354', '#2b908f', '#f45b5b', '#91e8e1'],
  1085. symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'],
  1086. lang: {
  1087. loading: 'Loading...',
  1088. months: ['January', 'February', 'March', 'April', 'May', 'June', 'July',
  1089. 'August', 'September', 'October', 'November', 'December'],
  1090. shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  1091. weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  1092. decimalPoint: '.',
  1093. numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels
  1094. resetZoom: 'Reset zoom',
  1095. resetZoomTitle: 'Reset zoom level 1:1',
  1096. thousandsSep: ' '
  1097. },
  1098. global: {
  1099. useUTC: true,
  1100. //timezoneOffset: 0,
  1101. canvasToolsURL: 'http://code.highcharts.com/4.1.5/modules/canvas-tools.js',
  1102. VMLRadialGradientURL: 'http://code.highcharts.com/4.1.5/gfx/vml-radial-gradient.png'
  1103. },
  1104. chart: {
  1105. //animation: true,
  1106. //alignTicks: false,
  1107. //reflow: true,
  1108. //className: null,
  1109. //events: { load, selection },
  1110. //margin: [null],
  1111. //marginTop: null,
  1112. //marginRight: null,
  1113. //marginBottom: null,
  1114. //marginLeft: null,
  1115. borderColor: '#4572A7',
  1116. //borderWidth: 0,
  1117. borderRadius: 0,
  1118. defaultSeriesType: 'line',
  1119. ignoreHiddenSeries: true,
  1120. //inverted: false,
  1121. //shadow: false,
  1122. spacing: [10, 10, 15, 10],
  1123. //spacingTop: 10,
  1124. //spacingRight: 10,
  1125. //spacingBottom: 15,
  1126. //spacingLeft: 10,
  1127. //style: {
  1128. // fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font
  1129. // fontSize: '12px'
  1130. //},
  1131. backgroundColor: '#FFFFFF',
  1132. //plotBackgroundColor: null,
  1133. plotBorderColor: '#C0C0C0',
  1134. //plotBorderWidth: 0,
  1135. //plotShadow: false,
  1136. //zoomType: ''
  1137. resetZoomButton: {
  1138. theme: {
  1139. zIndex: 20
  1140. },
  1141. position: {
  1142. align: 'right',
  1143. x: -10,
  1144. //verticalAlign: 'top',
  1145. y: 10
  1146. }
  1147. // relativeTo: 'plot'
  1148. }
  1149. },
  1150. title: {
  1151. text: 'Chart title',
  1152. align: 'center',
  1153. // floating: false,
  1154. margin: 15,
  1155. // x: 0,
  1156. // verticalAlign: 'top',
  1157. // y: null,
  1158. style: {
  1159. color: '#333333',
  1160. fontSize: '18px'
  1161. }
  1162. },
  1163. subtitle: {
  1164. text: '',
  1165. align: 'center',
  1166. // floating: false
  1167. // x: 0,
  1168. // verticalAlign: 'top',
  1169. // y: null,
  1170. style: {
  1171. color: '#555555'
  1172. }
  1173. },
  1174. plotOptions: {
  1175. line: { // base series options
  1176. allowPointSelect: false,
  1177. showCheckbox: false,
  1178. animation: {
  1179. duration: 1000
  1180. },
  1181. //connectNulls: false,
  1182. //cursor: 'default',
  1183. //clip: true,
  1184. //dashStyle: null,
  1185. //enableMouseTracking: true,
  1186. events: {},
  1187. //legendIndex: 0,
  1188. //linecap: 'round',
  1189. lineWidth: 2,
  1190. //shadow: false,
  1191. // stacking: null,
  1192. marker: {
  1193. //enabled: true,
  1194. //symbol: null,
  1195. lineWidth: 0,
  1196. radius: 4,
  1197. lineColor: '#FFFFFF',
  1198. //fillColor: null,
  1199. states: { // states for a single point
  1200. hover: {
  1201. enabled: true,
  1202. lineWidthPlus: 1,
  1203. radiusPlus: 2
  1204. },
  1205. select: {
  1206. fillColor: '#FFFFFF',
  1207. lineColor: '#000000',
  1208. lineWidth: 2
  1209. }
  1210. }
  1211. },
  1212. point: {
  1213. events: {}
  1214. },
  1215. dataLabels: {
  1216. align: 'center',
  1217. // defer: true,
  1218. // enabled: false,
  1219. formatter: function () {
  1220. return this.y === null ? '' : Highcharts.numberFormat(this.y, -1);
  1221. },
  1222. style: {
  1223. color: 'contrast',
  1224. fontSize: '11px',
  1225. fontWeight: 'bold',
  1226. textShadow: '0 0 6px contrast, 0 0 3px contrast'
  1227. },
  1228. verticalAlign: 'bottom', // above singular point
  1229. x: 0,
  1230. y: 0,
  1231. // backgroundColor: undefined,
  1232. // borderColor: undefined,
  1233. // borderRadius: undefined,
  1234. // borderWidth: undefined,
  1235. padding: 5
  1236. // shadow: false
  1237. },
  1238. cropThreshold: 300, // draw points outside the plot area when the number of points is less than this
  1239. pointRange: 0,
  1240. //pointStart: 0,
  1241. //pointInterval: 1,
  1242. //showInLegend: null, // auto: true for standalone series, false for linked series
  1243. states: { // states for the entire series
  1244. hover: {
  1245. //enabled: false,
  1246. lineWidthPlus: 1,
  1247. marker: {
  1248. // lineWidth: base + 1,
  1249. // radius: base + 1
  1250. },
  1251. halo: {
  1252. size: 10,
  1253. opacity: 0.25
  1254. }
  1255. },
  1256. select: {
  1257. marker: {}
  1258. }
  1259. },
  1260. stickyTracking: true,
  1261. //tooltip: {
  1262. //pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b>'
  1263. //valueDecimals: null,
  1264. //xDateFormat: '%A, %b %e, %Y',
  1265. //valuePrefix: '',
  1266. //ySuffix: ''
  1267. //}
  1268. turboThreshold: 1000
  1269. // zIndex: null
  1270. }
  1271. },
  1272. labels: {
  1273. //items: [],
  1274. style: {
  1275. //font: defaultFont,
  1276. position: ABSOLUTE,
  1277. color: '#3E576F'
  1278. }
  1279. },
  1280. legend: {
  1281. enabled: true,
  1282. align: 'center',
  1283. //floating: false,
  1284. layout: 'horizontal',
  1285. labelFormatter: function () {
  1286. return this.name;
  1287. },
  1288. //borderWidth: 0,
  1289. borderColor: '#909090',
  1290. borderRadius: 0,
  1291. navigation: {
  1292. // animation: true,
  1293. activeColor: '#274b6d',
  1294. // arrowSize: 12
  1295. inactiveColor: '#CCC'
  1296. // style: {} // text styles
  1297. },
  1298. // margin: 20,
  1299. // reversed: false,
  1300. shadow: false,
  1301. // backgroundColor: null,
  1302. /*style: {
  1303. padding: '5px'
  1304. },*/
  1305. itemStyle: {
  1306. color: '#333333',
  1307. fontSize: '12px',
  1308. fontWeight: 'bold'
  1309. },
  1310. itemHoverStyle: {
  1311. //cursor: 'pointer', removed as of #601
  1312. color: '#000'
  1313. },
  1314. itemHiddenStyle: {
  1315. color: '#CCC'
  1316. },
  1317. itemCheckboxStyle: {
  1318. position: ABSOLUTE,
  1319. width: '13px', // for IE precision
  1320. height: '13px'
  1321. },
  1322. // itemWidth: undefined,
  1323. // symbolRadius: 0,
  1324. // symbolWidth: 16,
  1325. symbolPadding: 5,
  1326. verticalAlign: 'bottom',
  1327. // width: undefined,
  1328. x: 0,
  1329. y: 0,
  1330. title: {
  1331. //text: null,
  1332. style: {
  1333. fontWeight: 'bold'
  1334. }
  1335. }
  1336. },
  1337. loading: {
  1338. // hideDuration: 100,
  1339. labelStyle: {
  1340. fontWeight: 'bold',
  1341. position: RELATIVE,
  1342. top: '45%'
  1343. },
  1344. // showDuration: 0,
  1345. style: {
  1346. position: ABSOLUTE,
  1347. backgroundColor: 'white',
  1348. opacity: 0.5,
  1349. textAlign: 'center'
  1350. }
  1351. },
  1352. tooltip: {
  1353. enabled: true,
  1354. animation: hasSVG,
  1355. //crosshairs: null,
  1356. backgroundColor: 'rgba(249, 249, 249, .85)',
  1357. borderWidth: 1,
  1358. borderRadius: 3,
  1359. dateTimeLabelFormats: {
  1360. millisecond: '%A, %b %e, %H:%M:%S.%L',
  1361. second: '%A, %b %e, %H:%M:%S',
  1362. minute: '%A, %b %e, %H:%M',
  1363. hour: '%A, %b %e, %H:%M',
  1364. day: '%A, %b %e, %Y',
  1365. week: 'Week from %A, %b %e, %Y',
  1366. month: '%B %Y',
  1367. year: '%Y'
  1368. },
  1369. footerFormat: '',
  1370. //formatter: defaultFormatter,
  1371. headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>',
  1372. pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b><br/>',
  1373. shadow: true,
  1374. //shape: 'callout',
  1375. //shared: false,
  1376. snap: isTouchDevice ? 25 : 10,
  1377. style: {
  1378. color: '#333333',
  1379. cursor: 'default',
  1380. fontSize: '12px',
  1381. padding: '8px',
  1382. whiteSpace: 'nowrap'
  1383. }
  1384. //xDateFormat: '%A, %b %e, %Y',
  1385. //valueDecimals: null,
  1386. //valuePrefix: '',
  1387. //valueSuffix: ''
  1388. },
  1389. credits: {
  1390. enabled: true,
  1391. text: 'Highcharts.com',
  1392. href: 'http://www.highcharts.com',
  1393. position: {
  1394. align: 'right',
  1395. x: -10,
  1396. verticalAlign: 'bottom',
  1397. y: -5
  1398. },
  1399. style: {
  1400. cursor: 'pointer',
  1401. color: '#909090',
  1402. fontSize: '9px'
  1403. }
  1404. }
  1405. };
  1406. // Series defaults
  1407. var defaultPlotOptions = defaultOptions.plotOptions,
  1408. defaultSeriesOptions = defaultPlotOptions.line;
  1409. // set the default time methods
  1410. setTimeMethods();
  1411. /**
  1412. * Set the time methods globally based on the useUTC option. Time method can be either
  1413. * local time or UTC (default).
  1414. */
  1415. function setTimeMethods() {
  1416. var globalOptions = defaultOptions.global,
  1417. useUTC = globalOptions.useUTC,
  1418. GET = useUTC ? 'getUTC' : 'get',
  1419. SET = useUTC ? 'setUTC' : 'set';
  1420. Date = globalOptions.Date || window.Date;
  1421. timezoneOffset = useUTC && globalOptions.timezoneOffset;
  1422. getTimezoneOffset = useUTC && globalOptions.getTimezoneOffset;
  1423. makeTime = function (year, month, date, hours, minutes, seconds) {
  1424. var d;
  1425. if (useUTC) {
  1426. d = Date.UTC.apply(0, arguments);
  1427. d += getTZOffset(d);
  1428. } else {
  1429. d = new Date(
  1430. year,
  1431. month,
  1432. pick(date, 1),
  1433. pick(hours, 0),
  1434. pick(minutes, 0),
  1435. pick(seconds, 0)
  1436. ).getTime();
  1437. }
  1438. return d;
  1439. };
  1440. getMinutes = GET + 'Minutes';
  1441. getHours = GET + 'Hours';
  1442. getDay = GET + 'Day';
  1443. getDate = GET + 'Date';
  1444. getMonth = GET + 'Month';
  1445. getFullYear = GET + 'FullYear';
  1446. setMilliseconds = SET + 'Milliseconds';
  1447. setSeconds = SET + 'Seconds';
  1448. setMinutes = SET + 'Minutes';
  1449. setHours = SET + 'Hours';
  1450. setDate = SET + 'Date';
  1451. setMonth = SET + 'Month';
  1452. setFullYear = SET + 'FullYear';
  1453. }
  1454. /**
  1455. * Merge the default options with custom options and return the new options structure
  1456. * @param {Object} options The new custom options
  1457. */
  1458. function setOptions(options) {
  1459. // Copy in the default options
  1460. defaultOptions = merge(true, defaultOptions, options);
  1461. // Apply UTC
  1462. setTimeMethods();
  1463. return defaultOptions;
  1464. }
  1465. /**
  1466. * Get the updated default options. Until 3.0.7, merely exposing defaultOptions for outside modules
  1467. * wasn't enough because the setOptions method created a new object.
  1468. */
  1469. function getOptions() {
  1470. return defaultOptions;
  1471. }
  1472. /**
  1473. * Handle color operations. The object methods are chainable.
  1474. * @param {String} input The input color in either rbga or hex format
  1475. */
  1476. var rgbaRegEx = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/,
  1477. hexRegEx = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/,
  1478. rgbRegEx = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/;
  1479. var Color = function (input) {
  1480. // declare variables
  1481. var rgba = [], result, stops;
  1482. /**
  1483. * Parse the input color to rgba array
  1484. * @param {String} input
  1485. */
  1486. function init(input) {
  1487. // Gradients
  1488. if (input && input.stops) {
  1489. stops = map(input.stops, function (stop) {
  1490. return Color(stop[1]);
  1491. });
  1492. // Solid colors
  1493. } else {
  1494. // rgba
  1495. result = rgbaRegEx.exec(input);
  1496. if (result) {
  1497. rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)];
  1498. } else {
  1499. // hex
  1500. result = hexRegEx.exec(input);
  1501. if (result) {
  1502. rgba = [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1];
  1503. } else {
  1504. // rgb
  1505. result = rgbRegEx.exec(input);
  1506. if (result) {
  1507. rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1];
  1508. }
  1509. }
  1510. }
  1511. }
  1512. }
  1513. /**
  1514. * Return the color a specified format
  1515. * @param {String} format
  1516. */
  1517. function get(format) {
  1518. var ret;
  1519. if (stops) {
  1520. ret = merge(input);
  1521. ret.stops = [].concat(ret.stops);
  1522. each(stops, function (stop, i) {
  1523. ret.stops[i] = [ret.stops[i][0], stop.get(format)];
  1524. });
  1525. // it's NaN if gradient colors on a column chart
  1526. } else if (rgba && !isNaN(rgba[0])) {
  1527. if (format === 'rgb') {
  1528. ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')';
  1529. } else if (format === 'a') {
  1530. ret = rgba[3];
  1531. } else {
  1532. ret = 'rgba(' + rgba.join(',') + ')';
  1533. }
  1534. } else {
  1535. ret = input;
  1536. }
  1537. return ret;
  1538. }
  1539. /**
  1540. * Brighten the color
  1541. * @param {Number} alpha
  1542. */
  1543. function brighten(alpha) {
  1544. if (stops) {
  1545. each(stops, function (stop) {
  1546. stop.brighten(alpha);
  1547. });
  1548. } else if (isNumber(alpha) && alpha !== 0) {
  1549. var i;
  1550. for (i = 0; i < 3; i++) {
  1551. rgba[i] += pInt(alpha * 255);
  1552. if (rgba[i] < 0) {
  1553. rgba[i] = 0;
  1554. }
  1555. if (rgba[i] > 255) {
  1556. rgba[i] = 255;
  1557. }
  1558. }
  1559. }
  1560. return this;
  1561. }
  1562. /**
  1563. * Set the color's opacity to a given alpha value
  1564. * @param {Number} alpha
  1565. */
  1566. function setOpacity(alpha) {
  1567. rgba[3] = alpha;
  1568. return this;
  1569. }
  1570. // initialize: parse the input
  1571. init(input);
  1572. // public methods
  1573. return {
  1574. get: get,
  1575. brighten: brighten,
  1576. rgba: rgba,
  1577. setOpacity: setOpacity,
  1578. raw: input
  1579. };
  1580. };
  1581. /**
  1582. * A wrapper object for SVG elements
  1583. */
  1584. function SVGElement() {}
  1585. SVGElement.prototype = {
  1586. // Default base for animation
  1587. opacity: 1,
  1588. // For labels, these CSS properties are applied to the <text> node directly
  1589. textProps: ['fontSize', 'fontWeight', 'fontFamily', 'fontStyle', 'color',
  1590. 'lineHeight', 'width', 'textDecoration', 'textShadow'],
  1591. /**
  1592. * Initialize the SVG renderer
  1593. * @param {Object} renderer
  1594. * @param {String} nodeName
  1595. */
  1596. init: function (renderer, nodeName) {
  1597. var wrapper = this;
  1598. wrapper.element = nodeName === 'span' ?
  1599. createElement(nodeName) :
  1600. doc.createElementNS(SVG_NS, nodeName);
  1601. wrapper.renderer = renderer;
  1602. },
  1603. /**
  1604. * Animate a given attribute
  1605. * @param {Object} params
  1606. * @param {Number} options The same options as in jQuery animation
  1607. * @param {Function} complete Function to perform at the end of animation
  1608. */
  1609. animate: function (params, options, complete) {
  1610. var animOptions = pick(options, globalAnimation, true);
  1611. stop(this); // stop regardless of animation actually running, or reverting to .attr (#607)
  1612. if (animOptions) {
  1613. animOptions = merge(animOptions, {}); //#2625
  1614. if (complete) { // allows using a callback with the global animation without overwriting it
  1615. animOptions.complete = complete;
  1616. }
  1617. animate(this, params, animOptions);
  1618. } else {
  1619. this.attr(params);
  1620. if (complete) {
  1621. complete();
  1622. }
  1623. }
  1624. return this;
  1625. },
  1626. /**
  1627. * Build an SVG gradient out of a common JavaScript configuration object
  1628. */
  1629. colorGradient: function (color, prop, elem) {
  1630. var renderer = this.renderer,
  1631. colorObject,
  1632. gradName,
  1633. gradAttr,
  1634. gradients,
  1635. gradientObject,
  1636. stops,
  1637. stopColor,
  1638. stopOpacity,
  1639. radialReference,
  1640. n,
  1641. id,
  1642. key = [];
  1643. // Apply linear or radial gradients
  1644. if (color.linearGradient) {
  1645. gradName = 'linearGradient';
  1646. } else if (color.radialGradient) {
  1647. gradName = 'radialGradient';
  1648. }
  1649. if (gradName) {
  1650. gradAttr = color[gradName];
  1651. gradients = renderer.gradients;
  1652. stops = color.stops;
  1653. radialReference = elem.radialReference;
  1654. // Keep < 2.2 kompatibility
  1655. if (isArray(gradAttr)) {
  1656. color[gradName] = gradAttr = {
  1657. x1: gradAttr[0],
  1658. y1: gradAttr[1],
  1659. x2: gradAttr[2],
  1660. y2: gradAttr[3],
  1661. gradientUnits: 'userSpaceOnUse'
  1662. };
  1663. }
  1664. // Correct the radial gradient for the radial reference system
  1665. if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) {
  1666. gradAttr = merge(gradAttr, {
  1667. cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2],
  1668. cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2],
  1669. r: gradAttr.r * radialReference[2],
  1670. gradientUnits: 'userSpaceOnUse'
  1671. });
  1672. }
  1673. // Build the unique key to detect whether we need to create a new element (#1282)
  1674. for (n in gradAttr) {
  1675. if (n !== 'id') {
  1676. key.push(n, gradAttr[n]);
  1677. }
  1678. }
  1679. for (n in stops) {
  1680. key.push(stops[n]);
  1681. }
  1682. key = key.join(',');
  1683. // Check if a gradient object with the same config object is created within this renderer
  1684. if (gradients[key]) {
  1685. id = gradients[key].attr('id');
  1686. } else {
  1687. // Set the id and create the element
  1688. gradAttr.id = id = PREFIX + idCounter++;
  1689. gradients[key] = gradientObject = renderer.createElement(gradName)
  1690. .attr(gradAttr)
  1691. .add(renderer.defs);
  1692. // The gradient needs to keep a list of stops to be able to destroy them
  1693. gradientObject.stops = [];
  1694. each(stops, function (stop) {
  1695. var stopObject;
  1696. if (stop[1].indexOf('rgba') === 0) {
  1697. colorObject = Color(stop[1]);
  1698. stopColor = colorObject.get('rgb');
  1699. stopOpacity = colorObject.get('a');
  1700. } else {
  1701. stopColor = stop[1];
  1702. stopOpacity = 1;
  1703. }
  1704. stopObject = renderer.createElement('stop').attr({
  1705. offset: stop[0],
  1706. 'stop-color': stopColor,
  1707. 'stop-opacity': stopOpacity
  1708. }).add(gradientObject);
  1709. // Add the stop element to the gradient
  1710. gradientObject.stops.push(stopObject);
  1711. });
  1712. }
  1713. // Set the reference to the gradient object
  1714. elem.setAttribute(prop, 'url(' + renderer.url + '#' + id + ')');
  1715. }
  1716. },
  1717. /**
  1718. * Apply a polyfill to the text-stroke CSS property, by copying the text element
  1719. * and apply strokes to the copy.
  1720. *
  1721. * docs: update default, document the polyfill and the limitations on hex colors and pixel values, document contrast pseudo-color
  1722. * TODO:
  1723. * - update defaults
  1724. */
  1725. applyTextShadow: function (textShadow) {
  1726. var elem = this.element,
  1727. tspans,
  1728. hasContrast = textShadow.indexOf('contrast') !== -1,
  1729. // IE10 and IE11 report textShadow in elem.style even though it doesn't work. Check
  1730. // this again with new IE release. In exports, the rendering is passed to PhantomJS.
  1731. supports = this.renderer.forExport || (elem.style.textShadow !== UNDEFINED && !isIE);
  1732. // When the text shadow is set to contrast, use dark stroke for light text and vice versa
  1733. if (hasContrast) {
  1734. textShadow = textShadow.replace(/contrast/g, this.renderer.getContrast(elem.style.fill));
  1735. }
  1736. /* Selective side-by-side testing in supported browser (http://jsfiddle.net/highcharts/73L1ptrh/)
  1737. if (elem.textContent.indexOf('2.') === 0) {
  1738. elem.style['text-shadow'] = 'none';
  1739. supports = false;
  1740. }
  1741. // */
  1742. // No reason to polyfill, we've got native support
  1743. if (supports) {
  1744. if (hasContrast) { // Apply the altered style
  1745. css(elem, {
  1746. textShadow: textShadow
  1747. });
  1748. }
  1749. } else {
  1750. this.fakeTS = true; // Fake text shadow
  1751. // In order to get the right y position of the clones,
  1752. // copy over the y setter
  1753. this.ySetter = this.xSetter;
  1754. tspans = [].slice.call(elem.getElementsByTagName('tspan'));
  1755. each(textShadow.split(/\s?,\s?/g), function (textShadow) {
  1756. var firstChild = elem.firstChild,
  1757. color,
  1758. strokeWidth;
  1759. textShadow = textShadow.split(' ');
  1760. color = textShadow[textShadow.length - 1];
  1761. // Approximately tune the settings to the text-shadow behaviour
  1762. strokeWidth = textShadow[textShadow.length - 2];
  1763. if (strokeWidth) {
  1764. each(tspans, function (tspan, y) {
  1765. var clone;
  1766. // Let the first line start at the correct X position
  1767. if (y === 0) {
  1768. tspan.setAttribute('x', elem.getAttribute('x'));
  1769. y = elem.getAttribute('y');
  1770. tspan.setAttribute('y', y || 0);
  1771. if (y === null) {
  1772. elem.setAttribute('y', 0);
  1773. }
  1774. }
  1775. // Create the clone and apply shadow properties
  1776. clone = tspan.cloneNode(1);
  1777. attr(clone, {
  1778. 'class': PREFIX + 'text-shadow',
  1779. 'fill': color,
  1780. 'stroke': color,
  1781. 'stroke-opacity': 1 / mathMax(pInt(strokeWidth), 3),
  1782. 'stroke-width': strokeWidth,
  1783. 'stroke-linejoin': 'round'
  1784. });
  1785. elem.insertBefore(clone, firstChild);
  1786. });
  1787. }
  1788. });
  1789. }
  1790. },
  1791. /**
  1792. * Set or get a given attribute
  1793. * @param {Object|String} hash
  1794. * @param {Mixed|Undefined} val
  1795. */
  1796. attr: function (hash, val) {
  1797. var key,
  1798. value,
  1799. element = this.element,
  1800. hasSetSymbolSize,
  1801. ret = this,
  1802. skipAttr;
  1803. // single key-value pair
  1804. if (typeof hash === 'string' && val !== UNDEFINED) {
  1805. key = hash;
  1806. hash = {};
  1807. hash[key] = val;
  1808. }
  1809. // used as a getter: first argument is a string, second is undefined
  1810. if (typeof hash === 'string') {
  1811. ret = (this[hash + 'Getter'] || this._defaultGetter).call(this, hash, element);
  1812. // setter
  1813. } else {
  1814. for (key in hash) {
  1815. value = hash[key];
  1816. skipAttr = false;
  1817. if (this.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) {
  1818. if (!hasSetSymbolSize) {
  1819. this.symbolAttr(hash);
  1820. hasSetSymbolSize = true;
  1821. }
  1822. skipAttr = true;
  1823. }
  1824. if (this.rotation && (key === 'x' || key === 'y')) {
  1825. this.doTransform = true;
  1826. }
  1827. if (!skipAttr) {
  1828. (this[key + 'Setter'] || this._defaultSetter).call(this, value, key, element);
  1829. }
  1830. // Let the shadow follow the main element
  1831. if (this.shadows && /^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(key)) {
  1832. this.updateShadows(key, value);
  1833. }
  1834. }
  1835. // Update transform. Do this outside the loop to prevent redundant updating for batch setting
  1836. // of attributes.
  1837. if (this.doTransform) {
  1838. this.updateTransform();
  1839. this.doTransform = false;
  1840. }
  1841. }
  1842. return ret;
  1843. },
  1844. updateShadows: function (key, value) {
  1845. var shadows = this.shadows,
  1846. i = shadows.length;
  1847. while (i--) {
  1848. shadows[i].setAttribute(
  1849. key,
  1850. key === 'height' ?
  1851. mathMax(value - (shadows[i].cutHeight || 0), 0) :
  1852. key === 'd' ? this.d : value
  1853. );
  1854. }
  1855. },
  1856. /**
  1857. * Add a class name to an element
  1858. */
  1859. addClass: function (className) {
  1860. var element = this.element,
  1861. currentClassName = attr(element, 'class') || '';
  1862. if (currentClassName.indexOf(className) === -1) {
  1863. attr(element, 'class', currentClassName + ' ' + className);
  1864. }
  1865. return this;
  1866. },
  1867. /* hasClass and removeClass are not (yet) needed
  1868. hasClass: function (className) {
  1869. return attr(this.element, 'class').indexOf(className) !== -1;
  1870. },
  1871. removeClass: function (className) {
  1872. attr(this.element, 'class', attr(this.element, 'class').replace(className, ''));
  1873. return this;
  1874. },
  1875. */
  1876. /**
  1877. * If one of the symbol size affecting parameters are changed,
  1878. * check all the others only once for each call to an element's
  1879. * .attr() method
  1880. * @param {Object} hash
  1881. */
  1882. symbolAttr: function (hash) {
  1883. var wrapper = this;
  1884. each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function (key) {
  1885. wrapper[key] = pick(hash[key], wrapper[key]);
  1886. });
  1887. wrapper.attr({
  1888. d: wrapper.renderer.symbols[wrapper.symbolName](
  1889. wrapper.x,
  1890. wrapper.y,
  1891. wrapper.width,
  1892. wrapper.height,
  1893. wrapper
  1894. )
  1895. });
  1896. },
  1897. /**
  1898. * Apply a clipping path to this object
  1899. * @param {String} id
  1900. */
  1901. clip: function (clipRect) {
  1902. return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : NONE);
  1903. },
  1904. /**
  1905. * Calculate the coordinates needed for drawing a rectangle crisply and return the
  1906. * calculated attributes
  1907. * @param {Number} strokeWidth
  1908. * @param {Number} x
  1909. * @param {Number} y
  1910. * @param {Number} width
  1911. * @param {Number} height
  1912. */
  1913. crisp: function (rect) {
  1914. var wrapper = this,
  1915. key,
  1916. attribs = {},
  1917. normalizer,
  1918. strokeWidth = rect.strokeWidth || wrapper.strokeWidth || 0;
  1919. normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors
  1920. // normalize for crisp edges
  1921. rect.x = mathFloor(rect.x || wrapper.x || 0) + normalizer;
  1922. rect.y = mathFloor(rect.y || wrapper.y || 0) + normalizer;
  1923. rect.width = mathFloor((rect.width || wrapper.width || 0) - 2 * normalizer);
  1924. rect.height = mathFloor((rect.height || wrapper.height || 0) - 2 * normalizer);
  1925. rect.strokeWidth = strokeWidth;
  1926. for (key in rect) {
  1927. if (wrapper[key] !== rect[key]) { // only set attribute if changed
  1928. wrapper[key] = attribs[key] = rect[key];
  1929. }
  1930. }
  1931. return attribs;
  1932. },
  1933. /**
  1934. * Set styles for the element
  1935. * @param {Object} styles
  1936. */
  1937. css: function (styles) {
  1938. var elemWrapper = this,
  1939. oldStyles = elemWrapper.styles,
  1940. newStyles = {},
  1941. elem = elemWrapper.element,
  1942. textWidth,
  1943. n,
  1944. serializedCss = '',
  1945. hyphenate,
  1946. hasNew = !oldStyles;
  1947. // convert legacy
  1948. if (styles && styles.color) {
  1949. styles.fill = styles.color;
  1950. }
  1951. // Filter out existing styles to increase performance (#2640)
  1952. if (oldStyles) {
  1953. for (n in styles) {
  1954. if (styles[n] !== oldStyles[n]) {
  1955. newStyles[n] = styles[n];
  1956. hasNew = true;
  1957. }
  1958. }
  1959. }
  1960. if (hasNew) {
  1961. textWidth = elemWrapper.textWidth =
  1962. (styles && styles.width && elem.nodeName.toLowerCase() === 'text' && pInt(styles.width)) ||
  1963. elemWrapper.textWidth; // #3501
  1964. // Merge the new styles with the old ones
  1965. if (oldStyles) {
  1966. styles = extend(
  1967. oldStyles,
  1968. newStyles
  1969. );
  1970. }
  1971. // store object
  1972. elemWrapper.styles = styles;
  1973. if (textWidth && (useCanVG || (!hasSVG && elemWrapper.renderer.forExport))) {
  1974. delete styles.width;
  1975. }
  1976. // serialize and set style attribute
  1977. if (isIE && !hasSVG) {
  1978. css(elemWrapper.element, styles);
  1979. } else {
  1980. /*jslint unparam: true*/
  1981. hyphenate = function (a, b) { return '-' + b.toLowerCase(); };
  1982. /*jslint unparam: false*/
  1983. for (n in styles) {
  1984. serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';';
  1985. }
  1986. attr(elem, 'style', serializedCss); // #1881
  1987. }
  1988. // re-build text
  1989. if (textWidth && elemWrapper.added) {
  1990. elemWrapper.renderer.buildText(elemWrapper);
  1991. }
  1992. }
  1993. return elemWrapper;
  1994. },
  1995. /**
  1996. * Add an event listener
  1997. * @param {String} eventType
  1998. * @param {Function} handler
  1999. */
  2000. on: function (eventType, handler) {
  2001. var svgElement = this,
  2002. element = svgElement.element;
  2003. // touch
  2004. if (hasTouch && eventType === 'click') {
  2005. element.ontouchstart = function (e) {
  2006. svgElement.touchEventFired = Date.now();
  2007. e.preventDefault();
  2008. handler.call(element, e);
  2009. };
  2010. element.onclick = function (e) {
  2011. if (userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { // #2269
  2012. handler.call(element, e);
  2013. }
  2014. };
  2015. } else {
  2016. // simplest possible event model for internal use
  2017. element['on' + eventType] = handler;
  2018. }
  2019. return this;
  2020. },
  2021. /**
  2022. * Set the coordinates needed to draw a consistent radial gradient across
  2023. * pie slices regardless of positioning inside the chart. The format is
  2024. * [centerX, centerY, diameter] in pixels.
  2025. */
  2026. setRadialReference: function (coordinates) {
  2027. this.element.radialReference = coordinates;
  2028. return this;
  2029. },
  2030. /**
  2031. * Move an object and its children by x and y values
  2032. * @param {Number} x
  2033. * @param {Number} y
  2034. */
  2035. translate: function (x, y) {
  2036. return this.attr({
  2037. translateX: x,
  2038. translateY: y
  2039. });
  2040. },
  2041. /**
  2042. * Invert a group, rotate and flip
  2043. */
  2044. invert: function () {
  2045. var wrapper = this;
  2046. wrapper.inverted = true;
  2047. wrapper.updateTransform();
  2048. return wrapper;
  2049. },
  2050. /**
  2051. * Private method to update the transform attribute based on internal
  2052. * properties
  2053. */
  2054. updateTransform: function () {
  2055. var wrapper = this,
  2056. translateX = wrapper.translateX || 0,
  2057. translateY = wrapper.translateY || 0,
  2058. scaleX = wrapper.scaleX,
  2059. scaleY = wrapper.scaleY,
  2060. inverted = wrapper.inverted,
  2061. rotation = wrapper.rotation,
  2062. element = wrapper.element,
  2063. transform;
  2064. // flipping affects translate as adjustment for flipping around the group's axis
  2065. if (inverted) {
  2066. translateX += wrapper.attr('width');
  2067. translateY += wrapper.attr('height');
  2068. }
  2069. // Apply translate. Nearly all transformed elements have translation, so instead
  2070. // of checking for translate = 0, do it always (#1767, #1846).
  2071. transform = ['translate(' + translateX + ',' + translateY + ')'];
  2072. // apply rotation
  2073. if (inverted) {
  2074. transform.push('rotate(90) scale(-1,1)');
  2075. } else if (rotation) { // text rotation
  2076. transform.push('rotate(' + rotation + ' ' + (element.getAttribute('x') || 0) + ' ' + (element.getAttribute('y') || 0) + ')');
  2077. // Delete bBox memo when the rotation changes
  2078. //delete wrapper.bBox;
  2079. }
  2080. // apply scale
  2081. if (defined(scaleX) || defined(scaleY)) {
  2082. transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')');
  2083. }
  2084. if (transform.length) {
  2085. element.setAttribute('transform', transform.join(' '));
  2086. }
  2087. },
  2088. /**
  2089. * Bring the element to the front
  2090. */
  2091. toFront: function () {
  2092. var element = this.element;
  2093. element.parentNode.appendChild(element);
  2094. return this;
  2095. },
  2096. /**
  2097. * Break down alignment options like align, verticalAlign, x and y
  2098. * to x and y relative to the chart.
  2099. *
  2100. * @param {Object} alignOptions
  2101. * @param {Boolean} alignByTranslate
  2102. * @param {String[Object} box The box to align to, needs a width and height. When the
  2103. * box is a string, it refers to an object in the Renderer. For example, when
  2104. * box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height
  2105. * x and y properties.
  2106. *
  2107. */
  2108. align: function (alignOptions, alignByTranslate, box) {
  2109. var align,
  2110. vAlign,
  2111. x,
  2112. y,
  2113. attribs = {},
  2114. alignTo,
  2115. renderer = this.renderer,
  2116. alignedObjects = renderer.alignedObjects;
  2117. // First call on instanciate
  2118. if (alignOptions) {
  2119. this.alignOptions = alignOptions;
  2120. this.alignByTranslate = alignByTranslate;
  2121. if (!box || isString(box)) { // boxes other than renderer handle this internally
  2122. this.alignTo = alignTo = box || 'renderer';
  2123. erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize
  2124. alignedObjects.push(this);
  2125. box = null; // reassign it below
  2126. }
  2127. // When called on resize, no arguments are supplied
  2128. } else {
  2129. alignOptions = this.alignOptions;
  2130. alignByTranslate = this.alignByTranslate;
  2131. alignTo = this.alignTo;
  2132. }
  2133. box = pick(box, renderer[alignTo], renderer);
  2134. // Assign variables
  2135. align = alignOptions.align;
  2136. vAlign = alignOptions.verticalAlign;
  2137. x = (box.x || 0) + (alignOptions.x || 0); // default: left align
  2138. y = (box.y || 0) + (alignOptions.y || 0); // default: top align
  2139. // Align
  2140. if (align === 'right' || align === 'center') {
  2141. x += (box.width - (alignOptions.width || 0)) /
  2142. { right: 1, center: 2 }[align];
  2143. }
  2144. attribs[alignByTranslate ? 'translateX' : 'x'] = mathRound(x);
  2145. // Vertical align
  2146. if (vAlign === 'bottom' || vAlign === 'middle') {
  2147. y += (box.height - (alignOptions.height || 0)) /
  2148. ({ bottom: 1, middle: 2 }[vAlign] || 1);
  2149. }
  2150. attribs[alignByTranslate ? 'translateY' : 'y'] = mathRound(y);
  2151. // Animate only if already placed
  2152. this[this.placed ? 'animate' : 'attr'](attribs);
  2153. this.placed = true;
  2154. this.alignAttr = attribs;
  2155. return this;
  2156. },
  2157. /**
  2158. * Get the bounding box (width, height, x and y) for the element
  2159. */
  2160. getBBox: function (reload) {
  2161. var wrapper = this,
  2162. bBox,// = wrapper.bBox,
  2163. renderer = wrapper.renderer,
  2164. width,
  2165. height,
  2166. rotation = wrapper.rotation,
  2167. element = wrapper.element,
  2168. styles = wrapper.styles,
  2169. rad = rotation * deg2rad,
  2170. textStr = wrapper.textStr,
  2171. textShadow,
  2172. elemStyle = element.style,
  2173. toggleTextShadowShim,
  2174. cacheKey;
  2175. if (textStr !== UNDEFINED) {
  2176. // Properties that affect bounding box
  2177. cacheKey = ['', rotation || 0, styles && styles.fontSize, element.style.width].join(',');
  2178. // Since numbers are monospaced, and numerical labels appear a lot in a chart,
  2179. // we assume that a label of n characters has the same bounding box as others
  2180. // of the same length.
  2181. if (textStr === '' || numRegex.test(textStr)) {
  2182. cacheKey = 'num:' + textStr.toString().length + cacheKey;
  2183. // Caching all strings reduces rendering time by 4-5%.
  2184. } else {
  2185. cacheKey = textStr + cacheKey;
  2186. }
  2187. }
  2188. if (cacheKey && !reload) {
  2189. bBox = renderer.cache[cacheKey];
  2190. }
  2191. // No cache found
  2192. if (!bBox) {
  2193. // SVG elements
  2194. if (element.namespaceURI === SVG_NS || renderer.forExport) {
  2195. try { // Fails in Firefox if the container has display: none.
  2196. // When the text shadow shim is used, we need to hide the fake shadows
  2197. // to get the correct bounding box (#3872)
  2198. toggleTextShadowShim = this.fakeTS && function (display) {
  2199. each(element.querySelectorAll('.' + PREFIX + 'text-shadow'), function (tspan) {
  2200. tspan.style.display = display;
  2201. });
  2202. };
  2203. // Workaround for #3842, Firefox reporting wrong bounding box for shadows
  2204. if (isFirefox && elemStyle.textShadow) {
  2205. textShadow = elemStyle.textShadow;
  2206. elemStyle.textShadow = '';
  2207. } else if (toggleTextShadowShim) {
  2208. toggleTextShadowShim(NONE);
  2209. }
  2210. bBox = element.getBBox ?
  2211. // SVG: use extend because IE9 is not allowed to change width and height in case
  2212. // of rotation (below)
  2213. extend({}, element.getBBox()) :
  2214. // Canvas renderer and legacy IE in export mode
  2215. {
  2216. width: element.offsetWidth,
  2217. height: element.offsetHeight
  2218. };
  2219. // #3842
  2220. if (textShadow) {
  2221. elemStyle.textShadow = textShadow;
  2222. } else if (toggleTextShadowShim) {
  2223. toggleTextShadowShim('');
  2224. }
  2225. } catch (e) {}
  2226. // If the bBox is not set, the try-catch block above failed. The other condition
  2227. // is for Opera that returns a width of -Infinity on hidden elements.
  2228. if (!bBox || bBox.width < 0) {
  2229. bBox = { width: 0, height: 0 };
  2230. }
  2231. // VML Renderer or useHTML within SVG
  2232. } else {
  2233. bBox = wrapper.htmlGetBBox();
  2234. }
  2235. // True SVG elements as well as HTML elements in modern browsers using the .useHTML option
  2236. // need to compensated for rotation
  2237. if (renderer.isSVG) {
  2238. width = bBox.width;
  2239. height = bBox.height;
  2240. // Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669, #2568)
  2241. if (isIE && styles && styles.fontSize === '11px' && height.toPrecision(3) === '16.9') {
  2242. bBox.height = height = 14;
  2243. }
  2244. // Adjust for rotated text
  2245. if (rotation) {
  2246. bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad));
  2247. bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad));
  2248. }
  2249. }
  2250. // Cache it
  2251. renderer.cache[cacheKey] = bBox;
  2252. }
  2253. return bBox;
  2254. },
  2255. /**
  2256. * Show the element
  2257. */
  2258. show: function (inherit) {
  2259. // IE9-11 doesn't handle visibilty:inherit well, so we remove the attribute instead (#2881)
  2260. if (inherit && this.element.namespaceURI === SVG_NS) {
  2261. this.element.removeAttribute('visibility');
  2262. } else {
  2263. this.attr({ visibility: inherit ? 'inherit' : VISIBLE });
  2264. }
  2265. return this;
  2266. },
  2267. /**
  2268. * Hide the element
  2269. */
  2270. hide: function () {
  2271. return this.attr({ visibility: HIDDEN });
  2272. },
  2273. fadeOut: function (duration) {
  2274. var elemWrapper = this;
  2275. elemWrapper.animate({
  2276. opacity: 0
  2277. }, {
  2278. duration: duration || 150,
  2279. complete: function () {
  2280. elemWrapper.attr({ y: -9999 }); // #3088, assuming we're only using this for tooltips
  2281. }
  2282. });
  2283. },
  2284. /**
  2285. * Add the element
  2286. * @param {Object|Undefined} parent Can be an element, an element wrapper or undefined
  2287. * to append the element to the renderer.box.
  2288. */
  2289. add: function (parent) {
  2290. var renderer = this.renderer,
  2291. element = this.element,
  2292. inserted;
  2293. if (parent) {
  2294. this.parentGroup = parent;
  2295. }
  2296. // mark as inverted
  2297. this.parentInverted = parent && parent.inverted;
  2298. // build formatted text
  2299. if (this.textStr !== undefined) {
  2300. renderer.buildText(this);
  2301. }
  2302. // Mark as added
  2303. this.added = true;
  2304. // If we're adding to renderer root, or other elements in the group
  2305. // have a z index, we need to handle it
  2306. if (!parent || parent.handleZ || this.zIndex) {
  2307. inserted = this.zIndexSetter();
  2308. }
  2309. // If zIndex is not handled, append at the end
  2310. if (!inserted) {
  2311. (parent ? parent.element : renderer.box).appendChild(element);
  2312. }
  2313. // fire an event for internal hooks
  2314. if (this.onAdd) {
  2315. this.onAdd();
  2316. }
  2317. return this;
  2318. },
  2319. /**
  2320. * Removes a child either by removeChild or move to garbageBin.
  2321. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not.
  2322. */
  2323. safeRemoveChild: function (element) {
  2324. var parentNode = element.parentNode;
  2325. if (parentNode) {
  2326. parentNode.removeChild(element);
  2327. }
  2328. },
  2329. /**
  2330. * Destroy the element and element wrapper
  2331. */
  2332. destroy: function () {
  2333. var wrapper = this,
  2334. element = wrapper.element || {},
  2335. shadows = wrapper.shadows,
  2336. parentToClean = wrapper.renderer.isSVG && element.nodeName === 'SPAN' && wrapper.parentGroup,
  2337. grandParent,
  2338. key,
  2339. i;
  2340. // remove events
  2341. element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null;
  2342. stop(wrapper); // stop running animations
  2343. if (wrapper.clipPath) {
  2344. wrapper.clipPath = wrapper.clipPath.destroy();
  2345. }
  2346. // Destroy stops in case this is a gradient object
  2347. if (wrapper.stops) {
  2348. for (i = 0; i < wrapper.stops.length; i++) {
  2349. wrapper.stops[i] = wrapper.stops[i].destroy();
  2350. }
  2351. wrapper.stops = null;
  2352. }
  2353. // remove element
  2354. wrapper.safeRemoveChild(element);
  2355. // destroy shadows
  2356. if (shadows) {
  2357. each(shadows, function (shadow) {
  2358. wrapper.safeRemoveChild(shadow);
  2359. });
  2360. }
  2361. // In case of useHTML, clean up empty containers emulating SVG groups (#1960, #2393, #2697).
  2362. while (parentToClean && parentToClean.div && parentToClean.div.childNodes.length === 0) {
  2363. grandParent = parentToClean.parentGroup;
  2364. wrapper.safeRemoveChild(parentToClean.div);
  2365. delete parentToClean.div;
  2366. parentToClean = grandParent;
  2367. }
  2368. // remove from alignObjects
  2369. if (wrapper.alignTo) {
  2370. erase(wrapper.renderer.alignedObjects, wrapper);
  2371. }
  2372. for (key in wrapper) {
  2373. delete wrapper[key];
  2374. }
  2375. return null;
  2376. },
  2377. /**
  2378. * Add a shadow to the element. Must be done after the element is added to the DOM
  2379. * @param {Boolean|Object} shadowOptions
  2380. */
  2381. shadow: function (shadowOptions, group, cutOff) {
  2382. var shadows = [],
  2383. i,
  2384. shadow,
  2385. element = this.element,
  2386. strokeWidth,
  2387. shadowWidth,
  2388. shadowElementOpacity,
  2389. // compensate for inverted plot area
  2390. transform;
  2391. if (shadowOptions) {
  2392. shadowWidth = pick(shadowOptions.width, 3);
  2393. shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth;
  2394. transform = this.parentInverted ?
  2395. '(-1,-1)' :
  2396. '(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')';
  2397. for (i = 1; i <= shadowWidth; i++) {
  2398. shadow = element.cloneNode(0);
  2399. strokeWidth = (shadowWidth * 2) + 1 - (2 * i);
  2400. attr(shadow, {
  2401. 'isShadow': 'true',
  2402. 'stroke': shadowOptions.color || 'black',
  2403. 'stroke-opacity': shadowElementOpacity * i,
  2404. 'stroke-width': strokeWidth,
  2405. 'transform': 'translate' + transform,
  2406. 'fill': NONE
  2407. });
  2408. if (cutOff) {
  2409. attr(shadow, 'height', mathMax(attr(shadow, 'height') - strokeWidth, 0));
  2410. shadow.cutHeight = strokeWidth;
  2411. }
  2412. if (group) {
  2413. group.element.appendChild(shadow);
  2414. } else {
  2415. element.parentNode.insertBefore(shadow, element);
  2416. }
  2417. shadows.push(shadow);
  2418. }
  2419. this.shadows = shadows;
  2420. }
  2421. return this;
  2422. },
  2423. xGetter: function (key) {
  2424. if (this.element.nodeName === 'circle') {
  2425. key = { x: 'cx', y: 'cy' }[key] || key;
  2426. }
  2427. return this._defaultGetter(key);
  2428. },
  2429. /**
  2430. * Get the current value of an attribute or pseudo attribute, used mainly
  2431. * for animation.
  2432. */
  2433. _defaultGetter: function (key) {
  2434. var ret = pick(this[key], this.element ? this.element.getAttribute(key) : null, 0);
  2435. if (/^[\-0-9\.]+$/.test(ret)) { // is numerical
  2436. ret = parseFloat(ret);
  2437. }
  2438. return ret;
  2439. },
  2440. dSetter: function (value, key, element) {
  2441. if (value && value.join) { // join path
  2442. value = value.join(' ');
  2443. }
  2444. if (/(NaN| {2}|^$)/.test(value)) {
  2445. value = 'M 0 0';
  2446. }
  2447. element.setAttribute(key, value);
  2448. this[key] = value;
  2449. },
  2450. dashstyleSetter: function (value) {
  2451. var i;
  2452. value = value && value.toLowerCase();
  2453. if (value) {
  2454. value = value
  2455. .replace('shortdashdotdot', '3,1,1,1,1,1,')
  2456. .replace('shortdashdot', '3,1,1,1')
  2457. .replace('shortdot', '1,1,')
  2458. .replace('shortdash', '3,1,')
  2459. .replace('longdash', '8,3,')
  2460. .replace(/dot/g, '1,3,')
  2461. .replace('dash', '4,3,')
  2462. .replace(/,$/, '')
  2463. .split(','); // ending comma
  2464. i = value.length;
  2465. while (i--) {
  2466. value[i] = pInt(value[i]) * this['stroke-width'];
  2467. }
  2468. value = value.join(',')
  2469. .replace('NaN', 'none'); // #3226
  2470. this.element.setAttribute('stroke-dasharray', value);
  2471. }
  2472. },
  2473. alignSetter: function (value) {
  2474. this.element.setAttribute('text-anchor', { left: 'start', center: 'middle', right: 'end' }[value]);
  2475. },
  2476. opacitySetter: function (value, key, element) {
  2477. this[key] = value;
  2478. element.setAttribute(key, value);
  2479. },
  2480. titleSetter: function (value) {
  2481. var titleNode = this.element.getElementsByTagName('title')[0];
  2482. if (!titleNode) {
  2483. titleNode = doc.createElementNS(SVG_NS, 'title');
  2484. this.element.appendChild(titleNode);
  2485. }
  2486. titleNode.textContent = (String(pick(value), '')).replace(/<[^>]*>/g, ''); // #3276 #3895
  2487. },
  2488. textSetter: function (value) {
  2489. if (value !== this.textStr) {
  2490. // Delete bBox memo when the text changes
  2491. delete this.bBox;
  2492. this.textStr = value;
  2493. if (this.added) {
  2494. this.renderer.buildText(this);
  2495. }
  2496. }
  2497. },
  2498. fillSetter: function (value, key, element) {
  2499. if (typeof value === 'string') {
  2500. element.setAttribute(key, value);
  2501. } else if (value) {
  2502. this.colorGradient(value, key, element);
  2503. }
  2504. },
  2505. zIndexSetter: function (value, key) {
  2506. var renderer = this.renderer,
  2507. parentGroup = this.parentGroup,
  2508. parentWrapper = parentGroup || renderer,
  2509. parentNode = parentWrapper.element || renderer.box,
  2510. childNodes,
  2511. otherElement,
  2512. otherZIndex,
  2513. element = this.element,
  2514. inserted,
  2515. run = this.added,
  2516. i;
  2517. if (defined(value)) {
  2518. element.setAttribute(key, value); // So we can read it for other elements in the group
  2519. value = +value;
  2520. if (this[key] === value) { // Only update when needed (#3865)
  2521. run = false;
  2522. }
  2523. this[key] = value;
  2524. }
  2525. // Insert according to this and other elements' zIndex. Before .add() is called,
  2526. // nothing is done. Then on add, or by later calls to zIndexSetter, the node
  2527. // is placed on the right place in the DOM.
  2528. if (run) {
  2529. value = this.zIndex;
  2530. if (value && parentGroup) {
  2531. parentGroup.handleZ = true;
  2532. }
  2533. childNodes = parentNode.childNodes;
  2534. for (i = 0; i < childNodes.length && !inserted; i++) {
  2535. otherElement = childNodes[i];
  2536. otherZIndex = attr(otherElement, 'zIndex');
  2537. if (otherElement !== element && (
  2538. // Insert before the first element with a higher zIndex
  2539. pInt(otherZIndex) > value ||
  2540. // If no zIndex given, insert before the first element with a zIndex
  2541. (!defined(value) && defined(otherZIndex))
  2542. )) {
  2543. parentNode.insertBefore(element, otherElement);
  2544. inserted = true;
  2545. }
  2546. }
  2547. if (!inserted) {
  2548. parentNode.appendChild(element);
  2549. }
  2550. }
  2551. return inserted;
  2552. },
  2553. _defaultSetter: function (value, key, element) {
  2554. element.setAttribute(key, value);
  2555. }
  2556. };
  2557. // Some shared setters and getters
  2558. SVGElement.prototype.yGetter = SVGElement.prototype.xGetter;
  2559. SVGElement.prototype.translateXSetter = SVGElement.prototype.translateYSetter =
  2560. SVGElement.prototype.rotationSetter = SVGElement.prototype.verticalAlignSetter =
  2561. SVGElement.prototype.scaleXSetter = SVGElement.prototype.scaleYSetter = function (value, key) {
  2562. this[key] = value;
  2563. this.doTransform = true;
  2564. };
  2565. // WebKit and Batik have problems with a stroke-width of zero, so in this case we remove the
  2566. // stroke attribute altogether. #1270, #1369, #3065, #3072.
  2567. SVGElement.prototype['stroke-widthSetter'] = SVGElement.prototype.strokeSetter = function (value, key, element) {
  2568. this[key] = value;
  2569. // Only apply the stroke attribute if the stroke width is defined and larger than 0
  2570. if (this.stroke && this['stroke-width']) {
  2571. this.strokeWidth = this['stroke-width'];
  2572. SVGElement.prototype.fillSetter.call(this, this.stroke, 'stroke', element); // use prototype as instance may be overridden
  2573. element.setAttribute('stroke-width', this['stroke-width']);
  2574. this.hasStroke = true;
  2575. } else if (key === 'stroke-width' && value === 0 && this.hasStroke) {
  2576. element.removeAttribute('stroke');
  2577. this.hasStroke = false;
  2578. }
  2579. };
  2580. /**
  2581. * The default SVG renderer
  2582. */
  2583. var SVGRenderer = function () {
  2584. this.init.apply(this, arguments);
  2585. };
  2586. SVGRenderer.prototype = {
  2587. Element: SVGElement,
  2588. /**
  2589. * Initialize the SVGRenderer
  2590. * @param {Object} container
  2591. * @param {Number} width
  2592. * @param {Number} height
  2593. * @param {Boolean} forExport
  2594. */
  2595. init: function (container, width, height, style, forExport) {
  2596. var renderer = this,
  2597. loc = location,
  2598. boxWrapper,
  2599. element,
  2600. desc;
  2601. boxWrapper = renderer.createElement('svg')
  2602. .attr({
  2603. version: '1.1'
  2604. })
  2605. .css(this.getStyle(style));
  2606. element = boxWrapper.element;
  2607. container.appendChild(element);
  2608. // For browsers other than IE, add the namespace attribute (#1978)
  2609. if (container.innerHTML.indexOf('xmlns') === -1) {
  2610. attr(element, 'xmlns', SVG_NS);
  2611. }
  2612. // object properties
  2613. renderer.isSVG = true;
  2614. renderer.box = element;
  2615. renderer.boxWrapper = boxWrapper;
  2616. renderer.alignedObjects = [];
  2617. // Page url used for internal references. #24, #672, #1070
  2618. renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ?
  2619. loc.href
  2620. .replace(/#.*?$/, '') // remove the hash
  2621. .replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes
  2622. .replace(/ /g, '%20') : // replace spaces (needed for Safari only)
  2623. '';
  2624. // Add description
  2625. desc = this.createElement('desc').add();
  2626. desc.element.appendChild(doc.createTextNode('Created with ' + PRODUCT + ' ' + VERSION));
  2627. renderer.defs = this.createElement('defs').add();
  2628. renderer.forExport = forExport;
  2629. renderer.gradients = {}; // Object where gradient SvgElements are stored
  2630. renderer.cache = {}; // Cache for numerical bounding boxes
  2631. renderer.setSize(width, height, false);
  2632. // Issue 110 workaround:
  2633. // In Firefox, if a div is positioned by percentage, its pixel position may land
  2634. // between pixels. The container itself doesn't display this, but an SVG element
  2635. // inside this container will be drawn at subpixel precision. In order to draw
  2636. // sharp lines, this must be compensated for. This doesn't seem to work inside
  2637. // iframes though (like in jsFiddle).
  2638. var subPixelFix, rect;
  2639. if (isFirefox && container.getBoundingClientRect) {
  2640. renderer.subPixelFix = subPixelFix = function () {
  2641. css(container, { left: 0, top: 0 });
  2642. rect = container.getBoundingClientRect();
  2643. css(container, {
  2644. left: (mathCeil(rect.left) - rect.left) + PX,
  2645. top: (mathCeil(rect.top) - rect.top) + PX
  2646. });
  2647. };
  2648. // run the fix now
  2649. subPixelFix();
  2650. // run it on resize
  2651. addEvent(win, 'resize', subPixelFix);
  2652. }
  2653. },
  2654. getStyle: function (style) {
  2655. return (this.style = extend({
  2656. fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif', // default font
  2657. fontSize: '12px'
  2658. }, style));
  2659. },
  2660. /**
  2661. * Detect whether the renderer is hidden. This happens when one of the parent elements
  2662. * has display: none. #608.
  2663. */
  2664. isHidden: function () {
  2665. return !this.boxWrapper.getBBox().width;
  2666. },
  2667. /**
  2668. * Destroys the renderer and its allocated members.
  2669. */
  2670. destroy: function () {
  2671. var renderer = this,
  2672. rendererDefs = renderer.defs;
  2673. renderer.box = null;
  2674. renderer.boxWrapper = renderer.boxWrapper.destroy();
  2675. // Call destroy on all gradient elements
  2676. destroyObjectProperties(renderer.gradients || {});
  2677. renderer.gradients = null;
  2678. // Defs are null in VMLRenderer
  2679. // Otherwise, destroy them here.
  2680. if (rendererDefs) {
  2681. renderer.defs = rendererDefs.destroy();
  2682. }
  2683. // Remove sub pixel fix handler
  2684. // We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed
  2685. // See issue #982
  2686. if (renderer.subPixelFix) {
  2687. removeEvent(win, 'resize', renderer.subPixelFix);
  2688. }
  2689. renderer.alignedObjects = null;
  2690. return null;
  2691. },
  2692. /**
  2693. * Create a wrapper for an SVG element
  2694. * @param {Object} nodeName
  2695. */
  2696. createElement: function (nodeName) {
  2697. var wrapper = new this.Element();
  2698. wrapper.init(this, nodeName);
  2699. return wrapper;
  2700. },
  2701. /**
  2702. * Dummy function for use in canvas renderer
  2703. */
  2704. draw: function () {},
  2705. /**
  2706. * Parse a simple HTML string into SVG tspans
  2707. *
  2708. * @param {Object} textNode The parent text SVG node
  2709. */
  2710. buildText: function (wrapper) {
  2711. var textNode = wrapper.element,
  2712. renderer = this,
  2713. forExport = renderer.forExport,
  2714. textStr = pick(wrapper.textStr, '').toString(),
  2715. hasMarkup = textStr.indexOf('<') !== -1,
  2716. lines,
  2717. childNodes = textNode.childNodes,
  2718. styleRegex,
  2719. hrefRegex,
  2720. parentX = attr(textNode, 'x'),
  2721. textStyles = wrapper.styles,
  2722. width = wrapper.textWidth,
  2723. textLineHeight = textStyles && textStyles.lineHeight,
  2724. textShadow = textStyles && textStyles.textShadow,
  2725. ellipsis = textStyles && textStyles.textOverflow === 'ellipsis',
  2726. i = childNodes.length,
  2727. tempParent = width && !wrapper.added && this.box,
  2728. getLineHeight = function (tspan) {
  2729. return textLineHeight ?
  2730. pInt(textLineHeight) :
  2731. renderer.fontMetrics(
  2732. /(px|em)$/.test(tspan && tspan.style.fontSize) ?
  2733. tspan.style.fontSize :
  2734. ((textStyles && textStyles.fontSize) || renderer.style.fontSize || 12),
  2735. tspan
  2736. ).h;
  2737. },
  2738. unescapeAngleBrackets = function (inputStr) {
  2739. return inputStr.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
  2740. };
  2741. /// remove old text
  2742. while (i--) {
  2743. textNode.removeChild(childNodes[i]);
  2744. }
  2745. // Skip tspans, add text directly to text node. The forceTSpan is a hook
  2746. // used in text outline hack.
  2747. if (!hasMarkup && !textShadow && !ellipsis && textStr.indexOf(' ') === -1) {
  2748. textNode.appendChild(doc.createTextNode(unescapeAngleBrackets(textStr)));
  2749. return;
  2750. // Complex strings, add more logic
  2751. } else {
  2752. styleRegex = /<.*style="([^"]+)".*>/;
  2753. hrefRegex = /<.*href="(http[^"]+)".*>/;
  2754. if (tempParent) {
  2755. tempParent.appendChild(textNode); // attach it to the DOM to read offset width
  2756. }
  2757. if (hasMarkup) {
  2758. lines = textStr
  2759. .replace(/<(b|strong)>/g, '<span style="font-weight:bold">')
  2760. .replace(/<(i|em)>/g, '<span style="font-style:italic">')
  2761. .replace(/<a/g, '<span')
  2762. .replace(/<\/(b|strong|i|em|a)>/g, '</span>')
  2763. .split(/<br.*?>/g);
  2764. } else {
  2765. lines = [textStr];
  2766. }
  2767. // remove empty line at end
  2768. if (lines[lines.length - 1] === '') {
  2769. lines.pop();
  2770. }
  2771. // build the lines
  2772. each(lines, function (line, lineNo) {
  2773. var spans, spanNo = 0;
  2774. line = line.replace(/<span/g, '|||<span').replace(/<\/span>/g, '</span>|||');
  2775. spans = line.split('|||');
  2776. each(spans, function (span) {
  2777. if (span !== '' || spans.length === 1) {
  2778. var attributes = {},
  2779. tspan = doc.createElementNS(SVG_NS, 'tspan'),
  2780. spanStyle; // #390
  2781. if (styleRegex.test(span)) {
  2782. spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2');
  2783. attr(tspan, 'style', spanStyle);
  2784. }
  2785. if (hrefRegex.test(span) && !forExport) { // Not for export - #1529
  2786. attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"');
  2787. css(tspan, { cursor: 'pointer' });
  2788. }
  2789. span = unescapeAngleBrackets(span.replace(/<(.|\n)*?>/g, '') || ' ');
  2790. // Nested tags aren't supported, and cause crash in Safari (#1596)
  2791. if (span !== ' ') {
  2792. // add the text node
  2793. tspan.appendChild(doc.createTextNode(span));
  2794. if (!spanNo) { // first span in a line, align it to the left
  2795. if (lineNo && parentX !== null) {
  2796. attributes.x = parentX;
  2797. }
  2798. } else {
  2799. attributes.dx = 0; // #16
  2800. }
  2801. // add attributes
  2802. attr(tspan, attributes);
  2803. // Append it
  2804. textNode.appendChild(tspan);
  2805. // first span on subsequent line, add the line height
  2806. if (!spanNo && lineNo) {
  2807. // allow getting the right offset height in exporting in IE
  2808. if (!hasSVG && forExport) {
  2809. css(tspan, { display: 'block' });
  2810. }
  2811. // Set the line height based on the font size of either
  2812. // the text element or the tspan element
  2813. attr(
  2814. tspan,
  2815. 'dy',
  2816. getLineHeight(tspan)
  2817. );
  2818. }
  2819. /*if (width) {
  2820. renderer.breakText(wrapper, width);
  2821. }*/
  2822. // Check width and apply soft breaks or ellipsis
  2823. if (width) {
  2824. var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273
  2825. hasWhiteSpace = spans.length > 1 || lineNo || (words.length > 1 && textStyles.whiteSpace !== 'nowrap'),
  2826. tooLong,
  2827. wasTooLong,
  2828. actualWidth,
  2829. rest = [],
  2830. dy = getLineHeight(tspan),
  2831. softLineNo = 1,
  2832. rotation = wrapper.rotation,
  2833. wordStr = span, // for ellipsis
  2834. cursor = wordStr.length, // binary search cursor
  2835. bBox;
  2836. while ((hasWhiteSpace || ellipsis) && (words.length || rest.length)) {
  2837. wrapper.rotation = 0; // discard rotation when computing box
  2838. bBox = wrapper.getBBox(true);
  2839. actualWidth = bBox.width;
  2840. // Old IE cannot measure the actualWidth for SVG elements (#2314)
  2841. if (!hasSVG && renderer.forExport) {
  2842. actualWidth = renderer.measureSpanWidth(tspan.firstChild.data, wrapper.styles);
  2843. }
  2844. tooLong = actualWidth > width;
  2845. // For ellipsis, do a binary search for the correct string length
  2846. if (wasTooLong === undefined) {
  2847. wasTooLong = tooLong; // First time
  2848. }
  2849. if (ellipsis && wasTooLong) {
  2850. cursor /= 2;
  2851. if (wordStr === '' || (!tooLong && cursor < 0.5)) {
  2852. words = []; // All ok, break out
  2853. } else {
  2854. if (tooLong) {
  2855. wasTooLong = true;
  2856. }
  2857. wordStr = span.substring(0, wordStr.length + (tooLong ? -1 : 1) * mathCeil(cursor));
  2858. words = [wordStr + '\u2026'];
  2859. tspan.removeChild(tspan.firstChild);
  2860. }
  2861. // Looping down, this is the first word sequence that is not too long,
  2862. // so we can move on to build the next line.
  2863. } else if (!tooLong || words.length === 1) {
  2864. words = rest;
  2865. rest = [];
  2866. if (words.length) {
  2867. softLineNo++;
  2868. tspan = doc.createElementNS(SVG_NS, 'tspan');
  2869. attr(tspan, {
  2870. dy: dy,
  2871. x: parentX
  2872. });
  2873. if (spanStyle) { // #390
  2874. attr(tspan, 'style', spanStyle);
  2875. }
  2876. textNode.appendChild(tspan);
  2877. }
  2878. if (actualWidth > width) { // a single word is pressing it out
  2879. width = actualWidth;
  2880. }
  2881. } else { // append to existing line tspan
  2882. tspan.removeChild(tspan.firstChild);
  2883. rest.unshift(words.pop());
  2884. }
  2885. if (words.length) {
  2886. tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-')));
  2887. }
  2888. }
  2889. if (wasTooLong) {
  2890. wrapper.attr('title', wrapper.textStr);
  2891. }
  2892. wrapper.rotation = rotation;
  2893. }
  2894. spanNo++;
  2895. }
  2896. }
  2897. });
  2898. });
  2899. if (tempParent) {
  2900. tempParent.removeChild(textNode); // attach it to the DOM to read offset width
  2901. }
  2902. // Apply the text shadow
  2903. if (textShadow && wrapper.applyTextShadow) {
  2904. wrapper.applyTextShadow(textShadow);
  2905. }
  2906. }
  2907. },
  2908. /*
  2909. breakText: function (wrapper, width) {
  2910. var bBox = wrapper.getBBox(),
  2911. node = wrapper.element,
  2912. textLength = node.textContent.length,
  2913. pos = mathRound(width * textLength / bBox.width), // try this position first, based on average character width
  2914. increment = 0,
  2915. finalPos;
  2916. if (bBox.width > width) {
  2917. while (finalPos === undefined) {
  2918. textLength = node.getSubStringLength(0, pos);
  2919. if (textLength <= width) {
  2920. if (increment === -1) {
  2921. finalPos = pos;
  2922. } else {
  2923. increment = 1;
  2924. }
  2925. } else {
  2926. if (increment === 1) {
  2927. finalPos = pos - 1;
  2928. } else {
  2929. increment = -1;
  2930. }
  2931. }
  2932. pos += increment;
  2933. }
  2934. }
  2935. console.log(finalPos, node.getSubStringLength(0, finalPos))
  2936. },
  2937. */
  2938. /**
  2939. * Returns white for dark colors and black for bright colors
  2940. */
  2941. getContrast: function (color) {
  2942. color = Color(color).rgba;
  2943. return color[0] + color[1] + color[2] > 384 ? '#000' : '#FFF';
  2944. },
  2945. /**
  2946. * Create a button with preset states
  2947. * @param {String} text
  2948. * @param {Number} x
  2949. * @param {Number} y
  2950. * @param {Function} callback
  2951. * @param {Object} normalState
  2952. * @param {Object} hoverState
  2953. * @param {Object} pressedState
  2954. */
  2955. button: function (text, x, y, callback, normalState, hoverState, pressedState, disabledState, shape) {
  2956. var label = this.label(text, x, y, shape, null, null, null, null, 'button'),
  2957. curState = 0,
  2958. stateOptions,
  2959. stateStyle,
  2960. normalStyle,
  2961. hoverStyle,
  2962. pressedStyle,
  2963. disabledStyle,
  2964. verticalGradient = { x1: 0, y1: 0, x2: 0, y2: 1 };
  2965. // Normal state - prepare the attributes
  2966. normalState = merge({
  2967. 'stroke-width': 1,
  2968. stroke: '#CCCCCC',
  2969. fill: {
  2970. linearGradient: verticalGradient,
  2971. stops: [
  2972. [0, '#FEFEFE'],
  2973. [1, '#F6F6F6']
  2974. ]
  2975. },
  2976. r: 2,
  2977. padding: 5,
  2978. style: {
  2979. color: 'black'
  2980. }
  2981. }, normalState);
  2982. normalStyle = normalState.style;
  2983. delete normalState.style;
  2984. // Hover state
  2985. hoverState = merge(normalState, {
  2986. stroke: '#68A',
  2987. fill: {
  2988. linearGradient: verticalGradient,
  2989. stops: [
  2990. [0, '#FFF'],
  2991. [1, '#ACF']
  2992. ]
  2993. }
  2994. }, hoverState);
  2995. hoverStyle = hoverState.style;
  2996. delete hoverState.style;
  2997. // Pressed state
  2998. pressedState = merge(normalState, {
  2999. stroke: '#68A',
  3000. fill: {
  3001. linearGradient: verticalGradient,
  3002. stops: [
  3003. [0, '#9BD'],
  3004. [1, '#CDF']
  3005. ]
  3006. }
  3007. }, pressedState);
  3008. pressedStyle = pressedState.style;
  3009. delete pressedState.style;
  3010. // Disabled state
  3011. disabledState = merge(normalState, {
  3012. style: {
  3013. color: '#CCC'
  3014. }
  3015. }, disabledState);
  3016. disabledStyle = disabledState.style;
  3017. delete disabledState.style;
  3018. // Add the events. IE9 and IE10 need mouseover and mouseout to funciton (#667).
  3019. addEvent(label.element, isIE ? 'mouseover' : 'mouseenter', function () {
  3020. if (curState !== 3) {
  3021. label.attr(hoverState)
  3022. .css(hoverStyle);
  3023. }
  3024. });
  3025. addEvent(label.element, isIE ? 'mouseout' : 'mouseleave', function () {
  3026. if (curState !== 3) {
  3027. stateOptions = [normalState, hoverState, pressedState][curState];
  3028. stateStyle = [normalStyle, hoverStyle, pressedStyle][curState];
  3029. label.attr(stateOptions)
  3030. .css(stateStyle);
  3031. }
  3032. });
  3033. label.setState = function (state) {
  3034. label.state = curState = state;
  3035. if (!state) {
  3036. label.attr(normalState)
  3037. .css(normalStyle);
  3038. } else if (state === 2) {
  3039. label.attr(pressedState)
  3040. .css(pressedStyle);
  3041. } else if (state === 3) {
  3042. label.attr(disabledState)
  3043. .css(disabledStyle);
  3044. }
  3045. };
  3046. return label
  3047. .on('click', function () {
  3048. if (curState !== 3) {
  3049. callback.call(label);
  3050. }
  3051. })
  3052. .attr(normalState)
  3053. .css(extend({ cursor: 'default' }, normalStyle));
  3054. },
  3055. /**
  3056. * Make a straight line crisper by not spilling out to neighbour pixels
  3057. * @param {Array} points
  3058. * @param {Number} width
  3059. */
  3060. crispLine: function (points, width) {
  3061. // points format: [M, 0, 0, L, 100, 0]
  3062. // normalize to a crisp line
  3063. if (points[1] === points[4]) {
  3064. // Substract due to #1129. Now bottom and left axis gridlines behave the same.
  3065. points[1] = points[4] = mathRound(points[1]) - (width % 2 / 2);
  3066. }
  3067. if (points[2] === points[5]) {
  3068. points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2);
  3069. }
  3070. return points;
  3071. },
  3072. /**
  3073. * Draw a path
  3074. * @param {Array} path An SVG path in array form
  3075. */
  3076. path: function (path) {
  3077. var attr = {
  3078. fill: NONE
  3079. };
  3080. if (isArray(path)) {
  3081. attr.d = path;
  3082. } else if (isObject(path)) { // attributes
  3083. extend(attr, path);
  3084. }
  3085. return this.createElement('path').attr(attr);
  3086. },
  3087. /**
  3088. * Draw and return an SVG circle
  3089. * @param {Number} x The x position
  3090. * @param {Number} y The y position
  3091. * @param {Number} r The radius
  3092. */
  3093. circle: function (x, y, r) {
  3094. var attr = isObject(x) ?
  3095. x :
  3096. {
  3097. x: x,
  3098. y: y,
  3099. r: r
  3100. },
  3101. wrapper = this.createElement('circle');
  3102. wrapper.xSetter = function (value) {
  3103. this.element.setAttribute('cx', value);
  3104. };
  3105. wrapper.ySetter = function (value) {
  3106. this.element.setAttribute('cy', value);
  3107. };
  3108. return wrapper.attr(attr);
  3109. },
  3110. /**
  3111. * Draw and return an arc
  3112. * @param {Number} x X position
  3113. * @param {Number} y Y position
  3114. * @param {Number} r Radius
  3115. * @param {Number} innerR Inner radius like used in donut charts
  3116. * @param {Number} start Starting angle
  3117. * @param {Number} end Ending angle
  3118. */
  3119. arc: function (x, y, r, innerR, start, end) {
  3120. var arc;
  3121. if (isObject(x)) {
  3122. y = x.y;
  3123. r = x.r;
  3124. innerR = x.innerR;
  3125. start = x.start;
  3126. end = x.end;
  3127. x = x.x;
  3128. }
  3129. // Arcs are defined as symbols for the ability to set
  3130. // attributes in attr and animate
  3131. arc = this.symbol('arc', x || 0, y || 0, r || 0, r || 0, {
  3132. innerR: innerR || 0,
  3133. start: start || 0,
  3134. end: end || 0
  3135. });
  3136. arc.r = r; // #959
  3137. return arc;
  3138. },
  3139. /**
  3140. * Draw and return a rectangle
  3141. * @param {Number} x Left position
  3142. * @param {Number} y Top position
  3143. * @param {Number} width
  3144. * @param {Number} height
  3145. * @param {Number} r Border corner radius
  3146. * @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing
  3147. */
  3148. rect: function (x, y, width, height, r, strokeWidth) {
  3149. r = isObject(x) ? x.r : r;
  3150. var wrapper = this.createElement('rect'),
  3151. attribs = isObject(x) ? x : x === UNDEFINED ? {} : {
  3152. x: x,
  3153. y: y,
  3154. width: mathMax(width, 0),
  3155. height: mathMax(height, 0)
  3156. };
  3157. if (strokeWidth !== UNDEFINED) {
  3158. attribs.strokeWidth = strokeWidth;
  3159. attribs = wrapper.crisp(attribs);
  3160. }
  3161. if (r) {
  3162. attribs.r = r;
  3163. }
  3164. wrapper.rSetter = function (value) {
  3165. attr(this.element, {
  3166. rx: value,
  3167. ry: value
  3168. });
  3169. };
  3170. return wrapper.attr(attribs);
  3171. },
  3172. /**
  3173. * Resize the box and re-align all aligned elements
  3174. * @param {Object} width
  3175. * @param {Object} height
  3176. * @param {Boolean} animate
  3177. *
  3178. */
  3179. setSize: function (width, height, animate) {
  3180. var renderer = this,
  3181. alignedObjects = renderer.alignedObjects,
  3182. i = alignedObjects.length;
  3183. renderer.width = width;
  3184. renderer.height = height;
  3185. renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({
  3186. width: width,
  3187. height: height
  3188. });
  3189. while (i--) {
  3190. alignedObjects[i].align();
  3191. }
  3192. },
  3193. /**
  3194. * Create a group
  3195. * @param {String} name The group will be given a class name of 'highcharts-{name}'.
  3196. * This can be used for styling and scripting.
  3197. */
  3198. g: function (name) {
  3199. var elem = this.createElement('g');
  3200. return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem;
  3201. },
  3202. /**
  3203. * Display an image
  3204. * @param {String} src
  3205. * @param {Number} x
  3206. * @param {Number} y
  3207. * @param {Number} width
  3208. * @param {Number} height
  3209. */
  3210. image: function (src, x, y, width, height) {
  3211. var attribs = {
  3212. preserveAspectRatio: NONE
  3213. },
  3214. elemWrapper;
  3215. // optional properties
  3216. if (arguments.length > 1) {
  3217. extend(attribs, {
  3218. x: x,
  3219. y: y,
  3220. width: width,
  3221. height: height
  3222. });
  3223. }
  3224. elemWrapper = this.createElement('image').attr(attribs);
  3225. // set the href in the xlink namespace
  3226. if (elemWrapper.element.setAttributeNS) {
  3227. elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink',
  3228. 'href', src);
  3229. } else {
  3230. // could be exporting in IE
  3231. // using href throws "not supported" in ie7 and under, requries regex shim to fix later
  3232. elemWrapper.element.setAttribute('hc-svg-href', src);
  3233. }
  3234. return elemWrapper;
  3235. },
  3236. /**
  3237. * Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object.
  3238. *
  3239. * @param {Object} symbol
  3240. * @param {Object} x
  3241. * @param {Object} y
  3242. * @param {Object} radius
  3243. * @param {Object} options
  3244. */
  3245. symbol: function (symbol, x, y, width, height, options) {
  3246. var obj,
  3247. // get the symbol definition function
  3248. symbolFn = this.symbols[symbol],
  3249. // check if there's a path defined for this symbol
  3250. path = symbolFn && symbolFn(
  3251. mathRound(x),
  3252. mathRound(y),
  3253. width,
  3254. height,
  3255. options
  3256. ),
  3257. imageElement,
  3258. imageRegex = /^url\((.*?)\)$/,
  3259. imageSrc,
  3260. imageSize,
  3261. centerImage;
  3262. if (path) {
  3263. obj = this.path(path);
  3264. // expando properties for use in animate and attr
  3265. extend(obj, {
  3266. symbolName: symbol,
  3267. x: x,
  3268. y: y,
  3269. width: width,
  3270. height: height
  3271. });
  3272. if (options) {
  3273. extend(obj, options);
  3274. }
  3275. // image symbols
  3276. } else if (imageRegex.test(symbol)) {
  3277. // On image load, set the size and position
  3278. centerImage = function (img, size) {
  3279. if (img.element) { // it may be destroyed in the meantime (#1390)
  3280. img.attr({
  3281. width: size[0],
  3282. height: size[1]
  3283. });
  3284. if (!img.alignByTranslate) { // #185
  3285. img.translate(
  3286. mathRound((width - size[0]) / 2), // #1378
  3287. mathRound((height - size[1]) / 2)
  3288. );
  3289. }
  3290. }
  3291. };
  3292. imageSrc = symbol.match(imageRegex)[1];
  3293. imageSize = symbolSizes[imageSrc] || (options && options.width && options.height && [options.width, options.height]);
  3294. // Ireate the image synchronously, add attribs async
  3295. obj = this.image(imageSrc)
  3296. .attr({
  3297. x: x,
  3298. y: y
  3299. });
  3300. obj.isImg = true;
  3301. if (imageSize) {
  3302. centerImage(obj, imageSize);
  3303. } else {
  3304. // Initialize image to be 0 size so export will still function if there's no cached sizes.
  3305. obj.attr({ width: 0, height: 0 });
  3306. // Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8,
  3307. // the created element must be assigned to a variable in order to load (#292).
  3308. imageElement = createElement('img', {
  3309. onload: function () {
  3310. centerImage(obj, symbolSizes[imageSrc] = [this.width, this.height]);
  3311. },
  3312. src: imageSrc
  3313. });
  3314. }
  3315. }
  3316. return obj;
  3317. },
  3318. /**
  3319. * An extendable collection of functions for defining symbol paths.
  3320. */
  3321. symbols: {
  3322. 'circle': function (x, y, w, h) {
  3323. var cpw = 0.166 * w;
  3324. return [
  3325. M, x + w / 2, y,
  3326. 'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h,
  3327. 'C', x - cpw, y + h, x - cpw, y, x + w / 2, y,
  3328. 'Z'
  3329. ];
  3330. },
  3331. 'square': function (x, y, w, h) {
  3332. return [
  3333. M, x, y,
  3334. L, x + w, y,
  3335. x + w, y + h,
  3336. x, y + h,
  3337. 'Z'
  3338. ];
  3339. },
  3340. 'triangle': function (x, y, w, h) {
  3341. return [
  3342. M, x + w / 2, y,
  3343. L, x + w, y + h,
  3344. x, y + h,
  3345. 'Z'
  3346. ];
  3347. },
  3348. 'triangle-down': function (x, y, w, h) {
  3349. return [
  3350. M, x, y,
  3351. L, x + w, y,
  3352. x + w / 2, y + h,
  3353. 'Z'
  3354. ];
  3355. },
  3356. 'diamond': function (x, y, w, h) {
  3357. return [
  3358. M, x + w / 2, y,
  3359. L, x + w, y + h / 2,
  3360. x + w / 2, y + h,
  3361. x, y + h / 2,
  3362. 'Z'
  3363. ];
  3364. },
  3365. 'arc': function (x, y, w, h, options) {
  3366. var start = options.start,
  3367. radius = options.r || w || h,
  3368. end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561)
  3369. innerRadius = options.innerR,
  3370. open = options.open,
  3371. cosStart = mathCos(start),
  3372. sinStart = mathSin(start),
  3373. cosEnd = mathCos(end),
  3374. sinEnd = mathSin(end),
  3375. longArc = options.end - start < mathPI ? 0 : 1;
  3376. return [
  3377. M,
  3378. x + radius * cosStart,
  3379. y + radius * sinStart,
  3380. 'A', // arcTo
  3381. radius, // x radius
  3382. radius, // y radius
  3383. 0, // slanting
  3384. longArc, // long or short arc
  3385. 1, // clockwise
  3386. x + radius * cosEnd,
  3387. y + radius * sinEnd,
  3388. open ? M : L,
  3389. x + innerRadius * cosEnd,
  3390. y + innerRadius * sinEnd,
  3391. 'A', // arcTo
  3392. innerRadius, // x radius
  3393. innerRadius, // y radius
  3394. 0, // slanting
  3395. longArc, // long or short arc
  3396. 0, // clockwise
  3397. x + innerRadius * cosStart,
  3398. y + innerRadius * sinStart,
  3399. open ? '' : 'Z' // close
  3400. ];
  3401. },
  3402. /**
  3403. * Callout shape used for default tooltips, also used for rounded rectangles in VML
  3404. */
  3405. callout: function (x, y, w, h, options) {
  3406. var arrowLength = 6,
  3407. halfDistance = 6,
  3408. r = mathMin((options && options.r) || 0, w, h),
  3409. safeDistance = r + halfDistance,
  3410. anchorX = options && options.anchorX,
  3411. anchorY = options && options.anchorY,
  3412. path,
  3413. normalizer = mathRound(options.strokeWidth || 0) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors;
  3414. x += normalizer;
  3415. y += normalizer;
  3416. path = [
  3417. 'M', x + r, y,
  3418. 'L', x + w - r, y, // top side
  3419. 'C', x + w, y, x + w, y, x + w, y + r, // top-right corner
  3420. 'L', x + w, y + h - r, // right side
  3421. 'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-right corner
  3422. 'L', x + r, y + h, // bottom side
  3423. 'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner
  3424. 'L', x, y + r, // left side
  3425. 'C', x, y, x, y, x + r, y // top-right corner
  3426. ];
  3427. if (anchorX && anchorX > w && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace right side
  3428. path.splice(13, 3,
  3429. 'L', x + w, anchorY - halfDistance,
  3430. x + w + arrowLength, anchorY,
  3431. x + w, anchorY + halfDistance,
  3432. x + w, y + h - r
  3433. );
  3434. } else if (anchorX && anchorX < 0 && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace left side
  3435. path.splice(33, 3,
  3436. 'L', x, anchorY + halfDistance,
  3437. x - arrowLength, anchorY,
  3438. x, anchorY - halfDistance,
  3439. x, y + r
  3440. );
  3441. } else if (anchorY && anchorY > h && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace bottom
  3442. path.splice(23, 3,
  3443. 'L', anchorX + halfDistance, y + h,
  3444. anchorX, y + h + arrowLength,
  3445. anchorX - halfDistance, y + h,
  3446. x + r, y + h
  3447. );
  3448. } else if (anchorY && anchorY < 0 && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace top
  3449. path.splice(3, 3,
  3450. 'L', anchorX - halfDistance, y,
  3451. anchorX, y - arrowLength,
  3452. anchorX + halfDistance, y,
  3453. w - r, y
  3454. );
  3455. }
  3456. return path;
  3457. }
  3458. },
  3459. /**
  3460. * Define a clipping rectangle
  3461. * @param {String} id
  3462. * @param {Number} x
  3463. * @param {Number} y
  3464. * @param {Number} width
  3465. * @param {Number} height
  3466. */
  3467. clipRect: function (x, y, width, height) {
  3468. var wrapper,
  3469. id = PREFIX + idCounter++,
  3470. clipPath = this.createElement('clipPath').attr({
  3471. id: id
  3472. }).add(this.defs);
  3473. wrapper = this.rect(x, y, width, height, 0).add(clipPath);
  3474. wrapper.id = id;
  3475. wrapper.clipPath = clipPath;
  3476. wrapper.count = 0;
  3477. return wrapper;
  3478. },
  3479. /**
  3480. * Add text to the SVG object
  3481. * @param {String} str
  3482. * @param {Number} x Left position
  3483. * @param {Number} y Top position
  3484. * @param {Boolean} useHTML Use HTML to render the text
  3485. */
  3486. text: function (str, x, y, useHTML) {
  3487. // declare variables
  3488. var renderer = this,
  3489. fakeSVG = useCanVG || (!hasSVG && renderer.forExport),
  3490. wrapper,
  3491. attr = {};
  3492. if (useHTML && !renderer.forExport) {
  3493. return renderer.html(str, x, y);
  3494. }
  3495. attr.x = Math.round(x || 0); // X is always needed for line-wrap logic
  3496. if (y) {
  3497. attr.y = Math.round(y);
  3498. }
  3499. if (str || str === 0) {
  3500. attr.text = str;
  3501. }
  3502. wrapper = renderer.createElement('text')
  3503. .attr(attr);
  3504. // Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063)
  3505. if (fakeSVG) {
  3506. wrapper.css({
  3507. position: ABSOLUTE
  3508. });
  3509. }
  3510. if (!useHTML) {
  3511. wrapper.xSetter = function (value, key, element) {
  3512. var tspans = element.getElementsByTagName('tspan'),
  3513. tspan,
  3514. parentVal = element.getAttribute(key),
  3515. i;
  3516. for (i = 0; i < tspans.length; i++) {
  3517. tspan = tspans[i];
  3518. // If the x values are equal, the tspan represents a linebreak
  3519. if (tspan.getAttribute(key) === parentVal) {
  3520. tspan.setAttribute(key, value);
  3521. }
  3522. }
  3523. element.setAttribute(key, value);
  3524. };
  3525. }
  3526. return wrapper;
  3527. },
  3528. /**
  3529. * Utility to return the baseline offset and total line height from the font size
  3530. */
  3531. fontMetrics: function (fontSize, elem) {
  3532. fontSize = fontSize || this.style.fontSize;
  3533. if (elem && win.getComputedStyle) {
  3534. elem = elem.element || elem; // SVGElement
  3535. fontSize = win.getComputedStyle(elem, "").fontSize;
  3536. }
  3537. fontSize = /px/.test(fontSize) ? pInt(fontSize) : /em/.test(fontSize) ? parseFloat(fontSize) * 12 : 12;
  3538. // Empirical values found by comparing font size and bounding box height.
  3539. // Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/
  3540. var lineHeight = fontSize < 24 ? fontSize + 3 : mathRound(fontSize * 1.2),
  3541. baseline = mathRound(lineHeight * 0.8);
  3542. return {
  3543. h: lineHeight,
  3544. b: baseline,
  3545. f: fontSize
  3546. };
  3547. },
  3548. /**
  3549. * Correct X and Y positioning of a label for rotation (#1764)
  3550. */
  3551. rotCorr: function (baseline, rotation, alterY) {
  3552. var y = baseline;
  3553. if (rotation && alterY) {
  3554. y = mathMax(y * mathCos(rotation * deg2rad), 4);
  3555. }
  3556. return {
  3557. x: (-baseline / 3) * mathSin(rotation * deg2rad),
  3558. y: y
  3559. };
  3560. },
  3561. /**
  3562. * Add a label, a text item that can hold a colored or gradient background
  3563. * as well as a border and shadow.
  3564. * @param {string} str
  3565. * @param {Number} x
  3566. * @param {Number} y
  3567. * @param {String} shape
  3568. * @param {Number} anchorX In case the shape has a pointer, like a flag, this is the
  3569. * coordinates it should be pinned to
  3570. * @param {Number} anchorY
  3571. * @param {Boolean} baseline Whether to position the label relative to the text baseline,
  3572. * like renderer.text, or to the upper border of the rectangle.
  3573. * @param {String} className Class name for the group
  3574. */
  3575. label: function (str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) {
  3576. var renderer = this,
  3577. wrapper = renderer.g(className),
  3578. text = renderer.text('', 0, 0, useHTML)
  3579. .attr({
  3580. zIndex: 1
  3581. }),
  3582. //.add(wrapper),
  3583. box,
  3584. bBox,
  3585. alignFactor = 0,
  3586. padding = 3,
  3587. paddingLeft = 0,
  3588. width,
  3589. height,
  3590. wrapperX,
  3591. wrapperY,
  3592. crispAdjust = 0,
  3593. deferredAttr = {},
  3594. baselineOffset,
  3595. needsBox;
  3596. /**
  3597. * This function runs after the label is added to the DOM (when the bounding box is
  3598. * available), and after the text of the label is updated to detect the new bounding
  3599. * box and reflect it in the border box.
  3600. */
  3601. function updateBoxSize() {
  3602. var boxX,
  3603. boxY,
  3604. style = text.element.style;
  3605. bBox = (width === undefined || height === undefined || wrapper.styles.textAlign) && defined(text.textStr) &&
  3606. text.getBBox(); //#3295 && 3514 box failure when string equals 0
  3607. wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft;
  3608. wrapper.height = (height || bBox.height || 0) + 2 * padding;
  3609. // update the label-scoped y offset
  3610. baselineOffset = padding + renderer.fontMetrics(style && style.fontSize, text).b;
  3611. if (needsBox) {
  3612. // create the border box if it is not already present
  3613. if (!box) {
  3614. boxX = mathRound(-alignFactor * padding);
  3615. boxY = baseline ? -baselineOffset : 0;
  3616. wrapper.box = box = shape ?
  3617. renderer.symbol(shape, boxX, boxY, wrapper.width, wrapper.height, deferredAttr) :
  3618. renderer.rect(boxX, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]);
  3619. box.attr('fill', NONE).add(wrapper);
  3620. }
  3621. // apply the box attributes
  3622. if (!box.isImg) { // #1630
  3623. box.attr(extend({
  3624. width: mathRound(wrapper.width),
  3625. height: mathRound(wrapper.height)
  3626. }, deferredAttr));
  3627. }
  3628. deferredAttr = null;
  3629. }
  3630. }
  3631. /**
  3632. * This function runs after setting text or padding, but only if padding is changed
  3633. */
  3634. function updateTextPadding() {
  3635. var styles = wrapper.styles,
  3636. textAlign = styles && styles.textAlign,
  3637. x = paddingLeft + padding * (1 - alignFactor),
  3638. y;
  3639. // determin y based on the baseline
  3640. y = baseline ? 0 : baselineOffset;
  3641. // compensate for alignment
  3642. if (defined(width) && bBox && (textAlign === 'center' || textAlign === 'right')) {
  3643. x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width);
  3644. }
  3645. // update if anything changed
  3646. if (x !== text.x || y !== text.y) {
  3647. text.attr('x', x);
  3648. if (y !== UNDEFINED) {
  3649. // As a workaround for #3649, use translation instead of y attribute. #3649
  3650. // is a rendering bug in WebKit for Retina (Mac, iOS, PhantomJS) that
  3651. // results in duplicated text when an y attribute is used in combination
  3652. // with a CSS text-style.
  3653. text.attr(text.element.nodeName === 'SPAN' ? 'y' : 'translateY', y);
  3654. }
  3655. }
  3656. // record current values
  3657. text.x = x;
  3658. text.y = y;
  3659. }
  3660. /**
  3661. * Set a box attribute, or defer it if the box is not yet created
  3662. * @param {Object} key
  3663. * @param {Object} value
  3664. */
  3665. function boxAttr(key, value) {
  3666. if (box) {
  3667. box.attr(key, value);
  3668. } else {
  3669. deferredAttr[key] = value;
  3670. }
  3671. }
  3672. /**
  3673. * After the text element is added, get the desired size of the border box
  3674. * and add it before the text in the DOM.
  3675. */
  3676. wrapper.onAdd = function () {
  3677. text.add(wrapper);
  3678. wrapper.attr({
  3679. text: (str || str === 0) ? str : '', // alignment is available now // #3295: 0 not rendered if given as a value
  3680. x: x,
  3681. y: y
  3682. });
  3683. if (box && defined(anchorX)) {
  3684. wrapper.attr({
  3685. anchorX: anchorX,
  3686. anchorY: anchorY
  3687. });
  3688. }
  3689. };
  3690. /*
  3691. * Add specific attribute setters.
  3692. */
  3693. // only change local variables
  3694. wrapper.widthSetter = function (value) {
  3695. width = value;
  3696. };
  3697. wrapper.heightSetter = function (value) {
  3698. height = value;
  3699. };
  3700. wrapper.paddingSetter = function (value) {
  3701. if (defined(value) && value !== padding) {
  3702. padding = wrapper.padding = value;
  3703. updateTextPadding();
  3704. }
  3705. };
  3706. wrapper.paddingLeftSetter = function (value) {
  3707. if (defined(value) && value !== paddingLeft) {
  3708. paddingLeft = value;
  3709. updateTextPadding();
  3710. }
  3711. };
  3712. // change local variable and prevent setting attribute on the group
  3713. wrapper.alignSetter = function (value) {
  3714. alignFactor = { left: 0, center: 0.5, right: 1 }[value];
  3715. };
  3716. // apply these to the box and the text alike
  3717. wrapper.textSetter = function (value) {
  3718. if (value !== UNDEFINED) {
  3719. text.textSetter(value);
  3720. }
  3721. updateBoxSize();
  3722. updateTextPadding();
  3723. };
  3724. // apply these to the box but not to the text
  3725. wrapper['stroke-widthSetter'] = function (value, key) {
  3726. if (value) {
  3727. needsBox = true;
  3728. }
  3729. crispAdjust = value % 2 / 2;
  3730. boxAttr(key, value);
  3731. };
  3732. wrapper.strokeSetter = wrapper.fillSetter = wrapper.rSetter = function (value, key) {
  3733. if (key === 'fill' && value) {
  3734. needsBox = true;
  3735. }
  3736. boxAttr(key, value);
  3737. };
  3738. wrapper.anchorXSetter = function (value, key) {
  3739. anchorX = value;
  3740. boxAttr(key, value + crispAdjust - wrapperX);
  3741. };
  3742. wrapper.anchorYSetter = function (value, key) {
  3743. anchorY = value;
  3744. boxAttr(key, value - wrapperY);
  3745. };
  3746. // rename attributes
  3747. wrapper.xSetter = function (value) {
  3748. wrapper.x = value; // for animation getter
  3749. if (alignFactor) {
  3750. value -= alignFactor * ((width || bBox.width) + padding);
  3751. }
  3752. wrapperX = mathRound(value);
  3753. wrapper.attr('translateX', wrapperX);
  3754. };
  3755. wrapper.ySetter = function (value) {
  3756. wrapperY = wrapper.y = mathRound(value);
  3757. wrapper.attr('translateY', wrapperY);
  3758. };
  3759. // Redirect certain methods to either the box or the text
  3760. var baseCss = wrapper.css;
  3761. return extend(wrapper, {
  3762. /**
  3763. * Pick up some properties and apply them to the text instead of the wrapper
  3764. */
  3765. css: function (styles) {
  3766. if (styles) {
  3767. var textStyles = {};
  3768. styles = merge(styles); // create a copy to avoid altering the original object (#537)
  3769. each(wrapper.textProps, function (prop) {
  3770. if (styles[prop] !== UNDEFINED) {
  3771. textStyles[prop] = styles[prop];
  3772. delete styles[prop];
  3773. }
  3774. });
  3775. text.css(textStyles);
  3776. }
  3777. return baseCss.call(wrapper, styles);
  3778. },
  3779. /**
  3780. * Return the bounding box of the box, not the group
  3781. */
  3782. getBBox: function () {
  3783. return {
  3784. width: bBox.width + 2 * padding,
  3785. height: bBox.height + 2 * padding,
  3786. x: bBox.x - padding,
  3787. y: bBox.y - padding
  3788. };
  3789. },
  3790. /**
  3791. * Apply the shadow to the box
  3792. */
  3793. shadow: function (b) {
  3794. if (box) {
  3795. box.shadow(b);
  3796. }
  3797. return wrapper;
  3798. },
  3799. /**
  3800. * Destroy and release memory.
  3801. */
  3802. destroy: function () {
  3803. // Added by button implementation
  3804. removeEvent(wrapper.element, 'mouseenter');
  3805. removeEvent(wrapper.element, 'mouseleave');
  3806. if (text) {
  3807. text = text.destroy();
  3808. }
  3809. if (box) {
  3810. box = box.destroy();
  3811. }
  3812. // Call base implementation to destroy the rest
  3813. SVGElement.prototype.destroy.call(wrapper);
  3814. // Release local pointers (#1298)
  3815. wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = null;
  3816. }
  3817. });
  3818. }
  3819. }; // end SVGRenderer
  3820. // general renderer
  3821. Renderer = SVGRenderer;
  3822. // extend SvgElement for useHTML option
  3823. extend(SVGElement.prototype, {
  3824. /**
  3825. * Apply CSS to HTML elements. This is used in text within SVG rendering and
  3826. * by the VML renderer
  3827. */
  3828. htmlCss: function (styles) {
  3829. var wrapper = this,
  3830. element = wrapper.element,
  3831. textWidth = styles && element.tagName === 'SPAN' && styles.width;
  3832. if (textWidth) {
  3833. delete styles.width;
  3834. wrapper.textWidth = textWidth;
  3835. wrapper.updateTransform();
  3836. }
  3837. if (styles && styles.textOverflow === 'ellipsis') {
  3838. styles.whiteSpace = 'nowrap';
  3839. styles.overflow = 'hidden';
  3840. }
  3841. wrapper.styles = extend(wrapper.styles, styles);
  3842. css(wrapper.element, styles);
  3843. return wrapper;
  3844. },
  3845. /**
  3846. * VML and useHTML method for calculating the bounding box based on offsets
  3847. * @param {Boolean} refresh Whether to force a fresh value from the DOM or to
  3848. * use the cached value
  3849. *
  3850. * @return {Object} A hash containing values for x, y, width and height
  3851. */
  3852. htmlGetBBox: function () {
  3853. var wrapper = this,
  3854. element = wrapper.element;
  3855. // faking getBBox in exported SVG in legacy IE
  3856. // faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?)
  3857. if (element.nodeName === 'text') {
  3858. element.style.position = ABSOLUTE;
  3859. }
  3860. return {
  3861. x: element.offsetLeft,
  3862. y: element.offsetTop,
  3863. width: element.offsetWidth,
  3864. height: element.offsetHeight
  3865. };
  3866. },
  3867. /**
  3868. * VML override private method to update elements based on internal
  3869. * properties based on SVG transform
  3870. */
  3871. htmlUpdateTransform: function () {
  3872. // aligning non added elements is expensive
  3873. if (!this.added) {
  3874. this.alignOnAdd = true;
  3875. return;
  3876. }
  3877. var wrapper = this,
  3878. renderer = wrapper.renderer,
  3879. elem = wrapper.element,
  3880. translateX = wrapper.translateX || 0,
  3881. translateY = wrapper.translateY || 0,
  3882. x = wrapper.x || 0,
  3883. y = wrapper.y || 0,
  3884. align = wrapper.textAlign || 'left',
  3885. alignCorrection = { left: 0, center: 0.5, right: 1 }[align],
  3886. shadows = wrapper.shadows,
  3887. styles = wrapper.styles;
  3888. // apply translate
  3889. css(elem, {
  3890. marginLeft: translateX,
  3891. marginTop: translateY
  3892. });
  3893. if (shadows) { // used in labels/tooltip
  3894. each(shadows, function (shadow) {
  3895. css(shadow, {
  3896. marginLeft: translateX + 1,
  3897. marginTop: translateY + 1
  3898. });
  3899. });
  3900. }
  3901. // apply inversion
  3902. if (wrapper.inverted) { // wrapper is a group
  3903. each(elem.childNodes, function (child) {
  3904. renderer.invertChild(child, elem);
  3905. });
  3906. }
  3907. if (elem.tagName === 'SPAN') {
  3908. var width,
  3909. rotation = wrapper.rotation,
  3910. baseline,
  3911. textWidth = pInt(wrapper.textWidth),
  3912. currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth].join(',');
  3913. if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed
  3914. baseline = renderer.fontMetrics(elem.style.fontSize).b;
  3915. // Renderer specific handling of span rotation
  3916. if (defined(rotation)) {
  3917. wrapper.setSpanRotation(rotation, alignCorrection, baseline);
  3918. }
  3919. width = pick(wrapper.elemWidth, elem.offsetWidth);
  3920. // Update textWidth
  3921. if (width > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254
  3922. css(elem, {
  3923. width: textWidth + PX,
  3924. display: 'block',
  3925. whiteSpace: (styles && styles.whiteSpace) || 'normal' // #3331
  3926. });
  3927. width = textWidth;
  3928. }
  3929. wrapper.getSpanCorrection(width, baseline, alignCorrection, rotation, align);
  3930. }
  3931. // apply position with correction
  3932. css(elem, {
  3933. left: (x + (wrapper.xCorr || 0)) + PX,
  3934. top: (y + (wrapper.yCorr || 0)) + PX
  3935. });
  3936. // force reflow in webkit to apply the left and top on useHTML element (#1249)
  3937. if (isWebKit) {
  3938. baseline = elem.offsetHeight; // assigned to baseline for JSLint purpose
  3939. }
  3940. // record current text transform
  3941. wrapper.cTT = currentTextTransform;
  3942. }
  3943. },
  3944. /**
  3945. * Set the rotation of an individual HTML span
  3946. */
  3947. setSpanRotation: function (rotation, alignCorrection, baseline) {
  3948. var rotationStyle = {},
  3949. cssTransformKey = isIE ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : '';
  3950. rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)';
  3951. rotationStyle[cssTransformKey + (isFirefox ? 'Origin' : '-origin')] = rotationStyle.transformOrigin = (alignCorrection * 100) + '% ' + baseline + 'px';
  3952. css(this.element, rotationStyle);
  3953. },
  3954. /**
  3955. * Get the correction in X and Y positioning as the element is rotated.
  3956. */
  3957. getSpanCorrection: function (width, baseline, alignCorrection) {
  3958. this.xCorr = -width * alignCorrection;
  3959. this.yCorr = -baseline;
  3960. }
  3961. });
  3962. // Extend SvgRenderer for useHTML option.
  3963. extend(SVGRenderer.prototype, {
  3964. /**
  3965. * Create HTML text node. This is used by the VML renderer as well as the SVG
  3966. * renderer through the useHTML option.
  3967. *
  3968. * @param {String} str
  3969. * @param {Number} x
  3970. * @param {Number} y
  3971. */
  3972. html: function (str, x, y) {
  3973. var wrapper = this.createElement('span'),
  3974. element = wrapper.element,
  3975. renderer = wrapper.renderer;
  3976. // Text setter
  3977. wrapper.textSetter = function (value) {
  3978. if (value !== element.innerHTML) {
  3979. delete this.bBox;
  3980. }
  3981. element.innerHTML = this.textStr = value;
  3982. };
  3983. // Various setters which rely on update transform
  3984. wrapper.xSetter = wrapper.ySetter = wrapper.alignSetter = wrapper.rotationSetter = function (value, key) {
  3985. if (key === 'align') {
  3986. key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML.
  3987. }
  3988. wrapper[key] = value;
  3989. wrapper.htmlUpdateTransform();
  3990. };
  3991. // Set the default attributes
  3992. wrapper.attr({
  3993. text: str,
  3994. x: mathRound(x),
  3995. y: mathRound(y)
  3996. })
  3997. .css({
  3998. position: ABSOLUTE,
  3999. fontFamily: this.style.fontFamily,
  4000. fontSize: this.style.fontSize
  4001. });
  4002. // Keep the whiteSpace style outside the wrapper.styles collection
  4003. element.style.whiteSpace = 'nowrap';
  4004. // Use the HTML specific .css method
  4005. wrapper.css = wrapper.htmlCss;
  4006. // This is specific for HTML within SVG
  4007. if (renderer.isSVG) {
  4008. wrapper.add = function (svgGroupWrapper) {
  4009. var htmlGroup,
  4010. container = renderer.box.parentNode,
  4011. parentGroup,
  4012. parents = [];
  4013. this.parentGroup = svgGroupWrapper;
  4014. // Create a mock group to hold the HTML elements
  4015. if (svgGroupWrapper) {
  4016. htmlGroup = svgGroupWrapper.div;
  4017. if (!htmlGroup) {
  4018. // Read the parent chain into an array and read from top down
  4019. parentGroup = svgGroupWrapper;
  4020. while (parentGroup) {
  4021. parents.push(parentGroup);
  4022. // Move up to the next parent group
  4023. parentGroup = parentGroup.parentGroup;
  4024. }
  4025. // Ensure dynamically updating position when any parent is translated
  4026. each(parents.reverse(), function (parentGroup) {
  4027. var htmlGroupStyle;
  4028. // Create a HTML div and append it to the parent div to emulate
  4029. // the SVG group structure
  4030. htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, {
  4031. className: attr(parentGroup.element, 'class')
  4032. }, {
  4033. position: ABSOLUTE,
  4034. left: (parentGroup.translateX || 0) + PX,
  4035. top: (parentGroup.translateY || 0) + PX
  4036. }, htmlGroup || container); // the top group is appended to container
  4037. // Shortcut
  4038. htmlGroupStyle = htmlGroup.style;
  4039. // Set listeners to update the HTML div's position whenever the SVG group
  4040. // position is changed
  4041. extend(parentGroup, {
  4042. translateXSetter: function (value, key) {
  4043. htmlGroupStyle.left = value + PX;
  4044. parentGroup[key] = value;
  4045. parentGroup.doTransform = true;
  4046. },
  4047. translateYSetter: function (value, key) {
  4048. htmlGroupStyle.top = value + PX;
  4049. parentGroup[key] = value;
  4050. parentGroup.doTransform = true;
  4051. },
  4052. visibilitySetter: function (value, key) {
  4053. htmlGroupStyle[key] = value;
  4054. }
  4055. });
  4056. });
  4057. }
  4058. } else {
  4059. htmlGroup = container;
  4060. }
  4061. htmlGroup.appendChild(element);
  4062. // Shared with VML:
  4063. wrapper.added = true;
  4064. if (wrapper.alignOnAdd) {
  4065. wrapper.htmlUpdateTransform();
  4066. }
  4067. return wrapper;
  4068. };
  4069. }
  4070. return wrapper;
  4071. }
  4072. });
  4073. /* ****************************************************************************
  4074. * *
  4075. * START OF INTERNET EXPLORER <= 8 SPECIFIC CODE *
  4076. * *
  4077. * For applications and websites that don't need IE support, like platform *
  4078. * targeted mobile apps and web apps, this code can be removed. *
  4079. * *
  4080. *****************************************************************************/
  4081. /**
  4082. * @constructor
  4083. */
  4084. var VMLRenderer, VMLElement;
  4085. if (!hasSVG && !useCanVG) {
  4086. /**
  4087. * The VML element wrapper.
  4088. */
  4089. VMLElement = {
  4090. /**
  4091. * Initialize a new VML element wrapper. It builds the markup as a string
  4092. * to minimize DOM traffic.
  4093. * @param {Object} renderer
  4094. * @param {Object} nodeName
  4095. */
  4096. init: function (renderer, nodeName) {
  4097. var wrapper = this,
  4098. markup = ['<', nodeName, ' filled="f" stroked="f"'],
  4099. style = ['position: ', ABSOLUTE, ';'],
  4100. isDiv = nodeName === DIV;
  4101. // divs and shapes need size
  4102. if (nodeName === 'shape' || isDiv) {
  4103. style.push('left:0;top:0;width:1px;height:1px;');
  4104. }
  4105. style.push('visibility: ', isDiv ? HIDDEN : VISIBLE);
  4106. markup.push(' style="', style.join(''), '"/>');
  4107. // create element with default attributes and style
  4108. if (nodeName) {
  4109. markup = isDiv || nodeName === 'span' || nodeName === 'img' ?
  4110. markup.join('')
  4111. : renderer.prepVML(markup);
  4112. wrapper.element = createElement(markup);
  4113. }
  4114. wrapper.renderer = renderer;
  4115. },
  4116. /**
  4117. * Add the node to the given parent
  4118. * @param {Object} parent
  4119. */
  4120. add: function (parent) {
  4121. var wrapper = this,
  4122. renderer = wrapper.renderer,
  4123. element = wrapper.element,
  4124. box = renderer.box,
  4125. inverted = parent && parent.inverted,
  4126. // get the parent node
  4127. parentNode = parent ?
  4128. parent.element || parent :
  4129. box;
  4130. // if the parent group is inverted, apply inversion on all children
  4131. if (inverted) { // only on groups
  4132. renderer.invertChild(element, parentNode);
  4133. }
  4134. // append it
  4135. parentNode.appendChild(element);
  4136. // align text after adding to be able to read offset
  4137. wrapper.added = true;
  4138. if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) {
  4139. wrapper.updateTransform();
  4140. }
  4141. // fire an event for internal hooks
  4142. if (wrapper.onAdd) {
  4143. wrapper.onAdd();
  4144. }
  4145. return wrapper;
  4146. },
  4147. /**
  4148. * VML always uses htmlUpdateTransform
  4149. */
  4150. updateTransform: SVGElement.prototype.htmlUpdateTransform,
  4151. /**
  4152. * Set the rotation of a span with oldIE's filter
  4153. */
  4154. setSpanRotation: function () {
  4155. // Adjust for alignment and rotation. Rotation of useHTML content is not yet implemented
  4156. // but it can probably be implemented for Firefox 3.5+ on user request. FF3.5+
  4157. // has support for CSS3 transform. The getBBox method also needs to be updated
  4158. // to compensate for the rotation, like it currently does for SVG.
  4159. // Test case: http://jsfiddle.net/highcharts/Ybt44/
  4160. var rotation = this.rotation,
  4161. costheta = mathCos(rotation * deg2rad),
  4162. sintheta = mathSin(rotation * deg2rad);
  4163. css(this.element, {
  4164. filter: rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta,
  4165. ', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta,
  4166. ', sizingMethod=\'auto expand\')'].join('') : NONE
  4167. });
  4168. },
  4169. /**
  4170. * Get the positioning correction for the span after rotating.
  4171. */
  4172. getSpanCorrection: function (width, baseline, alignCorrection, rotation, align) {
  4173. var costheta = rotation ? mathCos(rotation * deg2rad) : 1,
  4174. sintheta = rotation ? mathSin(rotation * deg2rad) : 0,
  4175. height = pick(this.elemHeight, this.element.offsetHeight),
  4176. quad,
  4177. nonLeft = align && align !== 'left';
  4178. // correct x and y
  4179. this.xCorr = costheta < 0 && -width;
  4180. this.yCorr = sintheta < 0 && -height;
  4181. // correct for baseline and corners spilling out after rotation
  4182. quad = costheta * sintheta < 0;
  4183. this.xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection);
  4184. this.yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1);
  4185. // correct for the length/height of the text
  4186. if (nonLeft) {
  4187. this.xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1);
  4188. if (rotation) {
  4189. this.yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1);
  4190. }
  4191. css(this.element, {
  4192. textAlign: align
  4193. });
  4194. }
  4195. },
  4196. /**
  4197. * Converts a subset of an SVG path definition to its VML counterpart. Takes an array
  4198. * as the parameter and returns a string.
  4199. */
  4200. pathToVML: function (value) {
  4201. // convert paths
  4202. var i = value.length,
  4203. path = [];
  4204. while (i--) {
  4205. // Multiply by 10 to allow subpixel precision.
  4206. // Substracting half a pixel seems to make the coordinates
  4207. // align with SVG, but this hasn't been tested thoroughly
  4208. if (isNumber(value[i])) {
  4209. path[i] = mathRound(value[i] * 10) - 5;
  4210. } else if (value[i] === 'Z') { // close the path
  4211. path[i] = 'x';
  4212. } else {
  4213. path[i] = value[i];
  4214. // When the start X and end X coordinates of an arc are too close,
  4215. // they are rounded to the same value above. In this case, substract or
  4216. // add 1 from the end X and Y positions. #186, #760, #1371, #1410.
  4217. if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) {
  4218. // Start and end X
  4219. if (path[i + 5] === path[i + 7]) {
  4220. path[i + 7] += value[i + 7] > value[i + 5] ? 1 : -1;
  4221. }
  4222. // Start and end Y
  4223. if (path[i + 6] === path[i + 8]) {
  4224. path[i + 8] += value[i + 8] > value[i + 6] ? 1 : -1;
  4225. }
  4226. }
  4227. }
  4228. }
  4229. // Loop up again to handle path shortcuts (#2132)
  4230. /*while (i++ < path.length) {
  4231. if (path[i] === 'H') { // horizontal line to
  4232. path[i] = 'L';
  4233. path.splice(i + 2, 0, path[i - 1]);
  4234. } else if (path[i] === 'V') { // vertical line to
  4235. path[i] = 'L';
  4236. path.splice(i + 1, 0, path[i - 2]);
  4237. }
  4238. }*/
  4239. return path.join(' ') || 'x';
  4240. },
  4241. /**
  4242. * Set the element's clipping to a predefined rectangle
  4243. *
  4244. * @param {String} id The id of the clip rectangle
  4245. */
  4246. clip: function (clipRect) {
  4247. var wrapper = this,
  4248. clipMembers,
  4249. cssRet;
  4250. if (clipRect) {
  4251. clipMembers = clipRect.members;
  4252. erase(clipMembers, wrapper); // Ensure unique list of elements (#1258)
  4253. clipMembers.push(wrapper);
  4254. wrapper.destroyClip = function () {
  4255. erase(clipMembers, wrapper);
  4256. };
  4257. cssRet = clipRect.getCSS(wrapper);
  4258. } else {
  4259. if (wrapper.destroyClip) {
  4260. wrapper.destroyClip();
  4261. }
  4262. cssRet = { clip: docMode8 ? 'inherit' : 'rect(auto)' }; // #1214
  4263. }
  4264. return wrapper.css(cssRet);
  4265. },
  4266. /**
  4267. * Set styles for the element
  4268. * @param {Object} styles
  4269. */
  4270. css: SVGElement.prototype.htmlCss,
  4271. /**
  4272. * Removes a child either by removeChild or move to garbageBin.
  4273. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not.
  4274. */
  4275. safeRemoveChild: function (element) {
  4276. // discardElement will detach the node from its parent before attaching it
  4277. // to the garbage bin. Therefore it is important that the node is attached and have parent.
  4278. if (element.parentNode) {
  4279. discardElement(element);
  4280. }
  4281. },
  4282. /**
  4283. * Extend element.destroy by removing it from the clip members array
  4284. */
  4285. destroy: function () {
  4286. if (this.destroyClip) {
  4287. this.destroyClip();
  4288. }
  4289. return SVGElement.prototype.destroy.apply(this);
  4290. },
  4291. /**
  4292. * Add an event listener. VML override for normalizing event parameters.
  4293. * @param {String} eventType
  4294. * @param {Function} handler
  4295. */
  4296. on: function (eventType, handler) {
  4297. // simplest possible event model for internal use
  4298. this.element['on' + eventType] = function () {
  4299. var evt = win.event;
  4300. evt.target = evt.srcElement;
  4301. handler(evt);
  4302. };
  4303. return this;
  4304. },
  4305. /**
  4306. * In stacked columns, cut off the shadows so that they don't overlap
  4307. */
  4308. cutOffPath: function (path, length) {
  4309. var len;
  4310. path = path.split(/[ ,]/);
  4311. len = path.length;
  4312. if (len === 9 || len === 11) {
  4313. path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length;
  4314. }
  4315. return path.join(' ');
  4316. },
  4317. /**
  4318. * Apply a drop shadow by copying elements and giving them different strokes
  4319. * @param {Boolean|Object} shadowOptions
  4320. */
  4321. shadow: function (shadowOptions, group, cutOff) {
  4322. var shadows = [],
  4323. i,
  4324. element = this.element,
  4325. renderer = this.renderer,
  4326. shadow,
  4327. elemStyle = element.style,
  4328. markup,
  4329. path = element.path,
  4330. strokeWidth,
  4331. modifiedPath,
  4332. shadowWidth,
  4333. shadowElementOpacity;
  4334. // some times empty paths are not strings
  4335. if (path && typeof path.value !== 'string') {
  4336. path = 'x';
  4337. }
  4338. modifiedPath = path;
  4339. if (shadowOptions) {
  4340. shadowWidth = pick(shadowOptions.width, 3);
  4341. shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth;
  4342. for (i = 1; i <= 3; i++) {
  4343. strokeWidth = (shadowWidth * 2) + 1 - (2 * i);
  4344. // Cut off shadows for stacked column items
  4345. if (cutOff) {
  4346. modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5);
  4347. }
  4348. markup = ['<shape isShadow="true" strokeweight="', strokeWidth,
  4349. '" filled="false" path="', modifiedPath,
  4350. '" coordsize="10 10" style="', element.style.cssText, '" />'];
  4351. shadow = createElement(renderer.prepVML(markup),
  4352. null, {
  4353. left: pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1),
  4354. top: pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1)
  4355. }
  4356. );
  4357. if (cutOff) {
  4358. shadow.cutOff = strokeWidth + 1;
  4359. }
  4360. // apply the opacity
  4361. markup = ['<stroke color="', shadowOptions.color || 'black', '" opacity="', shadowElementOpacity * i, '"/>'];
  4362. createElement(renderer.prepVML(markup), null, null, shadow);
  4363. // insert it
  4364. if (group) {
  4365. group.element.appendChild(shadow);
  4366. } else {
  4367. element.parentNode.insertBefore(shadow, element);
  4368. }
  4369. // record it
  4370. shadows.push(shadow);
  4371. }
  4372. this.shadows = shadows;
  4373. }
  4374. return this;
  4375. },
  4376. updateShadows: noop, // Used in SVG only
  4377. setAttr: function (key, value) {
  4378. if (docMode8) { // IE8 setAttribute bug
  4379. this.element[key] = value;
  4380. } else {
  4381. this.element.setAttribute(key, value);
  4382. }
  4383. },
  4384. classSetter: function (value) {
  4385. // IE8 Standards mode has problems retrieving the className unless set like this
  4386. this.element.className = value;
  4387. },
  4388. dashstyleSetter: function (value, key, element) {
  4389. var strokeElem = element.getElementsByTagName('stroke')[0] ||
  4390. createElement(this.renderer.prepVML(['<stroke/>']), null, null, element);
  4391. strokeElem[key] = value || 'solid';
  4392. this[key] = value; /* because changing stroke-width will change the dash length
  4393. and cause an epileptic effect */
  4394. },
  4395. dSetter: function (value, key, element) {
  4396. var i,
  4397. shadows = this.shadows;
  4398. value = value || [];
  4399. this.d = value.join && value.join(' '); // used in getter for animation
  4400. element.path = value = this.pathToVML(value);
  4401. // update shadows
  4402. if (shadows) {
  4403. i = shadows.length;
  4404. while (i--) {
  4405. shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value;
  4406. }
  4407. }
  4408. this.setAttr(key, value);
  4409. },
  4410. fillSetter: function (value, key, element) {
  4411. var nodeName = element.nodeName;
  4412. if (nodeName === 'SPAN') { // text color
  4413. element.style.color = value;
  4414. } else if (nodeName !== 'IMG') { // #1336
  4415. element.filled = value !== NONE;
  4416. this.setAttr('fillcolor', this.renderer.color(value, element, key, this));
  4417. }
  4418. },
  4419. opacitySetter: noop, // Don't bother - animation is too slow and filters introduce artifacts
  4420. rotationSetter: function (value, key, element) {
  4421. var style = element.style;
  4422. this[key] = style[key] = value; // style is for #1873
  4423. // Correction for the 1x1 size of the shape container. Used in gauge needles.
  4424. style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX;
  4425. style.top = mathRound(mathCos(value * deg2rad)) + PX;
  4426. },
  4427. strokeSetter: function (value, key, element) {
  4428. this.setAttr('strokecolor', this.renderer.color(value, element, key));
  4429. },
  4430. 'stroke-widthSetter': function (value, key, element) {
  4431. element.stroked = !!value; // VML "stroked" attribute
  4432. this[key] = value; // used in getter, issue #113
  4433. if (isNumber(value)) {
  4434. value += PX;
  4435. }
  4436. this.setAttr('strokeweight', value);
  4437. },
  4438. titleSetter: function (value, key) {
  4439. this.setAttr(key, value);
  4440. },
  4441. visibilitySetter: function (value, key, element) {
  4442. // Handle inherited visibility
  4443. if (value === 'inherit') {
  4444. value = VISIBLE;
  4445. }
  4446. // Let the shadow follow the main element
  4447. if (this.shadows) {
  4448. each(this.shadows, function (shadow) {
  4449. shadow.style[key] = value;
  4450. });
  4451. }
  4452. // Instead of toggling the visibility CSS property, move the div out of the viewport.
  4453. // This works around #61 and #586
  4454. if (element.nodeName === 'DIV') {
  4455. value = value === HIDDEN ? '-999em' : 0;
  4456. // In order to redraw, IE7 needs the div to be visible when tucked away
  4457. // outside the viewport. So the visibility is actually opposite of
  4458. // the expected value. This applies to the tooltip only.
  4459. if (!docMode8) {
  4460. element.style[key] = value ? VISIBLE : HIDDEN;
  4461. }
  4462. key = 'top';
  4463. }
  4464. element.style[key] = value;
  4465. },
  4466. xSetter: function (value, key, element) {
  4467. this[key] = value; // used in getter
  4468. if (key === 'x') {
  4469. key = 'left';
  4470. } else if (key === 'y') {
  4471. key = 'top';
  4472. }/* else {
  4473. value = mathMax(0, value); // don't set width or height below zero (#311)
  4474. }*/
  4475. // clipping rectangle special
  4476. if (this.updateClipping) {
  4477. this[key] = value; // the key is now 'left' or 'top' for 'x' and 'y'
  4478. this.updateClipping();
  4479. } else {
  4480. // normal
  4481. element.style[key] = value;
  4482. }
  4483. },
  4484. zIndexSetter: function (value, key, element) {
  4485. element.style[key] = value;
  4486. }
  4487. };
  4488. Highcharts.VMLElement = VMLElement = extendClass(SVGElement, VMLElement);
  4489. // Some shared setters
  4490. VMLElement.prototype.ySetter =
  4491. VMLElement.prototype.widthSetter =
  4492. VMLElement.prototype.heightSetter =
  4493. VMLElement.prototype.xSetter;
  4494. /**
  4495. * The VML renderer
  4496. */
  4497. var VMLRendererExtension = { // inherit SVGRenderer
  4498. Element: VMLElement,
  4499. isIE8: userAgent.indexOf('MSIE 8.0') > -1,
  4500. /**
  4501. * Initialize the VMLRenderer
  4502. * @param {Object} container
  4503. * @param {Number} width
  4504. * @param {Number} height
  4505. */
  4506. init: function (container, width, height, style) {
  4507. var renderer = this,
  4508. boxWrapper,
  4509. box,
  4510. css;
  4511. renderer.alignedObjects = [];
  4512. boxWrapper = renderer.createElement(DIV)
  4513. .css(extend(this.getStyle(style), { position: RELATIVE}));
  4514. box = boxWrapper.element;
  4515. container.appendChild(boxWrapper.element);
  4516. // generate the containing box
  4517. renderer.isVML = true;
  4518. renderer.box = box;
  4519. renderer.boxWrapper = boxWrapper;
  4520. renderer.cache = {};
  4521. renderer.setSize(width, height, false);
  4522. // The only way to make IE6 and IE7 print is to use a global namespace. However,
  4523. // with IE8 the only way to make the dynamic shapes visible in screen and print mode
  4524. // seems to be to add the xmlns attribute and the behaviour style inline.
  4525. if (!doc.namespaces.hcv) {
  4526. doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml');
  4527. // Setup default CSS (#2153, #2368, #2384)
  4528. css = 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' +
  4529. '{ behavior:url(#default#VML); display: inline-block; } ';
  4530. try {
  4531. doc.createStyleSheet().cssText = css;
  4532. } catch (e) {
  4533. doc.styleSheets[0].cssText += css;
  4534. }
  4535. }
  4536. },
  4537. /**
  4538. * Detect whether the renderer is hidden. This happens when one of the parent elements
  4539. * has display: none
  4540. */
  4541. isHidden: function () {
  4542. return !this.box.offsetWidth;
  4543. },
  4544. /**
  4545. * Define a clipping rectangle. In VML it is accomplished by storing the values
  4546. * for setting the CSS style to all associated members.
  4547. *
  4548. * @param {Number} x
  4549. * @param {Number} y
  4550. * @param {Number} width
  4551. * @param {Number} height
  4552. */
  4553. clipRect: function (x, y, width, height) {
  4554. // create a dummy element
  4555. var clipRect = this.createElement(),
  4556. isObj = isObject(x);
  4557. // mimic a rectangle with its style object for automatic updating in attr
  4558. return extend(clipRect, {
  4559. members: [],
  4560. count: 0,
  4561. left: (isObj ? x.x : x) + 1,
  4562. top: (isObj ? x.y : y) + 1,
  4563. width: (isObj ? x.width : width) - 1,
  4564. height: (isObj ? x.height : height) - 1,
  4565. getCSS: function (wrapper) {
  4566. var element = wrapper.element,
  4567. nodeName = element.nodeName,
  4568. isShape = nodeName === 'shape',
  4569. inverted = wrapper.inverted,
  4570. rect = this,
  4571. top = rect.top - (isShape ? element.offsetTop : 0),
  4572. left = rect.left,
  4573. right = left + rect.width,
  4574. bottom = top + rect.height,
  4575. ret = {
  4576. clip: 'rect(' +
  4577. mathRound(inverted ? left : top) + 'px,' +
  4578. mathRound(inverted ? bottom : right) + 'px,' +
  4579. mathRound(inverted ? right : bottom) + 'px,' +
  4580. mathRound(inverted ? top : left) + 'px)'
  4581. };
  4582. // issue 74 workaround
  4583. if (!inverted && docMode8 && nodeName === 'DIV') {
  4584. extend(ret, {
  4585. width: right + PX,
  4586. height: bottom + PX
  4587. });
  4588. }
  4589. return ret;
  4590. },
  4591. // used in attr and animation to update the clipping of all members
  4592. updateClipping: function () {
  4593. each(clipRect.members, function (member) {
  4594. if (member.element) { // Deleted series, like in stock/members/series-remove demo. Should be removed from members, but this will do.
  4595. member.css(clipRect.getCSS(member));
  4596. }
  4597. });
  4598. }
  4599. });
  4600. },
  4601. /**
  4602. * Take a color and return it if it's a string, make it a gradient if it's a
  4603. * gradient configuration object, and apply opacity.
  4604. *
  4605. * @param {Object} color The color or config object
  4606. */
  4607. color: function (color, elem, prop, wrapper) {
  4608. var renderer = this,
  4609. colorObject,
  4610. regexRgba = /^rgba/,
  4611. markup,
  4612. fillType,
  4613. ret = NONE;
  4614. // Check for linear or radial gradient
  4615. if (color && color.linearGradient) {
  4616. fillType = 'gradient';
  4617. } else if (color && color.radialGradient) {
  4618. fillType = 'pattern';
  4619. }
  4620. if (fillType) {
  4621. var stopColor,
  4622. stopOpacity,
  4623. gradient = color.linearGradient || color.radialGradient,
  4624. x1,
  4625. y1,
  4626. x2,
  4627. y2,
  4628. opacity1,
  4629. opacity2,
  4630. color1,
  4631. color2,
  4632. fillAttr = '',
  4633. stops = color.stops,
  4634. firstStop,
  4635. lastStop,
  4636. colors = [],
  4637. addFillNode = function () {
  4638. // Add the fill subnode. When colors attribute is used, the meanings of opacity and o:opacity2
  4639. // are reversed.
  4640. markup = ['<fill colors="' + colors.join(',') + '" opacity="', opacity2, '" o:opacity2="', opacity1,
  4641. '" type="', fillType, '" ', fillAttr, 'focus="100%" method="any" />'];
  4642. createElement(renderer.prepVML(markup), null, null, elem);
  4643. };
  4644. // Extend from 0 to 1
  4645. firstStop = stops[0];
  4646. lastStop = stops[stops.length - 1];
  4647. if (firstStop[0] > 0) {
  4648. stops.unshift([
  4649. 0,
  4650. firstStop[1]
  4651. ]);
  4652. }
  4653. if (lastStop[0] < 1) {
  4654. stops.push([
  4655. 1,
  4656. lastStop[1]
  4657. ]);
  4658. }
  4659. // Compute the stops
  4660. each(stops, function (stop, i) {
  4661. if (regexRgba.test(stop[1])) {
  4662. colorObject = Color(stop[1]);
  4663. stopColor = colorObject.get('rgb');
  4664. stopOpacity = colorObject.get('a');
  4665. } else {
  4666. stopColor = stop[1];
  4667. stopOpacity = 1;
  4668. }
  4669. // Build the color attribute
  4670. colors.push((stop[0] * 100) + '% ' + stopColor);
  4671. // Only start and end opacities are allowed, so we use the first and the last
  4672. if (!i) {
  4673. opacity1 = stopOpacity;
  4674. color2 = stopColor;
  4675. } else {
  4676. opacity2 = stopOpacity;
  4677. color1 = stopColor;
  4678. }
  4679. });
  4680. // Apply the gradient to fills only.
  4681. if (prop === 'fill') {
  4682. // Handle linear gradient angle
  4683. if (fillType === 'gradient') {
  4684. x1 = gradient.x1 || gradient[0] || 0;
  4685. y1 = gradient.y1 || gradient[1] || 0;
  4686. x2 = gradient.x2 || gradient[2] || 0;
  4687. y2 = gradient.y2 || gradient[3] || 0;
  4688. fillAttr = 'angle="' + (90 - math.atan(
  4689. (y2 - y1) / // y vector
  4690. (x2 - x1) // x vector
  4691. ) * 180 / mathPI) + '"';
  4692. addFillNode();
  4693. // Radial (circular) gradient
  4694. } else {
  4695. var r = gradient.r,
  4696. sizex = r * 2,
  4697. sizey = r * 2,
  4698. cx = gradient.cx,
  4699. cy = gradient.cy,
  4700. radialReference = elem.radialReference,
  4701. bBox,
  4702. applyRadialGradient = function () {
  4703. if (radialReference) {
  4704. bBox = wrapper.getBBox();
  4705. cx += (radialReference[0] - bBox.x) / bBox.width - 0.5;
  4706. cy += (radialReference[1] - bBox.y) / bBox.height - 0.5;
  4707. sizex *= radialReference[2] / bBox.width;
  4708. sizey *= radialReference[2] / bBox.height;
  4709. }
  4710. fillAttr = 'src="' + defaultOptions.global.VMLRadialGradientURL + '" ' +
  4711. 'size="' + sizex + ',' + sizey + '" ' +
  4712. 'origin="0.5,0.5" ' +
  4713. 'position="' + cx + ',' + cy + '" ' +
  4714. 'color2="' + color2 + '" ';
  4715. addFillNode();
  4716. };
  4717. // Apply radial gradient
  4718. if (wrapper.added) {
  4719. applyRadialGradient();
  4720. } else {
  4721. // We need to know the bounding box to get the size and position right
  4722. wrapper.onAdd = applyRadialGradient;
  4723. }
  4724. // The fill element's color attribute is broken in IE8 standards mode, so we
  4725. // need to set the parent shape's fillcolor attribute instead.
  4726. ret = color1;
  4727. }
  4728. // Gradients are not supported for VML stroke, return the first color. #722.
  4729. } else {
  4730. ret = stopColor;
  4731. }
  4732. // if the color is an rgba color, split it and add a fill node
  4733. // to hold the opacity component
  4734. } else if (regexRgba.test(color) && elem.tagName !== 'IMG') {
  4735. colorObject = Color(color);
  4736. markup = ['<', prop, ' opacity="', colorObject.get('a'), '"/>'];
  4737. createElement(this.prepVML(markup), null, null, elem);
  4738. ret = colorObject.get('rgb');
  4739. } else {
  4740. var propNodes = elem.getElementsByTagName(prop); // 'stroke' or 'fill' node
  4741. if (propNodes.length) {
  4742. propNodes[0].opacity = 1;
  4743. propNodes[0].type = 'solid';
  4744. }
  4745. ret = color;
  4746. }
  4747. return ret;
  4748. },
  4749. /**
  4750. * Take a VML string and prepare it for either IE8 or IE6/IE7.
  4751. * @param {Array} markup A string array of the VML markup to prepare
  4752. */
  4753. prepVML: function (markup) {
  4754. var vmlStyle = 'display:inline-block;behavior:url(#default#VML);',
  4755. isIE8 = this.isIE8;
  4756. markup = markup.join('');
  4757. if (isIE8) { // add xmlns and style inline
  4758. markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />');
  4759. if (markup.indexOf('style="') === -1) {
  4760. markup = markup.replace('/>', ' style="' + vmlStyle + '" />');
  4761. } else {
  4762. markup = markup.replace('style="', 'style="' + vmlStyle);
  4763. }
  4764. } else { // add namespace
  4765. markup = markup.replace('<', '<hcv:');
  4766. }
  4767. return markup;
  4768. },
  4769. /**
  4770. * Create rotated and aligned text
  4771. * @param {String} str
  4772. * @param {Number} x
  4773. * @param {Number} y
  4774. */
  4775. text: SVGRenderer.prototype.html,
  4776. /**
  4777. * Create and return a path element
  4778. * @param {Array} path
  4779. */
  4780. path: function (path) {
  4781. var attr = {
  4782. // subpixel precision down to 0.1 (width and height = 1px)
  4783. coordsize: '10 10'
  4784. };
  4785. if (isArray(path)) {
  4786. attr.d = path;
  4787. } else if (isObject(path)) { // attributes
  4788. extend(attr, path);
  4789. }
  4790. // create the shape
  4791. return this.createElement('shape').attr(attr);
  4792. },
  4793. /**
  4794. * Create and return a circle element. In VML circles are implemented as
  4795. * shapes, which is faster than v:oval
  4796. * @param {Number} x
  4797. * @param {Number} y
  4798. * @param {Number} r
  4799. */
  4800. circle: function (x, y, r) {
  4801. var circle = this.symbol('circle');
  4802. if (isObject(x)) {
  4803. r = x.r;
  4804. y = x.y;
  4805. x = x.x;
  4806. }
  4807. circle.isCircle = true; // Causes x and y to mean center (#1682)
  4808. circle.r = r;
  4809. return circle.attr({ x: x, y: y });
  4810. },
  4811. /**
  4812. * Create a group using an outer div and an inner v:group to allow rotating
  4813. * and flipping. A simple v:group would have problems with positioning
  4814. * child HTML elements and CSS clip.
  4815. *
  4816. * @param {String} name The name of the group
  4817. */
  4818. g: function (name) {
  4819. var wrapper,
  4820. attribs;
  4821. // set the class name
  4822. if (name) {
  4823. attribs = { 'className': PREFIX + name, 'class': PREFIX + name };
  4824. }
  4825. // the div to hold HTML and clipping
  4826. wrapper = this.createElement(DIV).attr(attribs);
  4827. return wrapper;
  4828. },
  4829. /**
  4830. * VML override to create a regular HTML image
  4831. * @param {String} src
  4832. * @param {Number} x
  4833. * @param {Number} y
  4834. * @param {Number} width
  4835. * @param {Number} height
  4836. */
  4837. image: function (src, x, y, width, height) {
  4838. var obj = this.createElement('img')
  4839. .attr({ src: src });
  4840. if (arguments.length > 1) {
  4841. obj.attr({
  4842. x: x,
  4843. y: y,
  4844. width: width,
  4845. height: height
  4846. });
  4847. }
  4848. return obj;
  4849. },
  4850. /**
  4851. * For rectangles, VML uses a shape for rect to overcome bugs and rotation problems
  4852. */
  4853. createElement: function (nodeName) {
  4854. return nodeName === 'rect' ? this.symbol(nodeName) : SVGRenderer.prototype.createElement.call(this, nodeName);
  4855. },
  4856. /**
  4857. * In the VML renderer, each child of an inverted div (group) is inverted
  4858. * @param {Object} element
  4859. * @param {Object} parentNode
  4860. */
  4861. invertChild: function (element, parentNode) {
  4862. var ren = this,
  4863. parentStyle = parentNode.style,
  4864. imgStyle = element.tagName === 'IMG' && element.style; // #1111
  4865. css(element, {
  4866. flip: 'x',
  4867. left: pInt(parentStyle.width) - (imgStyle ? pInt(imgStyle.top) : 1),
  4868. top: pInt(parentStyle.height) - (imgStyle ? pInt(imgStyle.left) : 1),
  4869. rotation: -90
  4870. });
  4871. // Recursively invert child elements, needed for nested composite shapes like box plots and error bars. #1680, #1806.
  4872. each(element.childNodes, function (child) {
  4873. ren.invertChild(child, element);
  4874. });
  4875. },
  4876. /**
  4877. * Symbol definitions that override the parent SVG renderer's symbols
  4878. *
  4879. */
  4880. symbols: {
  4881. // VML specific arc function
  4882. arc: function (x, y, w, h, options) {
  4883. var start = options.start,
  4884. end = options.end,
  4885. radius = options.r || w || h,
  4886. innerRadius = options.innerR,
  4887. cosStart = mathCos(start),
  4888. sinStart = mathSin(start),
  4889. cosEnd = mathCos(end),
  4890. sinEnd = mathSin(end),
  4891. ret;
  4892. if (end - start === 0) { // no angle, don't show it.
  4893. return ['x'];
  4894. }
  4895. ret = [
  4896. 'wa', // clockwise arc to
  4897. x - radius, // left
  4898. y - radius, // top
  4899. x + radius, // right
  4900. y + radius, // bottom
  4901. x + radius * cosStart, // start x
  4902. y + radius * sinStart, // start y
  4903. x + radius * cosEnd, // end x
  4904. y + radius * sinEnd // end y
  4905. ];
  4906. if (options.open && !innerRadius) {
  4907. ret.push(
  4908. 'e',
  4909. M,
  4910. x,// - innerRadius,
  4911. y// - innerRadius
  4912. );
  4913. }
  4914. ret.push(
  4915. 'at', // anti clockwise arc to
  4916. x - innerRadius, // left
  4917. y - innerRadius, // top
  4918. x + innerRadius, // right
  4919. y + innerRadius, // bottom
  4920. x + innerRadius * cosEnd, // start x
  4921. y + innerRadius * sinEnd, // start y
  4922. x + innerRadius * cosStart, // end x
  4923. y + innerRadius * sinStart, // end y
  4924. 'x', // finish path
  4925. 'e' // close
  4926. );
  4927. ret.isArc = true;
  4928. return ret;
  4929. },
  4930. // Add circle symbol path. This performs significantly faster than v:oval.
  4931. circle: function (x, y, w, h, wrapper) {
  4932. if (wrapper) {
  4933. w = h = 2 * wrapper.r;
  4934. }
  4935. // Center correction, #1682
  4936. if (wrapper && wrapper.isCircle) {
  4937. x -= w / 2;
  4938. y -= h / 2;
  4939. }
  4940. // Return the path
  4941. return [
  4942. 'wa', // clockwisearcto
  4943. x, // left
  4944. y, // top
  4945. x + w, // right
  4946. y + h, // bottom
  4947. x + w, // start x
  4948. y + h / 2, // start y
  4949. x + w, // end x
  4950. y + h / 2, // end y
  4951. //'x', // finish path
  4952. 'e' // close
  4953. ];
  4954. },
  4955. /**
  4956. * Add rectangle symbol path which eases rotation and omits arcsize problems
  4957. * compared to the built-in VML roundrect shape. When borders are not rounded,
  4958. * use the simpler square path, else use the callout path without the arrow.
  4959. */
  4960. rect: function (x, y, w, h, options) {
  4961. return SVGRenderer.prototype.symbols[
  4962. !defined(options) || !options.r ? 'square' : 'callout'
  4963. ].call(0, x, y, w, h, options);
  4964. }
  4965. }
  4966. };
  4967. Highcharts.VMLRenderer = VMLRenderer = function () {
  4968. this.init.apply(this, arguments);
  4969. };
  4970. VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension);
  4971. // general renderer
  4972. Renderer = VMLRenderer;
  4973. }
  4974. // This method is used with exporting in old IE, when emulating SVG (see #2314)
  4975. SVGRenderer.prototype.measureSpanWidth = function (text, styles) {
  4976. var measuringSpan = doc.createElement('span'),
  4977. offsetWidth,
  4978. textNode = doc.createTextNode(text);
  4979. measuringSpan.appendChild(textNode);
  4980. css(measuringSpan, styles);
  4981. this.box.appendChild(measuringSpan);
  4982. offsetWidth = measuringSpan.offsetWidth;
  4983. discardElement(measuringSpan); // #2463
  4984. return offsetWidth;
  4985. };
  4986. /* ****************************************************************************
  4987. * *
  4988. * END OF INTERNET EXPLORER <= 8 SPECIFIC CODE *
  4989. * *
  4990. *****************************************************************************/
  4991. /* ****************************************************************************
  4992. * *
  4993. * START OF ANDROID < 3 SPECIFIC CODE. THIS CAN BE REMOVED IF YOU'RE NOT *
  4994. * TARGETING THAT SYSTEM. *
  4995. * *
  4996. *****************************************************************************/
  4997. var CanVGRenderer,
  4998. CanVGController;
  4999. if (useCanVG) {
  5000. /**
  5001. * The CanVGRenderer is empty from start to keep the source footprint small.
  5002. * When requested, the CanVGController downloads the rest of the source packaged
  5003. * together with the canvg library.
  5004. */
  5005. Highcharts.CanVGRenderer = CanVGRenderer = function () {
  5006. // Override the global SVG namespace to fake SVG/HTML that accepts CSS
  5007. SVG_NS = 'http://www.w3.org/1999/xhtml';
  5008. };
  5009. /**
  5010. * Start with an empty symbols object. This is needed when exporting is used (exporting.src.js will add a few symbols), but
  5011. * the implementation from SvgRenderer will not be merged in until first render.
  5012. */
  5013. CanVGRenderer.prototype.symbols = {};
  5014. /**
  5015. * Handles on demand download of canvg rendering support.
  5016. */
  5017. CanVGController = (function () {
  5018. // List of renderering calls
  5019. var deferredRenderCalls = [];
  5020. /**
  5021. * When downloaded, we are ready to draw deferred charts.
  5022. */
  5023. function drawDeferred() {
  5024. var callLength = deferredRenderCalls.length,
  5025. callIndex;
  5026. // Draw all pending render calls
  5027. for (callIndex = 0; callIndex < callLength; callIndex++) {
  5028. deferredRenderCalls[callIndex]();
  5029. }
  5030. // Clear the list
  5031. deferredRenderCalls = [];
  5032. }
  5033. return {
  5034. push: function (func, scriptLocation) {
  5035. // Only get the script once
  5036. if (deferredRenderCalls.length === 0) {
  5037. getScript(scriptLocation, drawDeferred);
  5038. }
  5039. // Register render call
  5040. deferredRenderCalls.push(func);
  5041. }
  5042. };
  5043. }());
  5044. Renderer = CanVGRenderer;
  5045. } // end CanVGRenderer
  5046. /* ****************************************************************************
  5047. * *
  5048. * END OF ANDROID < 3 SPECIFIC CODE *
  5049. * *
  5050. *****************************************************************************/
  5051. /**
  5052. * The Tick class
  5053. */
  5054. function Tick(axis, pos, type, noLabel) {
  5055. this.axis = axis;
  5056. this.pos = pos;
  5057. this.type = type || '';
  5058. this.isNew = true;
  5059. if (!type && !noLabel) {
  5060. this.addLabel();
  5061. }
  5062. }
  5063. Tick.prototype = {
  5064. /**
  5065. * Write the tick label
  5066. */
  5067. addLabel: function () {
  5068. var tick = this,
  5069. axis = tick.axis,
  5070. options = axis.options,
  5071. chart = axis.chart,
  5072. categories = axis.categories,
  5073. names = axis.names,
  5074. pos = tick.pos,
  5075. labelOptions = options.labels,
  5076. str,
  5077. tickPositions = axis.tickPositions,
  5078. isFirst = pos === tickPositions[0],
  5079. isLast = pos === tickPositions[tickPositions.length - 1],
  5080. value = categories ?
  5081. pick(categories[pos], names[pos], pos) :
  5082. pos,
  5083. label = tick.label,
  5084. tickPositionInfo = tickPositions.info,
  5085. dateTimeLabelFormat;
  5086. // Set the datetime label format. If a higher rank is set for this position, use that. If not,
  5087. // use the general format.
  5088. if (axis.isDatetimeAxis && tickPositionInfo) {
  5089. dateTimeLabelFormat = options.dateTimeLabelFormats[tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName];
  5090. }
  5091. // set properties for access in render method
  5092. tick.isFirst = isFirst;
  5093. tick.isLast = isLast;
  5094. // get the string
  5095. str = axis.labelFormatter.call({
  5096. axis: axis,
  5097. chart: chart,
  5098. isFirst: isFirst,
  5099. isLast: isLast,
  5100. dateTimeLabelFormat: dateTimeLabelFormat,
  5101. value: axis.isLog ? correctFloat(lin2log(value)) : value
  5102. });
  5103. // prepare CSS
  5104. //css = width && { width: mathMax(1, mathRound(width - 2 * (labelOptions.padding || 10))) + PX };
  5105. // first call
  5106. if (!defined(label)) {
  5107. tick.label = label =
  5108. defined(str) && labelOptions.enabled ?
  5109. chart.renderer.text(
  5110. str,
  5111. 0,
  5112. 0,
  5113. labelOptions.useHTML
  5114. )
  5115. //.attr(attr)
  5116. // without position absolute, IE export sometimes is wrong
  5117. .css(merge(labelOptions.style))
  5118. .add(axis.labelGroup) :
  5119. null;
  5120. tick.labelLength = label && label.getBBox().width; // Un-rotated length
  5121. tick.rotation = 0; // Base value to detect change for new calls to getBBox
  5122. // update
  5123. } else if (label) {
  5124. label.attr({ text: str });
  5125. }
  5126. },
  5127. /**
  5128. * Get the offset height or width of the label
  5129. */
  5130. getLabelSize: function () {
  5131. return this.label ?
  5132. this.label.getBBox()[this.axis.horiz ? 'height' : 'width'] :
  5133. 0;
  5134. },
  5135. /**
  5136. * Handle the label overflow by adjusting the labels to the left and right edge, or
  5137. * hide them if they collide into the neighbour label.
  5138. */
  5139. handleOverflow: function (xy) {
  5140. var axis = this.axis,
  5141. pxPos = xy.x,
  5142. chartWidth = axis.chart.chartWidth,
  5143. spacing = axis.chart.spacing,
  5144. leftBound = pick(axis.labelLeft, spacing[3]),
  5145. rightBound = pick(axis.labelRight, chartWidth - spacing[1]),
  5146. label = this.label,
  5147. rotation = this.rotation,
  5148. factor = { left: 0, center: 0.5, right: 1 }[axis.labelAlign],
  5149. labelWidth = label.getBBox().width,
  5150. slotWidth = axis.slotWidth,
  5151. leftPos,
  5152. rightPos,
  5153. textWidth;
  5154. // Check if the label overshoots the chart spacing box. If it does, move it.
  5155. // If it now overshoots the slotWidth, add ellipsis.
  5156. if (!rotation) {
  5157. leftPos = pxPos - factor * labelWidth;
  5158. rightPos = pxPos + factor * labelWidth;
  5159. if (leftPos < leftBound) {
  5160. slotWidth -= leftBound - leftPos;
  5161. xy.x = leftBound;
  5162. label.attr({ align: 'left' });
  5163. } else if (rightPos > rightBound) {
  5164. slotWidth -= rightPos - rightBound;
  5165. xy.x = rightBound;
  5166. label.attr({ align: 'right' });
  5167. }
  5168. // If the label width exceeds the available space, set a text width to be
  5169. // picked up below. Also, if a width has been set before, we need to set a new
  5170. // one because the reported labelWidth will be limited by the box (#3938).
  5171. if (labelWidth > slotWidth || (axis.autoRotation && label.styles.width)) {
  5172. textWidth = slotWidth;
  5173. }
  5174. // Add ellipsis to prevent rotated labels to be clipped against the edge of the chart
  5175. } else if (rotation < 0 && pxPos - factor * labelWidth < leftBound) {
  5176. textWidth = mathRound(pxPos / mathCos(rotation * deg2rad) - leftBound);
  5177. } else if (rotation > 0 && pxPos + factor * labelWidth > rightBound) {
  5178. textWidth = mathRound((chartWidth - pxPos) / mathCos(rotation * deg2rad));
  5179. }
  5180. if (textWidth) {
  5181. label.css({
  5182. width: textWidth,
  5183. textOverflow: 'ellipsis'
  5184. });
  5185. }
  5186. },
  5187. /**
  5188. * Get the x and y position for ticks and labels
  5189. */
  5190. getPosition: function (horiz, pos, tickmarkOffset, old) {
  5191. var axis = this.axis,
  5192. chart = axis.chart,
  5193. cHeight = (old && chart.oldChartHeight) || chart.chartHeight;
  5194. return {
  5195. x: horiz ?
  5196. axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB :
  5197. axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0),
  5198. y: horiz ?
  5199. cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) :
  5200. cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB
  5201. };
  5202. },
  5203. /**
  5204. * Get the x, y position of the tick label
  5205. */
  5206. getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) {
  5207. var axis = this.axis,
  5208. transA = axis.transA,
  5209. reversed = axis.reversed,
  5210. staggerLines = axis.staggerLines,
  5211. rotCorr = axis.tickRotCorr || { x: 0, y: 0 },
  5212. yOffset = pick(labelOptions.y, rotCorr.y + (axis.side === 2 ? 8 : -(label.getBBox().height / 2))),
  5213. line;
  5214. x = x + labelOptions.x + rotCorr.x - (tickmarkOffset && horiz ?
  5215. tickmarkOffset * transA * (reversed ? -1 : 1) : 0);
  5216. y = y + yOffset - (tickmarkOffset && !horiz ?
  5217. tickmarkOffset * transA * (reversed ? 1 : -1) : 0);
  5218. // Correct for staggered labels
  5219. if (staggerLines) {
  5220. line = (index / (step || 1) % staggerLines);
  5221. y += line * (axis.labelOffset / staggerLines);
  5222. }
  5223. return {
  5224. x: x,
  5225. y: mathRound(y)
  5226. };
  5227. },
  5228. /**
  5229. * Extendible method to return the path of the marker
  5230. */
  5231. getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) {
  5232. return renderer.crispLine([
  5233. M,
  5234. x,
  5235. y,
  5236. L,
  5237. x + (horiz ? 0 : -tickLength),
  5238. y + (horiz ? tickLength : 0)
  5239. ], tickWidth);
  5240. },
  5241. /**
  5242. * Put everything in place
  5243. *
  5244. * @param index {Number}
  5245. * @param old {Boolean} Use old coordinates to prepare an animation into new position
  5246. */
  5247. render: function (index, old, opacity) {
  5248. var tick = this,
  5249. axis = tick.axis,
  5250. options = axis.options,
  5251. chart = axis.chart,
  5252. renderer = chart.renderer,
  5253. horiz = axis.horiz,
  5254. type = tick.type,
  5255. label = tick.label,
  5256. pos = tick.pos,
  5257. labelOptions = options.labels,
  5258. gridLine = tick.gridLine,
  5259. gridPrefix = type ? type + 'Grid' : 'grid',
  5260. tickPrefix = type ? type + 'Tick' : 'tick',
  5261. gridLineWidth = options[gridPrefix + 'LineWidth'],
  5262. gridLineColor = options[gridPrefix + 'LineColor'],
  5263. dashStyle = options[gridPrefix + 'LineDashStyle'],
  5264. tickLength = options[tickPrefix + 'Length'],
  5265. tickWidth = options[tickPrefix + 'Width'] || 0,
  5266. tickColor = options[tickPrefix + 'Color'],
  5267. tickPosition = options[tickPrefix + 'Position'],
  5268. gridLinePath,
  5269. mark = tick.mark,
  5270. markPath,
  5271. step = /*axis.labelStep || */labelOptions.step,
  5272. attribs,
  5273. show = true,
  5274. tickmarkOffset = axis.tickmarkOffset,
  5275. xy = tick.getPosition(horiz, pos, tickmarkOffset, old),
  5276. x = xy.x,
  5277. y = xy.y,
  5278. reverseCrisp = ((horiz && x === axis.pos + axis.len) || (!horiz && y === axis.pos)) ? -1 : 1; // #1480, #1687
  5279. opacity = pick(opacity, 1);
  5280. this.isActive = true;
  5281. // create the grid line
  5282. if (gridLineWidth) {
  5283. gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLineWidth * reverseCrisp, old, true);
  5284. if (gridLine === UNDEFINED) {
  5285. attribs = {
  5286. stroke: gridLineColor,
  5287. 'stroke-width': gridLineWidth
  5288. };
  5289. if (dashStyle) {
  5290. attribs.dashstyle = dashStyle;
  5291. }
  5292. if (!type) {
  5293. attribs.zIndex = 1;
  5294. }
  5295. if (old) {
  5296. attribs.opacity = 0;
  5297. }
  5298. tick.gridLine = gridLine =
  5299. gridLineWidth ?
  5300. renderer.path(gridLinePath)
  5301. .attr(attribs).add(axis.gridGroup) :
  5302. null;
  5303. }
  5304. // If the parameter 'old' is set, the current call will be followed
  5305. // by another call, therefore do not do any animations this time
  5306. if (!old && gridLine && gridLinePath) {
  5307. gridLine[tick.isNew ? 'attr' : 'animate']({
  5308. d: gridLinePath,
  5309. opacity: opacity
  5310. });
  5311. }
  5312. }
  5313. // create the tick mark
  5314. if (tickWidth && tickLength) {
  5315. // negate the length
  5316. if (tickPosition === 'inside') {
  5317. tickLength = -tickLength;
  5318. }
  5319. if (axis.opposite) {
  5320. tickLength = -tickLength;
  5321. }
  5322. markPath = tick.getMarkPath(x, y, tickLength, tickWidth * reverseCrisp, horiz, renderer);
  5323. if (mark) { // updating
  5324. mark.animate({
  5325. d: markPath,
  5326. opacity: opacity
  5327. });
  5328. } else { // first time
  5329. tick.mark = renderer.path(
  5330. markPath
  5331. ).attr({
  5332. stroke: tickColor,
  5333. 'stroke-width': tickWidth,
  5334. opacity: opacity
  5335. }).add(axis.axisGroup);
  5336. }
  5337. }
  5338. // the label is created on init - now move it into place
  5339. if (label && !isNaN(x)) {
  5340. label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step);
  5341. // Apply show first and show last. If the tick is both first and last, it is
  5342. // a single centered tick, in which case we show the label anyway (#2100).
  5343. if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) ||
  5344. (tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) {
  5345. show = false;
  5346. // Handle label overflow and show or hide accordingly
  5347. } else if (horiz && !axis.isRadial && !labelOptions.step && !labelOptions.rotation && !old && opacity !== 0) {
  5348. tick.handleOverflow(xy);
  5349. }
  5350. // apply step
  5351. if (step && index % step) {
  5352. // show those indices dividable by step
  5353. show = false;
  5354. }
  5355. // Set the new position, and show or hide
  5356. if (show && !isNaN(xy.y)) {
  5357. xy.opacity = opacity;
  5358. label[tick.isNew ? 'attr' : 'animate'](xy);
  5359. tick.isNew = false;
  5360. } else {
  5361. label.attr('y', -9999); // #1338
  5362. }
  5363. }
  5364. },
  5365. /**
  5366. * Destructor for the tick prototype
  5367. */
  5368. destroy: function () {
  5369. destroyObjectProperties(this, this.axis);
  5370. }
  5371. };
  5372. /**
  5373. * The object wrapper for plot lines and plot bands
  5374. * @param {Object} options
  5375. */
  5376. Highcharts.PlotLineOrBand = function (axis, options) {
  5377. this.axis = axis;
  5378. if (options) {
  5379. this.options = options;
  5380. this.id = options.id;
  5381. }
  5382. };
  5383. Highcharts.PlotLineOrBand.prototype = {
  5384. /**
  5385. * Render the plot line or plot band. If it is already existing,
  5386. * move it.
  5387. */
  5388. render: function () {
  5389. var plotLine = this,
  5390. axis = plotLine.axis,
  5391. horiz = axis.horiz,
  5392. options = plotLine.options,
  5393. optionsLabel = options.label,
  5394. label = plotLine.label,
  5395. width = options.width,
  5396. to = options.to,
  5397. from = options.from,
  5398. isBand = defined(from) && defined(to),
  5399. value = options.value,
  5400. dashStyle = options.dashStyle,
  5401. svgElem = plotLine.svgElem,
  5402. path = [],
  5403. addEvent,
  5404. eventType,
  5405. xs,
  5406. ys,
  5407. x,
  5408. y,
  5409. color = options.color,
  5410. zIndex = options.zIndex,
  5411. events = options.events,
  5412. attribs = {},
  5413. renderer = axis.chart.renderer;
  5414. // logarithmic conversion
  5415. if (axis.isLog) {
  5416. from = log2lin(from);
  5417. to = log2lin(to);
  5418. value = log2lin(value);
  5419. }
  5420. // plot line
  5421. if (width) {
  5422. path = axis.getPlotLinePath(value, width);
  5423. attribs = {
  5424. stroke: color,
  5425. 'stroke-width': width
  5426. };
  5427. if (dashStyle) {
  5428. attribs.dashstyle = dashStyle;
  5429. }
  5430. } else if (isBand) { // plot band
  5431. path = axis.getPlotBandPath(from, to, options);
  5432. if (color) {
  5433. attribs.fill = color;
  5434. }
  5435. if (options.borderWidth) {
  5436. attribs.stroke = options.borderColor;
  5437. attribs['stroke-width'] = options.borderWidth;
  5438. }
  5439. } else {
  5440. return;
  5441. }
  5442. // zIndex
  5443. if (defined(zIndex)) {
  5444. attribs.zIndex = zIndex;
  5445. }
  5446. // common for lines and bands
  5447. if (svgElem) {
  5448. if (path) {
  5449. svgElem.animate({
  5450. d: path
  5451. }, null, svgElem.onGetPath);
  5452. } else {
  5453. svgElem.hide();
  5454. svgElem.onGetPath = function () {
  5455. svgElem.show();
  5456. };
  5457. if (label) {
  5458. plotLine.label = label = label.destroy();
  5459. }
  5460. }
  5461. } else if (path && path.length) {
  5462. plotLine.svgElem = svgElem = renderer.path(path)
  5463. .attr(attribs).add();
  5464. // events
  5465. if (events) {
  5466. addEvent = function (eventType) {
  5467. svgElem.on(eventType, function (e) {
  5468. events[eventType].apply(plotLine, [e]);
  5469. });
  5470. };
  5471. for (eventType in events) {
  5472. addEvent(eventType);
  5473. }
  5474. }
  5475. }
  5476. // the plot band/line label
  5477. if (optionsLabel && defined(optionsLabel.text) && path && path.length && axis.width > 0 && axis.height > 0) {
  5478. // apply defaults
  5479. optionsLabel = merge({
  5480. align: horiz && isBand && 'center',
  5481. x: horiz ? !isBand && 4 : 10,
  5482. verticalAlign : !horiz && isBand && 'middle',
  5483. y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4,
  5484. rotation: horiz && !isBand && 90
  5485. }, optionsLabel);
  5486. // add the SVG element
  5487. if (!label) {
  5488. attribs = {
  5489. align: optionsLabel.textAlign || optionsLabel.align,
  5490. rotation: optionsLabel.rotation
  5491. };
  5492. if (defined(zIndex)) {
  5493. attribs.zIndex = zIndex;
  5494. }
  5495. plotLine.label = label = renderer.text(
  5496. optionsLabel.text,
  5497. 0,
  5498. 0,
  5499. optionsLabel.useHTML
  5500. )
  5501. .attr(attribs)
  5502. .css(optionsLabel.style)
  5503. .add();
  5504. }
  5505. // get the bounding box and align the label
  5506. // #3000 changed to better handle choice between plotband or plotline
  5507. xs = [path[1], path[4], (isBand ? path[6] : path[1])];
  5508. ys = [path[2], path[5], (isBand ? path[7] : path[2])];
  5509. x = arrayMin(xs);
  5510. y = arrayMin(ys);
  5511. label.align(optionsLabel, false, {
  5512. x: x,
  5513. y: y,
  5514. width: arrayMax(xs) - x,
  5515. height: arrayMax(ys) - y
  5516. });
  5517. label.show();
  5518. } else if (label) { // move out of sight
  5519. label.hide();
  5520. }
  5521. // chainable
  5522. return plotLine;
  5523. },
  5524. /**
  5525. * Remove the plot line or band
  5526. */
  5527. destroy: function () {
  5528. // remove it from the lookup
  5529. erase(this.axis.plotLinesAndBands, this);
  5530. delete this.axis;
  5531. destroyObjectProperties(this);
  5532. }
  5533. };
  5534. /**
  5535. * Object with members for extending the Axis prototype
  5536. */
  5537. AxisPlotLineOrBandExtension = {
  5538. /**
  5539. * Create the path for a plot band
  5540. */
  5541. getPlotBandPath: function (from, to) {
  5542. var toPath = this.getPlotLinePath(to, null, null, true),
  5543. path = this.getPlotLinePath(from, null, null, true);
  5544. if (path && toPath && path.toString() !== toPath.toString()) { // #3836
  5545. path.push(
  5546. toPath[4],
  5547. toPath[5],
  5548. toPath[1],
  5549. toPath[2]
  5550. );
  5551. } else { // outside the axis area
  5552. path = null;
  5553. }
  5554. return path;
  5555. },
  5556. addPlotBand: function (options) {
  5557. return this.addPlotBandOrLine(options, 'plotBands');
  5558. },
  5559. addPlotLine: function (options) {
  5560. return this.addPlotBandOrLine(options, 'plotLines');
  5561. },
  5562. /**
  5563. * Add a plot band or plot line after render time
  5564. *
  5565. * @param options {Object} The plotBand or plotLine configuration object
  5566. */
  5567. addPlotBandOrLine: function (options, coll) {
  5568. var obj = new Highcharts.PlotLineOrBand(this, options).render(),
  5569. userOptions = this.userOptions;
  5570. if (obj) { // #2189
  5571. // Add it to the user options for exporting and Axis.update
  5572. if (coll) {
  5573. userOptions[coll] = userOptions[coll] || [];
  5574. userOptions[coll].push(options);
  5575. }
  5576. this.plotLinesAndBands.push(obj);
  5577. }
  5578. return obj;
  5579. },
  5580. /**
  5581. * Remove a plot band or plot line from the chart by id
  5582. * @param {Object} id
  5583. */
  5584. removePlotBandOrLine: function (id) {
  5585. var plotLinesAndBands = this.plotLinesAndBands,
  5586. options = this.options,
  5587. userOptions = this.userOptions,
  5588. i = plotLinesAndBands.length;
  5589. while (i--) {
  5590. if (plotLinesAndBands[i].id === id) {
  5591. plotLinesAndBands[i].destroy();
  5592. }
  5593. }
  5594. each([options.plotLines || [], userOptions.plotLines || [], options.plotBands || [], userOptions.plotBands || []], function (arr) {
  5595. i = arr.length;
  5596. while (i--) {
  5597. if (arr[i].id === id) {
  5598. erase(arr, arr[i]);
  5599. }
  5600. }
  5601. });
  5602. }
  5603. };
  5604. /**
  5605. * Create a new axis object
  5606. * @param {Object} chart
  5607. * @param {Object} options
  5608. */
  5609. var Axis = Highcharts.Axis = function () {
  5610. this.init.apply(this, arguments);
  5611. };
  5612. Axis.prototype = {
  5613. /**
  5614. * Default options for the X axis - the Y axis has extended defaults
  5615. */
  5616. defaultOptions: {
  5617. // allowDecimals: null,
  5618. // alternateGridColor: null,
  5619. // categories: [],
  5620. dateTimeLabelFormats: {
  5621. millisecond: '%H:%M:%S.%L',
  5622. second: '%H:%M:%S',
  5623. minute: '%H:%M',
  5624. hour: '%H:%M',
  5625. day: '%e. %b',
  5626. week: '%e. %b',
  5627. month: '%b \'%y',
  5628. year: '%Y'
  5629. },
  5630. endOnTick: false,
  5631. gridLineColor: '#D8D8D8',
  5632. // gridLineDashStyle: 'solid',
  5633. // gridLineWidth: 0,
  5634. // reversed: false,
  5635. labels: {
  5636. enabled: true,
  5637. // rotation: 0,
  5638. // align: 'center',
  5639. // step: null,
  5640. style: {
  5641. color: '#606060',
  5642. cursor: 'default',
  5643. fontSize: '11px'
  5644. },
  5645. x: 0,
  5646. y: 15
  5647. /*formatter: function () {
  5648. return this.value;
  5649. },*/
  5650. },
  5651. lineColor: '#C0D0E0',
  5652. lineWidth: 1,
  5653. //linkedTo: null,
  5654. //max: undefined,
  5655. //min: undefined,
  5656. minPadding: 0.01,
  5657. maxPadding: 0.01,
  5658. //minRange: null,
  5659. minorGridLineColor: '#E0E0E0',
  5660. // minorGridLineDashStyle: null,
  5661. minorGridLineWidth: 1,
  5662. minorTickColor: '#A0A0A0',
  5663. //minorTickInterval: null,
  5664. minorTickLength: 2,
  5665. minorTickPosition: 'outside', // inside or outside
  5666. //minorTickWidth: 0,
  5667. //opposite: false,
  5668. //offset: 0,
  5669. //plotBands: [{
  5670. // events: {},
  5671. // zIndex: 1,
  5672. // labels: { align, x, verticalAlign, y, style, rotation, textAlign }
  5673. //}],
  5674. //plotLines: [{
  5675. // events: {}
  5676. // dashStyle: {}
  5677. // zIndex:
  5678. // labels: { align, x, verticalAlign, y, style, rotation, textAlign }
  5679. //}],
  5680. //reversed: false,
  5681. // showFirstLabel: true,
  5682. // showLastLabel: true,
  5683. startOfWeek: 1,
  5684. startOnTick: false,
  5685. tickColor: '#C0D0E0',
  5686. //tickInterval: null,
  5687. tickLength: 10,
  5688. tickmarkPlacement: 'between', // on or between
  5689. tickPixelInterval: 100,
  5690. tickPosition: 'outside',
  5691. tickWidth: 1,
  5692. title: {
  5693. //text: null,
  5694. align: 'middle', // low, middle or high
  5695. //margin: 0 for horizontal, 10 for vertical axes,
  5696. //rotation: 0,
  5697. //side: 'outside',
  5698. style: {
  5699. color: '#707070'
  5700. }
  5701. //x: 0,
  5702. //y: 0
  5703. },
  5704. type: 'linear' // linear, logarithmic or datetime
  5705. },
  5706. /**
  5707. * This options set extends the defaultOptions for Y axes
  5708. */
  5709. defaultYAxisOptions: {
  5710. endOnTick: true,
  5711. gridLineWidth: 1,
  5712. tickPixelInterval: 72,
  5713. showLastLabel: true,
  5714. labels: {
  5715. x: -8,
  5716. y: 3
  5717. },
  5718. lineWidth: 0,
  5719. maxPadding: 0.05,
  5720. minPadding: 0.05,
  5721. startOnTick: true,
  5722. tickWidth: 0,
  5723. title: {
  5724. rotation: 270,
  5725. text: 'Values'
  5726. },
  5727. stackLabels: {
  5728. enabled: false,
  5729. //align: dynamic,
  5730. //y: dynamic,
  5731. //x: dynamic,
  5732. //verticalAlign: dynamic,
  5733. //textAlign: dynamic,
  5734. //rotation: 0,
  5735. formatter: function () {
  5736. return Highcharts.numberFormat(this.total, -1);
  5737. },
  5738. style: merge(defaultPlotOptions.line.dataLabels.style, { color: '#000000' })
  5739. }
  5740. },
  5741. /**
  5742. * These options extend the defaultOptions for left axes
  5743. */
  5744. defaultLeftAxisOptions: {
  5745. labels: {
  5746. x: -15,
  5747. y: null
  5748. },
  5749. title: {
  5750. rotation: 270
  5751. }
  5752. },
  5753. /**
  5754. * These options extend the defaultOptions for right axes
  5755. */
  5756. defaultRightAxisOptions: {
  5757. labels: {
  5758. x: 15,
  5759. y: null
  5760. },
  5761. title: {
  5762. rotation: 90
  5763. }
  5764. },
  5765. /**
  5766. * These options extend the defaultOptions for bottom axes
  5767. */
  5768. defaultBottomAxisOptions: {
  5769. labels: {
  5770. autoRotation: [-45],
  5771. x: 0,
  5772. y: null // based on font size
  5773. // overflow: undefined,
  5774. // staggerLines: null
  5775. },
  5776. title: {
  5777. rotation: 0
  5778. }
  5779. },
  5780. /**
  5781. * These options extend the defaultOptions for top axes
  5782. */
  5783. defaultTopAxisOptions: {
  5784. labels: {
  5785. autoRotation: [-45],
  5786. x: 0,
  5787. y: -15
  5788. // overflow: undefined
  5789. // staggerLines: null
  5790. },
  5791. title: {
  5792. rotation: 0
  5793. }
  5794. },
  5795. /**
  5796. * Initialize the axis
  5797. */
  5798. init: function (chart, userOptions) {
  5799. var isXAxis = userOptions.isX,
  5800. axis = this;
  5801. // Flag, is the axis horizontal
  5802. axis.horiz = chart.inverted ? !isXAxis : isXAxis;
  5803. // Flag, isXAxis
  5804. axis.isXAxis = isXAxis;
  5805. axis.coll = isXAxis ? 'xAxis' : 'yAxis';
  5806. axis.opposite = userOptions.opposite; // needed in setOptions
  5807. axis.side = userOptions.side || (axis.horiz ?
  5808. (axis.opposite ? 0 : 2) : // top : bottom
  5809. (axis.opposite ? 1 : 3)); // right : left
  5810. axis.setOptions(userOptions);
  5811. var options = this.options,
  5812. type = options.type,
  5813. isDatetimeAxis = type === 'datetime';
  5814. axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format
  5815. // Flag, stagger lines or not
  5816. axis.userOptions = userOptions;
  5817. //axis.axisTitleMargin = UNDEFINED,// = options.title.margin,
  5818. axis.minPixelPadding = 0;
  5819. //axis.ignoreMinPadding = UNDEFINED; // can be set to true by a column or bar series
  5820. //axis.ignoreMaxPadding = UNDEFINED;
  5821. axis.chart = chart;
  5822. axis.reversed = options.reversed;
  5823. axis.zoomEnabled = options.zoomEnabled !== false;
  5824. // Initial categories
  5825. axis.categories = options.categories || type === 'category';
  5826. axis.names = axis.names || []; // Preserve on update (#3830)
  5827. // Elements
  5828. //axis.axisGroup = UNDEFINED;
  5829. //axis.gridGroup = UNDEFINED;
  5830. //axis.axisTitle = UNDEFINED;
  5831. //axis.axisLine = UNDEFINED;
  5832. // Shorthand types
  5833. axis.isLog = type === 'logarithmic';
  5834. axis.isDatetimeAxis = isDatetimeAxis;
  5835. // Flag, if axis is linked to another axis
  5836. axis.isLinked = defined(options.linkedTo);
  5837. // Linked axis.
  5838. //axis.linkedParent = UNDEFINED;
  5839. // Tick positions
  5840. //axis.tickPositions = UNDEFINED; // array containing predefined positions
  5841. // Tick intervals
  5842. //axis.tickInterval = UNDEFINED;
  5843. //axis.minorTickInterval = UNDEFINED;
  5844. // Major ticks
  5845. axis.ticks = {};
  5846. axis.labelEdge = [];
  5847. // Minor ticks
  5848. axis.minorTicks = {};
  5849. // List of plotLines/Bands
  5850. axis.plotLinesAndBands = [];
  5851. // Alternate bands
  5852. axis.alternateBands = {};
  5853. // Axis metrics
  5854. //axis.left = UNDEFINED;
  5855. //axis.top = UNDEFINED;
  5856. //axis.width = UNDEFINED;
  5857. //axis.height = UNDEFINED;
  5858. //axis.bottom = UNDEFINED;
  5859. //axis.right = UNDEFINED;
  5860. //axis.transA = UNDEFINED;
  5861. //axis.transB = UNDEFINED;
  5862. //axis.oldTransA = UNDEFINED;
  5863. axis.len = 0;
  5864. //axis.oldMin = UNDEFINED;
  5865. //axis.oldMax = UNDEFINED;
  5866. //axis.oldUserMin = UNDEFINED;
  5867. //axis.oldUserMax = UNDEFINED;
  5868. //axis.oldAxisLength = UNDEFINED;
  5869. axis.minRange = axis.userMinRange = options.minRange || options.maxZoom;
  5870. axis.range = options.range;
  5871. axis.offset = options.offset || 0;
  5872. // Dictionary for stacks
  5873. axis.stacks = {};
  5874. axis.oldStacks = {};
  5875. // Min and max in the data
  5876. //axis.dataMin = UNDEFINED,
  5877. //axis.dataMax = UNDEFINED,
  5878. // The axis range
  5879. axis.max = null;
  5880. axis.min = null;
  5881. // User set min and max
  5882. //axis.userMin = UNDEFINED,
  5883. //axis.userMax = UNDEFINED,
  5884. // Crosshair options
  5885. axis.crosshair = pick(options.crosshair, splat(chart.options.tooltip.crosshairs)[isXAxis ? 0 : 1], false);
  5886. // Run Axis
  5887. var eventType,
  5888. events = axis.options.events;
  5889. // Register
  5890. if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update()
  5891. if (isXAxis && !this.isColorAxis) { // #2713
  5892. chart.axes.splice(chart.xAxis.length, 0, axis);
  5893. } else {
  5894. chart.axes.push(axis);
  5895. }
  5896. chart[axis.coll].push(axis);
  5897. }
  5898. axis.series = axis.series || []; // populated by Series
  5899. // inverted charts have reversed xAxes as default
  5900. if (chart.inverted && isXAxis && axis.reversed === UNDEFINED) {
  5901. axis.reversed = true;
  5902. }
  5903. axis.removePlotBand = axis.removePlotBandOrLine;
  5904. axis.removePlotLine = axis.removePlotBandOrLine;
  5905. // register event listeners
  5906. for (eventType in events) {
  5907. addEvent(axis, eventType, events[eventType]);
  5908. }
  5909. // extend logarithmic axis
  5910. if (axis.isLog) {
  5911. axis.val2lin = log2lin;
  5912. axis.lin2val = lin2log;
  5913. }
  5914. },
  5915. /**
  5916. * Merge and set options
  5917. */
  5918. setOptions: function (userOptions) {
  5919. this.options = merge(
  5920. this.defaultOptions,
  5921. this.isXAxis ? {} : this.defaultYAxisOptions,
  5922. [this.defaultTopAxisOptions, this.defaultRightAxisOptions,
  5923. this.defaultBottomAxisOptions, this.defaultLeftAxisOptions][this.side],
  5924. merge(
  5925. defaultOptions[this.coll], // if set in setOptions (#1053)
  5926. userOptions
  5927. )
  5928. );
  5929. },
  5930. /**
  5931. * The default label formatter. The context is a special config object for the label.
  5932. */
  5933. defaultLabelFormatter: function () {
  5934. var axis = this.axis,
  5935. value = this.value,
  5936. categories = axis.categories,
  5937. dateTimeLabelFormat = this.dateTimeLabelFormat,
  5938. numericSymbols = defaultOptions.lang.numericSymbols,
  5939. i = numericSymbols && numericSymbols.length,
  5940. multi,
  5941. ret,
  5942. formatOption = axis.options.labels.format,
  5943. // make sure the same symbol is added for all labels on a linear axis
  5944. numericSymbolDetector = axis.isLog ? value : axis.tickInterval;
  5945. if (formatOption) {
  5946. ret = format(formatOption, this);
  5947. } else if (categories) {
  5948. ret = value;
  5949. } else if (dateTimeLabelFormat) { // datetime axis
  5950. ret = dateFormat(dateTimeLabelFormat, value);
  5951. } else if (i && numericSymbolDetector >= 1000) {
  5952. // Decide whether we should add a numeric symbol like k (thousands) or M (millions).
  5953. // If we are to enable this in tooltip or other places as well, we can move this
  5954. // logic to the numberFormatter and enable it by a parameter.
  5955. while (i-- && ret === UNDEFINED) {
  5956. multi = Math.pow(1000, i + 1);
  5957. if (numericSymbolDetector >= multi && numericSymbols[i] !== null) {
  5958. ret = Highcharts.numberFormat(value / multi, -1) + numericSymbols[i];
  5959. }
  5960. }
  5961. }
  5962. if (ret === UNDEFINED) {
  5963. if (mathAbs(value) >= 10000) { // add thousands separators
  5964. ret = Highcharts.numberFormat(value, 0);
  5965. } else { // small numbers
  5966. ret = Highcharts.numberFormat(value, -1, UNDEFINED, ''); // #2466
  5967. }
  5968. }
  5969. return ret;
  5970. },
  5971. /**
  5972. * Get the minimum and maximum for the series of each axis
  5973. */
  5974. getSeriesExtremes: function () {
  5975. var axis = this,
  5976. chart = axis.chart;
  5977. axis.hasVisibleSeries = false;
  5978. // Reset properties in case we're redrawing (#3353)
  5979. axis.dataMin = axis.dataMax = axis.ignoreMinPadding = axis.ignoreMaxPadding = null;
  5980. if (axis.buildStacks) {
  5981. axis.buildStacks();
  5982. }
  5983. // loop through this axis' series
  5984. each(axis.series, function (series) {
  5985. if (series.visible || !chart.options.chart.ignoreHiddenSeries) {
  5986. var seriesOptions = series.options,
  5987. xData,
  5988. threshold = seriesOptions.threshold,
  5989. seriesDataMin,
  5990. seriesDataMax;
  5991. axis.hasVisibleSeries = true;
  5992. // Validate threshold in logarithmic axes
  5993. if (axis.isLog && threshold <= 0) {
  5994. threshold = null;
  5995. }
  5996. // Get dataMin and dataMax for X axes
  5997. if (axis.isXAxis) {
  5998. xData = series.xData;
  5999. if (xData.length) {
  6000. axis.dataMin = mathMin(pick(axis.dataMin, xData[0]), arrayMin(xData));
  6001. axis.dataMax = mathMax(pick(axis.dataMax, xData[0]), arrayMax(xData));
  6002. }
  6003. // Get dataMin and dataMax for Y axes, as well as handle stacking and processed data
  6004. } else {
  6005. // Get this particular series extremes
  6006. series.getExtremes();
  6007. seriesDataMax = series.dataMax;
  6008. seriesDataMin = series.dataMin;
  6009. // Get the dataMin and dataMax so far. If percentage is used, the min and max are
  6010. // always 0 and 100. If seriesDataMin and seriesDataMax is null, then series
  6011. // doesn't have active y data, we continue with nulls
  6012. if (defined(seriesDataMin) && defined(seriesDataMax)) {
  6013. axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin);
  6014. axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax);
  6015. }
  6016. // Adjust to threshold
  6017. if (defined(threshold)) {
  6018. if (axis.dataMin >= threshold) {
  6019. axis.dataMin = threshold;
  6020. axis.ignoreMinPadding = true;
  6021. } else if (axis.dataMax < threshold) {
  6022. axis.dataMax = threshold;
  6023. axis.ignoreMaxPadding = true;
  6024. }
  6025. }
  6026. }
  6027. }
  6028. });
  6029. },
  6030. /**
  6031. * Translate from axis value to pixel position on the chart, or back
  6032. *
  6033. */
  6034. translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacement) {
  6035. var axis = this,
  6036. sign = 1,
  6037. cvsOffset = 0,
  6038. localA = old ? axis.oldTransA : axis.transA,
  6039. localMin = old ? axis.oldMin : axis.min,
  6040. returnValue,
  6041. minPixelPadding = axis.minPixelPadding,
  6042. doPostTranslate = (axis.doPostTranslate || (axis.isLog && handleLog)) && axis.lin2val;
  6043. if (!localA) {
  6044. localA = axis.transA;
  6045. }
  6046. // In vertical axes, the canvas coordinates start from 0 at the top like in
  6047. // SVG.
  6048. if (cvsCoord) {
  6049. sign *= -1; // canvas coordinates inverts the value
  6050. cvsOffset = axis.len;
  6051. }
  6052. // Handle reversed axis
  6053. if (axis.reversed) {
  6054. sign *= -1;
  6055. cvsOffset -= sign * (axis.sector || axis.len);
  6056. }
  6057. // From pixels to value
  6058. if (backwards) { // reverse translation
  6059. val = val * sign + cvsOffset;
  6060. val -= minPixelPadding;
  6061. returnValue = val / localA + localMin; // from chart pixel to value
  6062. if (doPostTranslate) { // log and ordinal axes
  6063. returnValue = axis.lin2val(returnValue);
  6064. }
  6065. // From value to pixels
  6066. } else {
  6067. if (doPostTranslate) { // log and ordinal axes
  6068. val = axis.val2lin(val);
  6069. }
  6070. if (pointPlacement === 'between') {
  6071. pointPlacement = 0.5;
  6072. }
  6073. returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) +
  6074. (isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0);
  6075. }
  6076. return returnValue;
  6077. },
  6078. /**
  6079. * Utility method to translate an axis value to pixel position.
  6080. * @param {Number} value A value in terms of axis units
  6081. * @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart
  6082. * or just the axis/pane itself.
  6083. */
  6084. toPixels: function (value, paneCoordinates) {
  6085. return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos);
  6086. },
  6087. /*
  6088. * Utility method to translate a pixel position in to an axis value
  6089. * @param {Number} pixel The pixel value coordinate
  6090. * @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the
  6091. * axis/pane itself.
  6092. */
  6093. toValue: function (pixel, paneCoordinates) {
  6094. return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true);
  6095. },
  6096. /**
  6097. * Create the path for a plot line that goes from the given value on
  6098. * this axis, across the plot to the opposite side
  6099. * @param {Number} value
  6100. * @param {Number} lineWidth Used for calculation crisp line
  6101. * @param {Number] old Use old coordinates (for resizing and rescaling)
  6102. */
  6103. getPlotLinePath: function (value, lineWidth, old, force, translatedValue) {
  6104. var axis = this,
  6105. chart = axis.chart,
  6106. axisLeft = axis.left,
  6107. axisTop = axis.top,
  6108. x1,
  6109. y1,
  6110. x2,
  6111. y2,
  6112. cHeight = (old && chart.oldChartHeight) || chart.chartHeight,
  6113. cWidth = (old && chart.oldChartWidth) || chart.chartWidth,
  6114. skip,
  6115. transB = axis.transB,
  6116. /**
  6117. * Check if x is between a and b. If not, either move to a/b or skip,
  6118. * depending on the force parameter.
  6119. */
  6120. between = function (x, a, b) {
  6121. if (x < a || x > b) {
  6122. if (force) {
  6123. x = mathMin(mathMax(a, x), b);
  6124. } else {
  6125. skip = true;
  6126. }
  6127. }
  6128. return x;
  6129. };
  6130. translatedValue = pick(translatedValue, axis.translate(value, null, null, old));
  6131. x1 = x2 = mathRound(translatedValue + transB);
  6132. y1 = y2 = mathRound(cHeight - translatedValue - transB);
  6133. if (isNaN(translatedValue)) { // no min or max
  6134. skip = true;
  6135. } else if (axis.horiz) {
  6136. y1 = axisTop;
  6137. y2 = cHeight - axis.bottom;
  6138. x1 = x2 = between(x1, axisLeft, axisLeft + axis.width);
  6139. } else {
  6140. x1 = axisLeft;
  6141. x2 = cWidth - axis.right;
  6142. y1 = y2 = between(y1, axisTop, axisTop + axis.height);
  6143. }
  6144. return skip && !force ?
  6145. null :
  6146. chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 1);
  6147. },
  6148. /**
  6149. * Set the tick positions of a linear axis to round values like whole tens or every five.
  6150. */
  6151. getLinearTickPositions: function (tickInterval, min, max) {
  6152. var pos,
  6153. lastPos,
  6154. roundedMin = correctFloat(mathFloor(min / tickInterval) * tickInterval),
  6155. roundedMax = correctFloat(mathCeil(max / tickInterval) * tickInterval),
  6156. tickPositions = [];
  6157. // For single points, add a tick regardless of the relative position (#2662)
  6158. if (min === max && isNumber(min)) {
  6159. return [min];
  6160. }
  6161. // Populate the intermediate values
  6162. pos = roundedMin;
  6163. while (pos <= roundedMax) {
  6164. // Place the tick on the rounded value
  6165. tickPositions.push(pos);
  6166. // Always add the raw tickInterval, not the corrected one.
  6167. pos = correctFloat(pos + tickInterval);
  6168. // If the interval is not big enough in the current min - max range to actually increase
  6169. // the loop variable, we need to break out to prevent endless loop. Issue #619
  6170. if (pos === lastPos) {
  6171. break;
  6172. }
  6173. // Record the last value
  6174. lastPos = pos;
  6175. }
  6176. return tickPositions;
  6177. },
  6178. /**
  6179. * Return the minor tick positions. For logarithmic axes, reuse the same logic
  6180. * as for major ticks.
  6181. */
  6182. getMinorTickPositions: function () {
  6183. var axis = this,
  6184. options = axis.options,
  6185. tickPositions = axis.tickPositions,
  6186. minorTickInterval = axis.minorTickInterval,
  6187. minorTickPositions = [],
  6188. pos,
  6189. i,
  6190. min = axis.min,
  6191. max = axis.max,
  6192. range = max - min,
  6193. len;
  6194. // If minor ticks get too dense, they are hard to read, and may cause long running script. So we don't draw them.
  6195. if (range && range / minorTickInterval < axis.len / 3) { // #3875
  6196. if (axis.isLog) {
  6197. len = tickPositions.length;
  6198. for (i = 1; i < len; i++) {
  6199. minorTickPositions = minorTickPositions.concat(
  6200. axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true)
  6201. );
  6202. }
  6203. } else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314
  6204. minorTickPositions = minorTickPositions.concat(
  6205. axis.getTimeTicks(
  6206. axis.normalizeTimeTickInterval(minorTickInterval),
  6207. min,
  6208. max,
  6209. options.startOfWeek
  6210. )
  6211. );
  6212. } else {
  6213. for (pos = min + (tickPositions[0] - min) % minorTickInterval; pos <= max; pos += minorTickInterval) {
  6214. minorTickPositions.push(pos);
  6215. }
  6216. }
  6217. }
  6218. axis.trimTicks(minorTickPositions); // #3652 #3743
  6219. return minorTickPositions;
  6220. },
  6221. /**
  6222. * Adjust the min and max for the minimum range. Keep in mind that the series data is
  6223. * not yet processed, so we don't have information on data cropping and grouping, or
  6224. * updated axis.pointRange or series.pointRange. The data can't be processed until
  6225. * we have finally established min and max.
  6226. */
  6227. adjustForMinRange: function () {
  6228. var axis = this,
  6229. options = axis.options,
  6230. min = axis.min,
  6231. max = axis.max,
  6232. zoomOffset,
  6233. spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange,
  6234. closestDataRange,
  6235. i,
  6236. distance,
  6237. xData,
  6238. loopLength,
  6239. minArgs,
  6240. maxArgs;
  6241. // Set the automatic minimum range based on the closest point distance
  6242. if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) {
  6243. if (defined(options.min) || defined(options.max)) {
  6244. axis.minRange = null; // don't do this again
  6245. } else {
  6246. // Find the closest distance between raw data points, as opposed to
  6247. // closestPointRange that applies to processed points (cropped and grouped)
  6248. each(axis.series, function (series) {
  6249. xData = series.xData;
  6250. loopLength = series.xIncrement ? 1 : xData.length - 1;
  6251. for (i = loopLength; i > 0; i--) {
  6252. distance = xData[i] - xData[i - 1];
  6253. if (closestDataRange === UNDEFINED || distance < closestDataRange) {
  6254. closestDataRange = distance;
  6255. }
  6256. }
  6257. });
  6258. axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin);
  6259. }
  6260. }
  6261. // if minRange is exceeded, adjust
  6262. if (max - min < axis.minRange) {
  6263. var minRange = axis.minRange;
  6264. zoomOffset = (minRange - max + min) / 2;
  6265. // if min and max options have been set, don't go beyond it
  6266. minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)];
  6267. if (spaceAvailable) { // if space is available, stay within the data range
  6268. minArgs[2] = axis.dataMin;
  6269. }
  6270. min = arrayMax(minArgs);
  6271. maxArgs = [min + minRange, pick(options.max, min + minRange)];
  6272. if (spaceAvailable) { // if space is availabe, stay within the data range
  6273. maxArgs[2] = axis.dataMax;
  6274. }
  6275. max = arrayMin(maxArgs);
  6276. // now if the max is adjusted, adjust the min back
  6277. if (max - min < minRange) {
  6278. minArgs[0] = max - minRange;
  6279. minArgs[1] = pick(options.min, max - minRange);
  6280. min = arrayMax(minArgs);
  6281. }
  6282. }
  6283. // Record modified extremes
  6284. axis.min = min;
  6285. axis.max = max;
  6286. },
  6287. /**
  6288. * Update translation information
  6289. */
  6290. setAxisTranslation: function (saveOld) {
  6291. var axis = this,
  6292. range = axis.max - axis.min,
  6293. pointRange = axis.axisPointRange || 0,
  6294. closestPointRange,
  6295. minPointOffset = 0,
  6296. pointRangePadding = 0,
  6297. linkedParent = axis.linkedParent,
  6298. ordinalCorrection,
  6299. hasCategories = !!axis.categories,
  6300. transA = axis.transA,
  6301. isXAxis = axis.isXAxis;
  6302. // Adjust translation for padding. Y axis with categories need to go through the same (#1784).
  6303. if (isXAxis || hasCategories || pointRange) {
  6304. if (linkedParent) {
  6305. minPointOffset = linkedParent.minPointOffset;
  6306. pointRangePadding = linkedParent.pointRangePadding;
  6307. } else {
  6308. each(axis.series, function (series) {
  6309. var seriesPointRange = hasCategories ? 1 : (isXAxis ? series.pointRange : (axis.axisPointRange || 0)), // #2806
  6310. pointPlacement = series.options.pointPlacement,
  6311. seriesClosestPointRange = series.closestPointRange;
  6312. if (seriesPointRange > range) { // #1446
  6313. seriesPointRange = 0;
  6314. }
  6315. pointRange = mathMax(pointRange, seriesPointRange);
  6316. if (!axis.single) {
  6317. // minPointOffset is the value padding to the left of the axis in order to make
  6318. // room for points with a pointRange, typically columns. When the pointPlacement option
  6319. // is 'between' or 'on', this padding does not apply.
  6320. minPointOffset = mathMax(
  6321. minPointOffset,
  6322. isString(pointPlacement) ? 0 : seriesPointRange / 2
  6323. );
  6324. // Determine the total padding needed to the length of the axis to make room for the
  6325. // pointRange. If the series' pointPlacement is 'on', no padding is added.
  6326. pointRangePadding = mathMax(
  6327. pointRangePadding,
  6328. pointPlacement === 'on' ? 0 : seriesPointRange
  6329. );
  6330. }
  6331. // Set the closestPointRange
  6332. if (!series.noSharedTooltip && defined(seriesClosestPointRange)) {
  6333. closestPointRange = defined(closestPointRange) ?
  6334. mathMin(closestPointRange, seriesClosestPointRange) :
  6335. seriesClosestPointRange;
  6336. }
  6337. });
  6338. }
  6339. // Record minPointOffset and pointRangePadding
  6340. ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853
  6341. axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection;
  6342. axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection;
  6343. // pointRange means the width reserved for each point, like in a column chart
  6344. axis.pointRange = mathMin(pointRange, range);
  6345. // closestPointRange means the closest distance between points. In columns
  6346. // it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange
  6347. // is some other value
  6348. if (isXAxis) {
  6349. axis.closestPointRange = closestPointRange;
  6350. }
  6351. }
  6352. // Secondary values
  6353. if (saveOld) {
  6354. axis.oldTransA = transA;
  6355. }
  6356. axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1);
  6357. axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend
  6358. axis.minPixelPadding = transA * minPointOffset;
  6359. },
  6360. /**
  6361. * Set the tick positions to round values and optionally extend the extremes
  6362. * to the nearest tick
  6363. */
  6364. setTickInterval: function (secondPass) {
  6365. var axis = this,
  6366. chart = axis.chart,
  6367. options = axis.options,
  6368. isLog = axis.isLog,
  6369. isDatetimeAxis = axis.isDatetimeAxis,
  6370. isXAxis = axis.isXAxis,
  6371. isLinked = axis.isLinked,
  6372. maxPadding = options.maxPadding,
  6373. minPadding = options.minPadding,
  6374. length,
  6375. linkedParentExtremes,
  6376. tickIntervalOption = options.tickInterval,
  6377. minTickInterval,
  6378. tickPixelIntervalOption = options.tickPixelInterval,
  6379. categories = axis.categories;
  6380. if (!isDatetimeAxis && !categories && !isLinked) {
  6381. this.getTickAmount();
  6382. }
  6383. // linked axis gets the extremes from the parent axis
  6384. if (isLinked) {
  6385. axis.linkedParent = chart[axis.coll][options.linkedTo];
  6386. linkedParentExtremes = axis.linkedParent.getExtremes();
  6387. axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin);
  6388. axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax);
  6389. if (options.type !== axis.linkedParent.options.type) {
  6390. error(11, 1); // Can't link axes of different type
  6391. }
  6392. } else { // initial min and max from the extreme data values
  6393. axis.min = pick(axis.userMin, options.min, axis.dataMin);
  6394. axis.max = pick(axis.userMax, options.max, axis.dataMax);
  6395. }
  6396. if (isLog) {
  6397. if (!secondPass && mathMin(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978
  6398. error(10, 1); // Can't plot negative values on log axis
  6399. }
  6400. axis.min = correctFloat(log2lin(axis.min)); // correctFloat cures #934
  6401. axis.max = correctFloat(log2lin(axis.max));
  6402. }
  6403. // handle zoomed range
  6404. if (axis.range && defined(axis.max)) {
  6405. axis.userMin = axis.min = mathMax(axis.min, axis.max - axis.range); // #618
  6406. axis.userMax = axis.max;
  6407. axis.range = null; // don't use it when running setExtremes
  6408. }
  6409. // Hook for adjusting this.min and this.max. Used by bubble series.
  6410. if (axis.beforePadding) {
  6411. axis.beforePadding();
  6412. }
  6413. // adjust min and max for the minimum range
  6414. axis.adjustForMinRange();
  6415. // Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding
  6416. // into account, we do this after computing tick interval (#1337).
  6417. if (!categories && !axis.axisPointRange && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) {
  6418. length = axis.max - axis.min;
  6419. if (length) {
  6420. if (!defined(options.min) && !defined(axis.userMin) && minPadding && (axis.dataMin < 0 || !axis.ignoreMinPadding)) {
  6421. axis.min -= length * minPadding;
  6422. }
  6423. if (!defined(options.max) && !defined(axis.userMax) && maxPadding && (axis.dataMax > 0 || !axis.ignoreMaxPadding)) {
  6424. axis.max += length * maxPadding;
  6425. }
  6426. }
  6427. }
  6428. // Stay within floor and ceiling
  6429. if (isNumber(options.floor)) {
  6430. axis.min = mathMax(axis.min, options.floor);
  6431. }
  6432. if (isNumber(options.ceiling)) {
  6433. axis.max = mathMin(axis.max, options.ceiling);
  6434. }
  6435. // get tickInterval
  6436. if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) {
  6437. axis.tickInterval = 1;
  6438. } else if (isLinked && !tickIntervalOption &&
  6439. tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) {
  6440. axis.tickInterval = axis.linkedParent.tickInterval;
  6441. } else {
  6442. axis.tickInterval = pick(
  6443. tickIntervalOption,
  6444. this.tickAmount ? ((axis.max - axis.min) / mathMax(this.tickAmount - 1, 1)) : undefined,
  6445. categories ? // for categoried axis, 1 is default, for linear axis use tickPix
  6446. 1 :
  6447. // don't let it be more than the data range
  6448. (axis.max - axis.min) * tickPixelIntervalOption / mathMax(axis.len, tickPixelIntervalOption)
  6449. );
  6450. }
  6451. // Now we're finished detecting min and max, crop and group series data. This
  6452. // is in turn needed in order to find tick positions in ordinal axes.
  6453. if (isXAxis && !secondPass) {
  6454. each(axis.series, function (series) {
  6455. series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax);
  6456. });
  6457. }
  6458. // set the translation factor used in translate function
  6459. axis.setAxisTranslation(true);
  6460. // hook for ordinal axes and radial axes
  6461. if (axis.beforeSetTickPositions) {
  6462. axis.beforeSetTickPositions();
  6463. }
  6464. // hook for extensions, used in Highstock ordinal axes
  6465. if (axis.postProcessTickInterval) {
  6466. axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval);
  6467. }
  6468. // In column-like charts, don't cramp in more ticks than there are points (#1943)
  6469. if (axis.pointRange) {
  6470. axis.tickInterval = mathMax(axis.pointRange, axis.tickInterval);
  6471. }
  6472. // Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined.
  6473. minTickInterval = pick(options.minTickInterval, axis.isDatetimeAxis && axis.closestPointRange);
  6474. if (!tickIntervalOption && axis.tickInterval < minTickInterval) {
  6475. axis.tickInterval = minTickInterval;
  6476. }
  6477. // for linear axes, get magnitude and normalize the interval
  6478. if (!isDatetimeAxis && !isLog) { // linear
  6479. if (!tickIntervalOption) {
  6480. axis.tickInterval = normalizeTickInterval(
  6481. axis.tickInterval,
  6482. null,
  6483. getMagnitude(axis.tickInterval),
  6484. // If the tick interval is between 0.5 and 5 and the axis max is in the order of
  6485. // thousands, chances are we are dealing with years. Don't allow decimals. #3363.
  6486. pick(options.allowDecimals, !(axis.tickInterval > 0.5 && axis.tickInterval < 5 && axis.max > 1000 && axis.max < 9999)),
  6487. !!this.tickAmount
  6488. );
  6489. }
  6490. }
  6491. // Prevent ticks from getting so close that we can't draw the labels
  6492. if (!this.tickAmount && this.len) { // Color axis with disabled legend has no length
  6493. axis.tickInterval = axis.unsquish();
  6494. }
  6495. this.setTickPositions();
  6496. },
  6497. /**
  6498. * Now we have computed the normalized tickInterval, get the tick positions
  6499. */
  6500. setTickPositions: function () {
  6501. var options = this.options,
  6502. tickPositions,
  6503. tickPositionsOption = options.tickPositions,
  6504. tickPositioner = options.tickPositioner,
  6505. startOnTick = options.startOnTick,
  6506. endOnTick = options.endOnTick,
  6507. single;
  6508. // Set the tickmarkOffset
  6509. this.tickmarkOffset = (this.categories && options.tickmarkPlacement === 'between' &&
  6510. this.tickInterval === 1) ? 0.5 : 0; // #3202
  6511. // get minorTickInterval
  6512. this.minorTickInterval = options.minorTickInterval === 'auto' && this.tickInterval ?
  6513. this.tickInterval / 5 : options.minorTickInterval;
  6514. // Find the tick positions
  6515. this.tickPositions = tickPositions = options.tickPositions && options.tickPositions.slice(); // Work on a copy (#1565)
  6516. if (!tickPositions) {
  6517. if (this.isDatetimeAxis) {
  6518. tickPositions = this.getTimeTicks(
  6519. this.normalizeTimeTickInterval(this.tickInterval, options.units),
  6520. this.min,
  6521. this.max,
  6522. options.startOfWeek,
  6523. this.ordinalPositions,
  6524. this.closestPointRange,
  6525. true
  6526. );
  6527. } else if (this.isLog) {
  6528. tickPositions = this.getLogTickPositions(this.tickInterval, this.min, this.max);
  6529. } else {
  6530. tickPositions = this.getLinearTickPositions(this.tickInterval, this.min, this.max);
  6531. }
  6532. this.tickPositions = tickPositions;
  6533. // Run the tick positioner callback, that allows modifying auto tick positions.
  6534. if (tickPositioner) {
  6535. tickPositioner = tickPositioner.apply(this, [this.min, this.max]);
  6536. if (tickPositioner) {
  6537. this.tickPositions = tickPositions = tickPositioner;
  6538. }
  6539. }
  6540. }
  6541. if (!this.isLinked) {
  6542. // reset min/max or remove extremes based on start/end on tick
  6543. this.trimTicks(tickPositions, startOnTick, endOnTick);
  6544. // When there is only one point, or all points have the same value on this axis, then min
  6545. // and max are equal and tickPositions.length is 0 or 1. In this case, add some padding
  6546. // in order to center the point, but leave it with one tick. #1337.
  6547. if (this.min === this.max && defined(this.min) && !this.tickAmount) {
  6548. // Substract half a unit (#2619, #2846, #2515, #3390)
  6549. single = true;
  6550. this.min -= 0.5;
  6551. this.max += 0.5;
  6552. }
  6553. this.single = single;
  6554. if (!tickPositionsOption && !tickPositioner) {
  6555. this.adjustTickAmount();
  6556. }
  6557. }
  6558. },
  6559. /**
  6560. * Handle startOnTick and endOnTick by either adapting to padding min/max or rounded min/max
  6561. */
  6562. trimTicks: function (tickPositions, startOnTick, endOnTick) {
  6563. var roundedMin = tickPositions[0],
  6564. roundedMax = tickPositions[tickPositions.length - 1],
  6565. minPointOffset = this.minPointOffset || 0;
  6566. if (startOnTick) {
  6567. this.min = roundedMin;
  6568. } else if (this.min - minPointOffset > roundedMin) {
  6569. tickPositions.shift();
  6570. }
  6571. if (endOnTick) {
  6572. this.max = roundedMax;
  6573. } else if (this.max + minPointOffset < roundedMax) {
  6574. tickPositions.pop();
  6575. }
  6576. // If no tick are left, set one tick in the middle (#3195)
  6577. if (tickPositions.length === 0 && defined(roundedMin)) {
  6578. tickPositions.push((roundedMax + roundedMin) / 2);
  6579. }
  6580. },
  6581. /**
  6582. * Set the max ticks of either the x and y axis collection
  6583. */
  6584. getTickAmount: function () {
  6585. var others = {}, // Whether there is another axis to pair with this one
  6586. hasOther,
  6587. options = this.options,
  6588. tickAmount = options.tickAmount,
  6589. tickPixelInterval = options.tickPixelInterval;
  6590. if (!defined(options.tickInterval) && this.len < tickPixelInterval && !this.isRadial &&
  6591. !this.isLog && options.startOnTick && options.endOnTick) {
  6592. tickAmount = 2;
  6593. }
  6594. if (!tickAmount && this.chart.options.chart.alignTicks !== false && options.alignTicks !== false) {
  6595. // Check if there are multiple axes in the same pane
  6596. each(this.chart[this.coll], function (axis) {
  6597. var options = axis.options,
  6598. horiz = axis.horiz,
  6599. key = [horiz ? options.left : options.top, horiz ? options.width : options.height, options.pane].join(',');
  6600. if (others[key]) {
  6601. hasOther = true;
  6602. } else {
  6603. others[key] = 1;
  6604. }
  6605. });
  6606. if (hasOther) {
  6607. // Add 1 because 4 tick intervals require 5 ticks (including first and last)
  6608. tickAmount = mathCeil(this.len / tickPixelInterval) + 1;
  6609. }
  6610. }
  6611. // For tick amounts of 2 and 3, compute five ticks and remove the intermediate ones. This
  6612. // prevents the axis from adding ticks that are too far away from the data extremes.
  6613. if (tickAmount < 4) {
  6614. this.finalTickAmt = tickAmount;
  6615. tickAmount = 5;
  6616. }
  6617. this.tickAmount = tickAmount;
  6618. },
  6619. /**
  6620. * When using multiple axes, adjust the number of ticks to match the highest
  6621. * number of ticks in that group
  6622. */
  6623. adjustTickAmount: function () {
  6624. var tickInterval = this.tickInterval,
  6625. tickPositions = this.tickPositions,
  6626. tickAmount = this.tickAmount,
  6627. finalTickAmt = this.finalTickAmt,
  6628. currentTickAmount = tickPositions && tickPositions.length,
  6629. i,
  6630. len;
  6631. if (currentTickAmount < tickAmount) { // TODO: Check #3411
  6632. while (tickPositions.length < tickAmount) {
  6633. tickPositions.push(correctFloat(
  6634. tickPositions[tickPositions.length - 1] + tickInterval
  6635. ));
  6636. }
  6637. this.transA *= (currentTickAmount - 1) / (tickAmount - 1);
  6638. this.max = tickPositions[tickPositions.length - 1];
  6639. // We have too many ticks, run second pass to try to reduce ticks
  6640. } else if (currentTickAmount > tickAmount) {
  6641. this.tickInterval *= 2;
  6642. this.setTickPositions();
  6643. }
  6644. // The finalTickAmt property is set in getTickAmount
  6645. if (defined(finalTickAmt)) {
  6646. i = len = tickPositions.length;
  6647. while (i--) {
  6648. if (
  6649. (finalTickAmt === 3 && i % 2 === 1) || // Remove every other tick
  6650. (finalTickAmt <= 2 && i > 0 && i < len - 1) // Remove all but first and last
  6651. ) {
  6652. tickPositions.splice(i, 1);
  6653. }
  6654. }
  6655. this.finalTickAmt = UNDEFINED;
  6656. }
  6657. },
  6658. /**
  6659. * Set the scale based on data min and max, user set min and max or options
  6660. *
  6661. */
  6662. setScale: function () {
  6663. var axis = this,
  6664. stacks = axis.stacks,
  6665. type,
  6666. i,
  6667. isDirtyData,
  6668. isDirtyAxisLength;
  6669. axis.oldMin = axis.min;
  6670. axis.oldMax = axis.max;
  6671. axis.oldAxisLength = axis.len;
  6672. // set the new axisLength
  6673. axis.setAxisSize();
  6674. //axisLength = horiz ? axisWidth : axisHeight;
  6675. isDirtyAxisLength = axis.len !== axis.oldAxisLength;
  6676. // is there new data?
  6677. each(axis.series, function (series) {
  6678. if (series.isDirtyData || series.isDirty ||
  6679. series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well
  6680. isDirtyData = true;
  6681. }
  6682. });
  6683. // do we really need to go through all this?
  6684. if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw ||
  6685. axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax) {
  6686. // reset stacks
  6687. if (!axis.isXAxis) {
  6688. for (type in stacks) {
  6689. for (i in stacks[type]) {
  6690. stacks[type][i].total = null;
  6691. stacks[type][i].cum = 0;
  6692. }
  6693. }
  6694. }
  6695. axis.forceRedraw = false;
  6696. // get data extremes if needed
  6697. axis.getSeriesExtremes();
  6698. // get fixed positions based on tickInterval
  6699. axis.setTickInterval();
  6700. // record old values to decide whether a rescale is necessary later on (#540)
  6701. axis.oldUserMin = axis.userMin;
  6702. axis.oldUserMax = axis.userMax;
  6703. // Mark as dirty if it is not already set to dirty and extremes have changed. #595.
  6704. if (!axis.isDirty) {
  6705. axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax;
  6706. }
  6707. } else if (!axis.isXAxis) {
  6708. if (axis.oldStacks) {
  6709. stacks = axis.stacks = axis.oldStacks;
  6710. }
  6711. // reset stacks
  6712. for (type in stacks) {
  6713. for (i in stacks[type]) {
  6714. stacks[type][i].cum = stacks[type][i].total;
  6715. }
  6716. }
  6717. }
  6718. },
  6719. /**
  6720. * Set the extremes and optionally redraw
  6721. * @param {Number} newMin
  6722. * @param {Number} newMax
  6723. * @param {Boolean} redraw
  6724. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  6725. * configuration
  6726. * @param {Object} eventArguments
  6727. *
  6728. */
  6729. setExtremes: function (newMin, newMax, redraw, animation, eventArguments) {
  6730. var axis = this,
  6731. chart = axis.chart;
  6732. redraw = pick(redraw, true); // defaults to true
  6733. each(axis.series, function (serie) {
  6734. delete serie.kdTree;
  6735. });
  6736. // Extend the arguments with min and max
  6737. eventArguments = extend(eventArguments, {
  6738. min: newMin,
  6739. max: newMax
  6740. });
  6741. // Fire the event
  6742. fireEvent(axis, 'setExtremes', eventArguments, function () { // the default event handler
  6743. axis.userMin = newMin;
  6744. axis.userMax = newMax;
  6745. axis.eventArgs = eventArguments;
  6746. // Mark for running afterSetExtremes
  6747. axis.isDirtyExtremes = true;
  6748. // redraw
  6749. if (redraw) {
  6750. chart.redraw(animation);
  6751. }
  6752. });
  6753. },
  6754. /**
  6755. * Overridable method for zooming chart. Pulled out in a separate method to allow overriding
  6756. * in stock charts.
  6757. */
  6758. zoom: function (newMin, newMax) {
  6759. var dataMin = this.dataMin,
  6760. dataMax = this.dataMax,
  6761. options = this.options;
  6762. // Prevent pinch zooming out of range. Check for defined is for #1946. #1734.
  6763. if (!this.allowZoomOutside) {
  6764. if (defined(dataMin) && newMin <= mathMin(dataMin, pick(options.min, dataMin))) {
  6765. newMin = UNDEFINED;
  6766. }
  6767. if (defined(dataMax) && newMax >= mathMax(dataMax, pick(options.max, dataMax))) {
  6768. newMax = UNDEFINED;
  6769. }
  6770. }
  6771. // In full view, displaying the reset zoom button is not required
  6772. this.displayBtn = newMin !== UNDEFINED || newMax !== UNDEFINED;
  6773. // Do it
  6774. this.setExtremes(
  6775. newMin,
  6776. newMax,
  6777. false,
  6778. UNDEFINED,
  6779. { trigger: 'zoom' }
  6780. );
  6781. return true;
  6782. },
  6783. /**
  6784. * Update the axis metrics
  6785. */
  6786. setAxisSize: function () {
  6787. var chart = this.chart,
  6788. options = this.options,
  6789. offsetLeft = options.offsetLeft || 0,
  6790. offsetRight = options.offsetRight || 0,
  6791. horiz = this.horiz,
  6792. width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight),
  6793. height = pick(options.height, chart.plotHeight),
  6794. top = pick(options.top, chart.plotTop),
  6795. left = pick(options.left, chart.plotLeft + offsetLeft),
  6796. percentRegex = /%$/;
  6797. // Check for percentage based input values
  6798. if (percentRegex.test(height)) {
  6799. height = parseFloat(height) / 100 * chart.plotHeight;
  6800. }
  6801. if (percentRegex.test(top)) {
  6802. top = parseFloat(top) / 100 * chart.plotHeight + chart.plotTop;
  6803. }
  6804. // Expose basic values to use in Series object and navigator
  6805. this.left = left;
  6806. this.top = top;
  6807. this.width = width;
  6808. this.height = height;
  6809. this.bottom = chart.chartHeight - height - top;
  6810. this.right = chart.chartWidth - width - left;
  6811. // Direction agnostic properties
  6812. this.len = mathMax(horiz ? width : height, 0); // mathMax fixes #905
  6813. this.pos = horiz ? left : top; // distance from SVG origin
  6814. },
  6815. /**
  6816. * Get the actual axis extremes
  6817. */
  6818. getExtremes: function () {
  6819. var axis = this,
  6820. isLog = axis.isLog;
  6821. return {
  6822. min: isLog ? correctFloat(lin2log(axis.min)) : axis.min,
  6823. max: isLog ? correctFloat(lin2log(axis.max)) : axis.max,
  6824. dataMin: axis.dataMin,
  6825. dataMax: axis.dataMax,
  6826. userMin: axis.userMin,
  6827. userMax: axis.userMax
  6828. };
  6829. },
  6830. /**
  6831. * Get the zero plane either based on zero or on the min or max value.
  6832. * Used in bar and area plots
  6833. */
  6834. getThreshold: function (threshold) {
  6835. var axis = this,
  6836. isLog = axis.isLog;
  6837. var realMin = isLog ? lin2log(axis.min) : axis.min,
  6838. realMax = isLog ? lin2log(axis.max) : axis.max;
  6839. if (realMin > threshold || threshold === null) {
  6840. threshold = realMin;
  6841. } else if (realMax < threshold) {
  6842. threshold = realMax;
  6843. }
  6844. return axis.translate(threshold, 0, 1, 0, 1);
  6845. },
  6846. /**
  6847. * Compute auto alignment for the axis label based on which side the axis is on
  6848. * and the given rotation for the label
  6849. */
  6850. autoLabelAlign: function (rotation) {
  6851. var ret,
  6852. angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360;
  6853. if (angle > 15 && angle < 165) {
  6854. ret = 'right';
  6855. } else if (angle > 195 && angle < 345) {
  6856. ret = 'left';
  6857. } else {
  6858. ret = 'center';
  6859. }
  6860. return ret;
  6861. },
  6862. /**
  6863. * Prevent the ticks from getting so close we can't draw the labels. On a horizontal
  6864. * axis, this is handled by rotating the labels, removing ticks and adding ellipsis.
  6865. * On a vertical axis remove ticks and add ellipsis.
  6866. */
  6867. unsquish: function () {
  6868. var chart = this.chart,
  6869. ticks = this.ticks,
  6870. labelOptions = this.options.labels,
  6871. horiz = this.horiz,
  6872. tickInterval = this.tickInterval,
  6873. newTickInterval = tickInterval,
  6874. slotSize = this.len / (((this.categories ? 1 : 0) + this.max - this.min) / tickInterval),
  6875. rotation,
  6876. rotationOption = labelOptions.rotation,
  6877. labelMetrics = chart.renderer.fontMetrics(labelOptions.style.fontSize, ticks[0] && ticks[0].label),
  6878. step,
  6879. bestScore = Number.MAX_VALUE,
  6880. autoRotation,
  6881. // Return the multiple of tickInterval that is needed to avoid collision
  6882. getStep = function (spaceNeeded) {
  6883. var step = spaceNeeded / (slotSize || 1);
  6884. step = step > 1 ? mathCeil(step) : 1;
  6885. return step * tickInterval;
  6886. };
  6887. if (horiz) {
  6888. autoRotation = defined(rotationOption) ?
  6889. [rotationOption] :
  6890. slotSize < pick(labelOptions.autoRotationLimit, 80) && !labelOptions.staggerLines && !labelOptions.step && labelOptions.autoRotation;
  6891. if (autoRotation) {
  6892. // Loop over the given autoRotation options, and determine which gives the best score. The
  6893. // best score is that with the lowest number of steps and a rotation closest to horizontal.
  6894. each(autoRotation, function (rot) {
  6895. var score;
  6896. if (rot === rotationOption || (rot && rot >= -90 && rot <= 90)) { // #3891
  6897. step = getStep(mathAbs(labelMetrics.h / mathSin(deg2rad * rot)));
  6898. score = step + mathAbs(rot / 360);
  6899. if (score < bestScore) {
  6900. bestScore = score;
  6901. rotation = rot;
  6902. newTickInterval = step;
  6903. }
  6904. }
  6905. });
  6906. }
  6907. } else {
  6908. newTickInterval = getStep(labelMetrics.h);
  6909. }
  6910. this.autoRotation = autoRotation;
  6911. this.labelRotation = rotation;
  6912. return newTickInterval;
  6913. },
  6914. renderUnsquish: function () {
  6915. var chart = this.chart,
  6916. renderer = chart.renderer,
  6917. tickPositions = this.tickPositions,
  6918. ticks = this.ticks,
  6919. labelOptions = this.options.labels,
  6920. horiz = this.horiz,
  6921. margin = chart.margin,
  6922. slotWidth = this.slotWidth = (horiz && !labelOptions.step && !labelOptions.rotation &&
  6923. ((this.staggerLines || 1) * chart.plotWidth) / tickPositions.length) ||
  6924. (!horiz && ((margin[3] && (margin[3] - chart.spacing[3])) || chart.chartWidth * 0.33)), // #1580, #1931,
  6925. innerWidth = mathMax(1, mathRound(slotWidth - 2 * (labelOptions.padding || 5))),
  6926. attr = {},
  6927. labelMetrics = renderer.fontMetrics(labelOptions.style.fontSize, ticks[0] && ticks[0].label),
  6928. css,
  6929. labelLength = 0,
  6930. label,
  6931. i,
  6932. pos;
  6933. // Set rotation option unless it is "auto", like in gauges
  6934. if (!isString(labelOptions.rotation)) {
  6935. attr.rotation = labelOptions.rotation;
  6936. }
  6937. // Handle auto rotation on horizontal axis
  6938. if (this.autoRotation) {
  6939. // Get the longest label length
  6940. each(tickPositions, function (tick) {
  6941. tick = ticks[tick];
  6942. if (tick && tick.labelLength > labelLength) {
  6943. labelLength = tick.labelLength;
  6944. }
  6945. });
  6946. // Apply rotation only if the label is too wide for the slot, and
  6947. // the label is wider than its height.
  6948. if (labelLength > innerWidth && labelLength > labelMetrics.h) {
  6949. attr.rotation = this.labelRotation;
  6950. } else {
  6951. this.labelRotation = 0;
  6952. }
  6953. // Handle word-wrap or ellipsis on vertical axis
  6954. } else if (slotWidth) {
  6955. // For word-wrap or ellipsis
  6956. css = { width: innerWidth + PX, textOverflow: 'clip' };
  6957. // On vertical axis, only allow word wrap if there is room for more lines.
  6958. i = tickPositions.length;
  6959. while (!horiz && i--) {
  6960. pos = tickPositions[i];
  6961. label = ticks[pos].label;
  6962. if (label) {
  6963. // Reset ellipsis in order to get the correct bounding box (#4070)
  6964. if (label.styles.textOverflow === 'ellipsis') {
  6965. label.css({ textOverflow: 'clip' });
  6966. }
  6967. if (label.getBBox().height > this.len / tickPositions.length - (labelMetrics.h - labelMetrics.f)) {
  6968. label.specCss = { textOverflow: 'ellipsis' };
  6969. }
  6970. }
  6971. }
  6972. }
  6973. // Add ellipsis if the label length is significantly longer than ideal
  6974. if (attr.rotation) {
  6975. css = {
  6976. width: (labelLength > chart.chartHeight * 0.5 ? chart.chartHeight * 0.33 : chart.chartHeight) + PX,
  6977. textOverflow: 'ellipsis'
  6978. };
  6979. }
  6980. // Set the explicit or automatic label alignment
  6981. this.labelAlign = attr.align = labelOptions.align || this.autoLabelAlign(this.labelRotation);
  6982. // Apply general and specific CSS
  6983. each(tickPositions, function (pos) {
  6984. var tick = ticks[pos],
  6985. label = tick && tick.label;
  6986. if (label) {
  6987. if (css) {
  6988. label.css(merge(css, label.specCss));
  6989. }
  6990. delete label.specCss;
  6991. label.attr(attr);
  6992. tick.rotation = attr.rotation;
  6993. }
  6994. });
  6995. // TODO: Why not part of getLabelPosition?
  6996. this.tickRotCorr = renderer.rotCorr(labelMetrics.b, this.labelRotation || 0, this.side === 2);
  6997. },
  6998. /**
  6999. * Render the tick labels to a preliminary position to get their sizes
  7000. */
  7001. getOffset: function () {
  7002. var axis = this,
  7003. chart = axis.chart,
  7004. renderer = chart.renderer,
  7005. options = axis.options,
  7006. tickPositions = axis.tickPositions,
  7007. ticks = axis.ticks,
  7008. horiz = axis.horiz,
  7009. side = axis.side,
  7010. invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side,
  7011. hasData,
  7012. showAxis,
  7013. titleOffset = 0,
  7014. titleOffsetOption,
  7015. titleMargin = 0,
  7016. axisTitleOptions = options.title,
  7017. labelOptions = options.labels,
  7018. labelOffset = 0, // reset
  7019. labelOffsetPadded,
  7020. axisOffset = chart.axisOffset,
  7021. clipOffset = chart.clipOffset,
  7022. directionFactor = [-1, 1, 1, -1][side],
  7023. n,
  7024. lineHeightCorrection;
  7025. // For reuse in Axis.render
  7026. axis.hasData = hasData = (axis.hasVisibleSeries || (defined(axis.min) && defined(axis.max) && !!tickPositions));
  7027. axis.showAxis = showAxis = hasData || pick(options.showEmpty, true);
  7028. // Set/reset staggerLines
  7029. axis.staggerLines = axis.horiz && labelOptions.staggerLines;
  7030. // Create the axisGroup and gridGroup elements on first iteration
  7031. if (!axis.axisGroup) {
  7032. axis.gridGroup = renderer.g('grid')
  7033. .attr({ zIndex: options.gridZIndex || 1 })
  7034. .add();
  7035. axis.axisGroup = renderer.g('axis')
  7036. .attr({ zIndex: options.zIndex || 2 })
  7037. .add();
  7038. axis.labelGroup = renderer.g('axis-labels')
  7039. .attr({ zIndex: labelOptions.zIndex || 7 })
  7040. .addClass(PREFIX + axis.coll.toLowerCase() + '-labels')
  7041. .add();
  7042. }
  7043. if (hasData || axis.isLinked) {
  7044. // Generate ticks
  7045. each(tickPositions, function (pos) {
  7046. if (!ticks[pos]) {
  7047. ticks[pos] = new Tick(axis, pos);
  7048. } else {
  7049. ticks[pos].addLabel(); // update labels depending on tick interval
  7050. }
  7051. });
  7052. axis.renderUnsquish();
  7053. each(tickPositions, function (pos) {
  7054. // left side must be align: right and right side must have align: left for labels
  7055. if (side === 0 || side === 2 || { 1: 'left', 3: 'right' }[side] === axis.labelAlign) {
  7056. // get the highest offset
  7057. labelOffset = mathMax(
  7058. ticks[pos].getLabelSize(),
  7059. labelOffset
  7060. );
  7061. }
  7062. });
  7063. if (axis.staggerLines) {
  7064. labelOffset *= axis.staggerLines;
  7065. axis.labelOffset = labelOffset;
  7066. }
  7067. } else { // doesn't have data
  7068. for (n in ticks) {
  7069. ticks[n].destroy();
  7070. delete ticks[n];
  7071. }
  7072. }
  7073. if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) {
  7074. if (!axis.axisTitle) {
  7075. axis.axisTitle = renderer.text(
  7076. axisTitleOptions.text,
  7077. 0,
  7078. 0,
  7079. axisTitleOptions.useHTML
  7080. )
  7081. .attr({
  7082. zIndex: 7,
  7083. rotation: axisTitleOptions.rotation || 0,
  7084. align:
  7085. axisTitleOptions.textAlign ||
  7086. { low: 'left', middle: 'center', high: 'right' }[axisTitleOptions.align]
  7087. })
  7088. .addClass(PREFIX + this.coll.toLowerCase() + '-title')
  7089. .css(axisTitleOptions.style)
  7090. .add(axis.axisGroup);
  7091. axis.axisTitle.isNew = true;
  7092. }
  7093. if (showAxis) {
  7094. titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width'];
  7095. titleOffsetOption = axisTitleOptions.offset;
  7096. titleMargin = defined(titleOffsetOption) ? 0 : pick(axisTitleOptions.margin, horiz ? 5 : 10);
  7097. }
  7098. // hide or show the title depending on whether showEmpty is set
  7099. axis.axisTitle[showAxis ? 'show' : 'hide']();
  7100. }
  7101. // handle automatic or user set offset
  7102. axis.offset = directionFactor * pick(options.offset, axisOffset[side]);
  7103. axis.tickRotCorr = axis.tickRotCorr || { x: 0, y: 0 }; // polar
  7104. lineHeightCorrection = side === 2 ? axis.tickRotCorr.y : 0;
  7105. labelOffsetPadded = labelOffset + titleMargin +
  7106. (labelOffset && (directionFactor * (horiz ? pick(labelOptions.y, axis.tickRotCorr.y + 8) : labelOptions.x) - lineHeightCorrection));
  7107. axis.axisTitleMargin = pick(titleOffsetOption, labelOffsetPadded);
  7108. axisOffset[side] = mathMax(
  7109. axisOffset[side],
  7110. axis.axisTitleMargin + titleOffset + directionFactor * axis.offset,
  7111. labelOffsetPadded // #3027
  7112. );
  7113. clipOffset[invertedSide] = mathMax(clipOffset[invertedSide], mathFloor(options.lineWidth / 2) * 2);
  7114. },
  7115. /**
  7116. * Get the path for the axis line
  7117. */
  7118. getLinePath: function (lineWidth) {
  7119. var chart = this.chart,
  7120. opposite = this.opposite,
  7121. offset = this.offset,
  7122. horiz = this.horiz,
  7123. lineLeft = this.left + (opposite ? this.width : 0) + offset,
  7124. lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset;
  7125. if (opposite) {
  7126. lineWidth *= -1; // crispify the other way - #1480, #1687
  7127. }
  7128. return chart.renderer.crispLine([
  7129. M,
  7130. horiz ?
  7131. this.left :
  7132. lineLeft,
  7133. horiz ?
  7134. lineTop :
  7135. this.top,
  7136. L,
  7137. horiz ?
  7138. chart.chartWidth - this.right :
  7139. lineLeft,
  7140. horiz ?
  7141. lineTop :
  7142. chart.chartHeight - this.bottom
  7143. ], lineWidth);
  7144. },
  7145. /**
  7146. * Position the title
  7147. */
  7148. getTitlePosition: function () {
  7149. // compute anchor points for each of the title align options
  7150. var horiz = this.horiz,
  7151. axisLeft = this.left,
  7152. axisTop = this.top,
  7153. axisLength = this.len,
  7154. axisTitleOptions = this.options.title,
  7155. margin = horiz ? axisLeft : axisTop,
  7156. opposite = this.opposite,
  7157. offset = this.offset,
  7158. fontSize = pInt(axisTitleOptions.style.fontSize || 12),
  7159. // the position in the length direction of the axis
  7160. alongAxis = {
  7161. low: margin + (horiz ? 0 : axisLength),
  7162. middle: margin + axisLength / 2,
  7163. high: margin + (horiz ? axisLength : 0)
  7164. }[axisTitleOptions.align],
  7165. // the position in the perpendicular direction of the axis
  7166. offAxis = (horiz ? axisTop + this.height : axisLeft) +
  7167. (horiz ? 1 : -1) * // horizontal axis reverses the margin
  7168. (opposite ? -1 : 1) * // so does opposite axes
  7169. this.axisTitleMargin +
  7170. (this.side === 2 ? fontSize : 0);
  7171. return {
  7172. x: horiz ?
  7173. alongAxis :
  7174. offAxis + (opposite ? this.width : 0) + offset +
  7175. (axisTitleOptions.x || 0), // x
  7176. y: horiz ?
  7177. offAxis - (opposite ? this.height : 0) + offset :
  7178. alongAxis + (axisTitleOptions.y || 0) // y
  7179. };
  7180. },
  7181. /**
  7182. * Render the axis
  7183. */
  7184. render: function () {
  7185. var axis = this,
  7186. chart = axis.chart,
  7187. renderer = chart.renderer,
  7188. options = axis.options,
  7189. isLog = axis.isLog,
  7190. isLinked = axis.isLinked,
  7191. tickPositions = axis.tickPositions,
  7192. axisTitle = axis.axisTitle,
  7193. ticks = axis.ticks,
  7194. minorTicks = axis.minorTicks,
  7195. alternateBands = axis.alternateBands,
  7196. stackLabelOptions = options.stackLabels,
  7197. alternateGridColor = options.alternateGridColor,
  7198. tickmarkOffset = axis.tickmarkOffset,
  7199. lineWidth = options.lineWidth,
  7200. linePath,
  7201. hasRendered = chart.hasRendered,
  7202. slideInTicks = hasRendered && defined(axis.oldMin) && !isNaN(axis.oldMin),
  7203. hasData = axis.hasData,
  7204. showAxis = axis.showAxis,
  7205. from,
  7206. to;
  7207. // Reset
  7208. axis.labelEdge.length = 0;
  7209. //axis.justifyToPlot = overflow === 'justify';
  7210. axis.overlap = false;
  7211. // Mark all elements inActive before we go over and mark the active ones
  7212. each([ticks, minorTicks, alternateBands], function (coll) {
  7213. var pos;
  7214. for (pos in coll) {
  7215. coll[pos].isActive = false;
  7216. }
  7217. });
  7218. // If the series has data draw the ticks. Else only the line and title
  7219. if (hasData || isLinked) {
  7220. // minor ticks
  7221. if (axis.minorTickInterval && !axis.categories) {
  7222. each(axis.getMinorTickPositions(), function (pos) {
  7223. if (!minorTicks[pos]) {
  7224. minorTicks[pos] = new Tick(axis, pos, 'minor');
  7225. }
  7226. // render new ticks in old position
  7227. if (slideInTicks && minorTicks[pos].isNew) {
  7228. minorTicks[pos].render(null, true);
  7229. }
  7230. minorTicks[pos].render(null, false, 1);
  7231. });
  7232. }
  7233. // Major ticks. Pull out the first item and render it last so that
  7234. // we can get the position of the neighbour label. #808.
  7235. if (tickPositions.length) { // #1300
  7236. each(tickPositions, function (pos, i) {
  7237. // linked axes need an extra check to find out if
  7238. if (!isLinked || (pos >= axis.min && pos <= axis.max)) {
  7239. if (!ticks[pos]) {
  7240. ticks[pos] = new Tick(axis, pos);
  7241. }
  7242. // render new ticks in old position
  7243. if (slideInTicks && ticks[pos].isNew) {
  7244. ticks[pos].render(i, true, 0.1);
  7245. }
  7246. ticks[pos].render(i);
  7247. }
  7248. });
  7249. // In a categorized axis, the tick marks are displayed between labels. So
  7250. // we need to add a tick mark and grid line at the left edge of the X axis.
  7251. if (tickmarkOffset && (axis.min === 0 || axis.single)) {
  7252. if (!ticks[-1]) {
  7253. ticks[-1] = new Tick(axis, -1, null, true);
  7254. }
  7255. ticks[-1].render(-1);
  7256. }
  7257. }
  7258. // alternate grid color
  7259. if (alternateGridColor) {
  7260. each(tickPositions, function (pos, i) {
  7261. if (i % 2 === 0 && pos < axis.max) {
  7262. if (!alternateBands[pos]) {
  7263. alternateBands[pos] = new Highcharts.PlotLineOrBand(axis);
  7264. }
  7265. from = pos + tickmarkOffset; // #949
  7266. to = tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] + tickmarkOffset : axis.max;
  7267. alternateBands[pos].options = {
  7268. from: isLog ? lin2log(from) : from,
  7269. to: isLog ? lin2log(to) : to,
  7270. color: alternateGridColor
  7271. };
  7272. alternateBands[pos].render();
  7273. alternateBands[pos].isActive = true;
  7274. }
  7275. });
  7276. }
  7277. // custom plot lines and bands
  7278. if (!axis._addedPlotLB) { // only first time
  7279. each((options.plotLines || []).concat(options.plotBands || []), function (plotLineOptions) {
  7280. axis.addPlotBandOrLine(plotLineOptions);
  7281. });
  7282. axis._addedPlotLB = true;
  7283. }
  7284. } // end if hasData
  7285. // Remove inactive ticks
  7286. each([ticks, minorTicks, alternateBands], function (coll) {
  7287. var pos,
  7288. i,
  7289. forDestruction = [],
  7290. delay = globalAnimation ? globalAnimation.duration || 500 : 0,
  7291. destroyInactiveItems = function () {
  7292. i = forDestruction.length;
  7293. while (i--) {
  7294. // When resizing rapidly, the same items may be destroyed in different timeouts,
  7295. // or the may be reactivated
  7296. if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) {
  7297. coll[forDestruction[i]].destroy();
  7298. delete coll[forDestruction[i]];
  7299. }
  7300. }
  7301. };
  7302. for (pos in coll) {
  7303. if (!coll[pos].isActive) {
  7304. // Render to zero opacity
  7305. coll[pos].render(pos, false, 0);
  7306. coll[pos].isActive = false;
  7307. forDestruction.push(pos);
  7308. }
  7309. }
  7310. // When the objects are finished fading out, destroy them
  7311. if (coll === alternateBands || !chart.hasRendered || !delay) {
  7312. destroyInactiveItems();
  7313. } else if (delay) {
  7314. setTimeout(destroyInactiveItems, delay);
  7315. }
  7316. });
  7317. // Static items. As the axis group is cleared on subsequent calls
  7318. // to render, these items are added outside the group.
  7319. // axis line
  7320. if (lineWidth) {
  7321. linePath = axis.getLinePath(lineWidth);
  7322. if (!axis.axisLine) {
  7323. axis.axisLine = renderer.path(linePath)
  7324. .attr({
  7325. stroke: options.lineColor,
  7326. 'stroke-width': lineWidth,
  7327. zIndex: 7
  7328. })
  7329. .add(axis.axisGroup);
  7330. } else {
  7331. axis.axisLine.animate({ d: linePath });
  7332. }
  7333. // show or hide the line depending on options.showEmpty
  7334. axis.axisLine[showAxis ? 'show' : 'hide']();
  7335. }
  7336. if (axisTitle && showAxis) {
  7337. axisTitle[axisTitle.isNew ? 'attr' : 'animate'](
  7338. axis.getTitlePosition()
  7339. );
  7340. axisTitle.isNew = false;
  7341. }
  7342. // Stacked totals:
  7343. if (stackLabelOptions && stackLabelOptions.enabled) {
  7344. axis.renderStackTotals();
  7345. }
  7346. // End stacked totals
  7347. axis.isDirty = false;
  7348. },
  7349. /**
  7350. * Redraw the axis to reflect changes in the data or axis extremes
  7351. */
  7352. redraw: function () {
  7353. // render the axis
  7354. this.render();
  7355. // move plot lines and bands
  7356. each(this.plotLinesAndBands, function (plotLine) {
  7357. plotLine.render();
  7358. });
  7359. // mark associated series as dirty and ready for redraw
  7360. each(this.series, function (series) {
  7361. series.isDirty = true;
  7362. });
  7363. },
  7364. /**
  7365. * Destroys an Axis instance.
  7366. */
  7367. destroy: function (keepEvents) {
  7368. var axis = this,
  7369. stacks = axis.stacks,
  7370. stackKey,
  7371. plotLinesAndBands = axis.plotLinesAndBands,
  7372. i;
  7373. // Remove the events
  7374. if (!keepEvents) {
  7375. removeEvent(axis);
  7376. }
  7377. // Destroy each stack total
  7378. for (stackKey in stacks) {
  7379. destroyObjectProperties(stacks[stackKey]);
  7380. stacks[stackKey] = null;
  7381. }
  7382. // Destroy collections
  7383. each([axis.ticks, axis.minorTicks, axis.alternateBands], function (coll) {
  7384. destroyObjectProperties(coll);
  7385. });
  7386. i = plotLinesAndBands.length;
  7387. while (i--) { // #1975
  7388. plotLinesAndBands[i].destroy();
  7389. }
  7390. // Destroy local variables
  7391. each(['stackTotalGroup', 'axisLine', 'axisTitle', 'axisGroup', 'cross', 'gridGroup', 'labelGroup'], function (prop) {
  7392. if (axis[prop]) {
  7393. axis[prop] = axis[prop].destroy();
  7394. }
  7395. });
  7396. // Destroy crosshair
  7397. if (this.cross) {
  7398. this.cross.destroy();
  7399. }
  7400. },
  7401. /**
  7402. * Draw the crosshair
  7403. */
  7404. drawCrosshair: function (e, point) { // docs: Missing docs for Axis.crosshair. Also for properties.
  7405. var path,
  7406. options = this.crosshair,
  7407. animation = options.animation,
  7408. pos,
  7409. attribs,
  7410. categorized;
  7411. if (
  7412. // Disabled in options
  7413. !this.crosshair ||
  7414. // Snap
  7415. ((defined(point) || !pick(this.crosshair.snap, true)) === false)
  7416. ) {
  7417. this.hideCrosshair();
  7418. } else {
  7419. // Get the path
  7420. if (!pick(options.snap, true)) {
  7421. pos = (this.horiz ? e.chartX - this.pos : this.len - e.chartY + this.pos);
  7422. } else if (defined(point)) {
  7423. /*jslint eqeq: true*/
  7424. pos = this.isXAxis ? point.plotX : this.len - point.plotY; // #3834
  7425. /*jslint eqeq: false*/
  7426. }
  7427. if (this.isRadial) {
  7428. path = this.getPlotLinePath(this.isXAxis ? point.x : pick(point.stackY, point.y)) || null; // #3189
  7429. } else {
  7430. path = this.getPlotLinePath(null, null, null, null, pos) || null; // #3189
  7431. }
  7432. if (path === null) {
  7433. this.hideCrosshair();
  7434. return;
  7435. }
  7436. // Draw the cross
  7437. if (this.cross) {
  7438. this.cross
  7439. .attr({ visibility: VISIBLE })[animation ? 'animate' : 'attr']({ d: path }, animation);
  7440. } else {
  7441. categorized = this.categories && !this.isRadial;
  7442. attribs = {
  7443. 'stroke-width': options.width || (categorized ? this.transA : 1),
  7444. stroke: options.color || (categorized ? 'rgba(155,200,255,0.2)' : '#C0C0C0'),
  7445. zIndex: options.zIndex || 2
  7446. };
  7447. if (options.dashStyle) {
  7448. attribs.dashstyle = options.dashStyle;
  7449. }
  7450. this.cross = this.chart.renderer.path(path).attr(attribs).add();
  7451. }
  7452. }
  7453. },
  7454. /**
  7455. * Hide the crosshair.
  7456. */
  7457. hideCrosshair: function () {
  7458. if (this.cross) {
  7459. this.cross.hide();
  7460. }
  7461. }
  7462. }; // end Axis
  7463. extend(Axis.prototype, AxisPlotLineOrBandExtension);
  7464. /**
  7465. * Set the tick positions to a time unit that makes sense, for example
  7466. * on the first of each month or on every Monday. Return an array
  7467. * with the time positions. Used in datetime axes as well as for grouping
  7468. * data on a datetime axis.
  7469. *
  7470. * @param {Object} normalizedInterval The interval in axis values (ms) and the count
  7471. * @param {Number} min The minimum in axis values
  7472. * @param {Number} max The maximum in axis values
  7473. * @param {Number} startOfWeek
  7474. */
  7475. Axis.prototype.getTimeTicks = function (normalizedInterval, min, max, startOfWeek) {
  7476. var tickPositions = [],
  7477. i,
  7478. higherRanks = {},
  7479. useUTC = defaultOptions.global.useUTC,
  7480. minYear, // used in months and years as a basis for Date.UTC()
  7481. minDate = new Date(min - getTZOffset(min)),
  7482. interval = normalizedInterval.unitRange,
  7483. count = normalizedInterval.count;
  7484. if (defined(min)) { // #1300
  7485. minDate[setMilliseconds](interval >= timeUnits.second ? 0 : // #3935
  7486. count * mathFloor(minDate.getMilliseconds() / count)); // #3652, #3654
  7487. if (interval >= timeUnits.second) { // second
  7488. minDate[setSeconds](interval >= timeUnits.minute ? 0 : // #3935
  7489. count * mathFloor(minDate.getSeconds() / count));
  7490. }
  7491. if (interval >= timeUnits.minute) { // minute
  7492. minDate[setMinutes](interval >= timeUnits.hour ? 0 :
  7493. count * mathFloor(minDate[getMinutes]() / count));
  7494. }
  7495. if (interval >= timeUnits.hour) { // hour
  7496. minDate[setHours](interval >= timeUnits.day ? 0 :
  7497. count * mathFloor(minDate[getHours]() / count));
  7498. }
  7499. if (interval >= timeUnits.day) { // day
  7500. minDate[setDate](interval >= timeUnits.month ? 1 :
  7501. count * mathFloor(minDate[getDate]() / count));
  7502. }
  7503. if (interval >= timeUnits.month) { // month
  7504. minDate[setMonth](interval >= timeUnits.year ? 0 :
  7505. count * mathFloor(minDate[getMonth]() / count));
  7506. minYear = minDate[getFullYear]();
  7507. }
  7508. if (interval >= timeUnits.year) { // year
  7509. minYear -= minYear % count;
  7510. minDate[setFullYear](minYear);
  7511. }
  7512. // week is a special case that runs outside the hierarchy
  7513. if (interval === timeUnits.week) {
  7514. // get start of current week, independent of count
  7515. minDate[setDate](minDate[getDate]() - minDate[getDay]() +
  7516. pick(startOfWeek, 1));
  7517. }
  7518. // get tick positions
  7519. i = 1;
  7520. if (timezoneOffset || getTimezoneOffset) {
  7521. minDate = minDate.getTime();
  7522. minDate = new Date(minDate + getTZOffset(minDate));
  7523. }
  7524. minYear = minDate[getFullYear]();
  7525. var time = minDate.getTime(),
  7526. minMonth = minDate[getMonth](),
  7527. minDateDate = minDate[getDate](),
  7528. localTimezoneOffset = (timeUnits.day +
  7529. (useUTC ? getTZOffset(minDate) : minDate.getTimezoneOffset() * 60 * 1000)
  7530. ) % timeUnits.day; // #950, #3359
  7531. // iterate and add tick positions at appropriate values
  7532. while (time < max) {
  7533. tickPositions.push(time);
  7534. // if the interval is years, use Date.UTC to increase years
  7535. if (interval === timeUnits.year) {
  7536. time = makeTime(minYear + i * count, 0);
  7537. // if the interval is months, use Date.UTC to increase months
  7538. } else if (interval === timeUnits.month) {
  7539. time = makeTime(minYear, minMonth + i * count);
  7540. // if we're using global time, the interval is not fixed as it jumps
  7541. // one hour at the DST crossover
  7542. } else if (!useUTC && (interval === timeUnits.day || interval === timeUnits.week)) {
  7543. time = makeTime(minYear, minMonth, minDateDate +
  7544. i * count * (interval === timeUnits.day ? 1 : 7));
  7545. // else, the interval is fixed and we use simple addition
  7546. } else {
  7547. time += interval * count;
  7548. }
  7549. i++;
  7550. }
  7551. // push the last time
  7552. tickPositions.push(time);
  7553. // mark new days if the time is dividible by day (#1649, #1760)
  7554. each(grep(tickPositions, function (time) {
  7555. return interval <= timeUnits.hour && time % timeUnits.day === localTimezoneOffset;
  7556. }), function (time) {
  7557. higherRanks[time] = 'day';
  7558. });
  7559. }
  7560. // record information on the chosen unit - for dynamic label formatter
  7561. tickPositions.info = extend(normalizedInterval, {
  7562. higherRanks: higherRanks,
  7563. totalRange: interval * count
  7564. });
  7565. return tickPositions;
  7566. };
  7567. /**
  7568. * Get a normalized tick interval for dates. Returns a configuration object with
  7569. * unit range (interval), count and name. Used to prepare data for getTimeTicks.
  7570. * Previously this logic was part of getTimeTicks, but as getTimeTicks now runs
  7571. * of segments in stock charts, the normalizing logic was extracted in order to
  7572. * prevent it for running over again for each segment having the same interval.
  7573. * #662, #697.
  7574. */
  7575. Axis.prototype.normalizeTimeTickInterval = function (tickInterval, unitsOption) {
  7576. var units = unitsOption || [[
  7577. 'millisecond', // unit name
  7578. [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples
  7579. ], [
  7580. 'second',
  7581. [1, 2, 5, 10, 15, 30]
  7582. ], [
  7583. 'minute',
  7584. [1, 2, 5, 10, 15, 30]
  7585. ], [
  7586. 'hour',
  7587. [1, 2, 3, 4, 6, 8, 12]
  7588. ], [
  7589. 'day',
  7590. [1, 2]
  7591. ], [
  7592. 'week',
  7593. [1, 2]
  7594. ], [
  7595. 'month',
  7596. [1, 2, 3, 4, 6]
  7597. ], [
  7598. 'year',
  7599. null
  7600. ]],
  7601. unit = units[units.length - 1], // default unit is years
  7602. interval = timeUnits[unit[0]],
  7603. multiples = unit[1],
  7604. count,
  7605. i;
  7606. // loop through the units to find the one that best fits the tickInterval
  7607. for (i = 0; i < units.length; i++) {
  7608. unit = units[i];
  7609. interval = timeUnits[unit[0]];
  7610. multiples = unit[1];
  7611. if (units[i + 1]) {
  7612. // lessThan is in the middle between the highest multiple and the next unit.
  7613. var lessThan = (interval * multiples[multiples.length - 1] +
  7614. timeUnits[units[i + 1][0]]) / 2;
  7615. // break and keep the current unit
  7616. if (tickInterval <= lessThan) {
  7617. break;
  7618. }
  7619. }
  7620. }
  7621. // prevent 2.5 years intervals, though 25, 250 etc. are allowed
  7622. if (interval === timeUnits.year && tickInterval < 5 * interval) {
  7623. multiples = [1, 2, 5];
  7624. }
  7625. // get the count
  7626. count = normalizeTickInterval(
  7627. tickInterval / interval,
  7628. multiples,
  7629. unit[0] === 'year' ? mathMax(getMagnitude(tickInterval / interval), 1) : 1 // #1913, #2360
  7630. );
  7631. return {
  7632. unitRange: interval,
  7633. count: count,
  7634. unitName: unit[0]
  7635. };
  7636. };/**
  7637. * Methods defined on the Axis prototype
  7638. */
  7639. /**
  7640. * Set the tick positions of a logarithmic axis
  7641. */
  7642. Axis.prototype.getLogTickPositions = function (interval, min, max, minor) {
  7643. var axis = this,
  7644. options = axis.options,
  7645. axisLength = axis.len,
  7646. // Since we use this method for both major and minor ticks,
  7647. // use a local variable and return the result
  7648. positions = [];
  7649. // Reset
  7650. if (!minor) {
  7651. axis._minorAutoInterval = null;
  7652. }
  7653. // First case: All ticks fall on whole logarithms: 1, 10, 100 etc.
  7654. if (interval >= 0.5) {
  7655. interval = mathRound(interval);
  7656. positions = axis.getLinearTickPositions(interval, min, max);
  7657. // Second case: We need intermediary ticks. For example
  7658. // 1, 2, 4, 6, 8, 10, 20, 40 etc.
  7659. } else if (interval >= 0.08) {
  7660. var roundedMin = mathFloor(min),
  7661. intermediate,
  7662. i,
  7663. j,
  7664. len,
  7665. pos,
  7666. lastPos,
  7667. break2;
  7668. if (interval > 0.3) {
  7669. intermediate = [1, 2, 4];
  7670. } else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc
  7671. intermediate = [1, 2, 4, 6, 8];
  7672. } else { // 0.1 equals ten minor ticks per 1, 10, 100 etc
  7673. intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  7674. }
  7675. for (i = roundedMin; i < max + 1 && !break2; i++) {
  7676. len = intermediate.length;
  7677. for (j = 0; j < len && !break2; j++) {
  7678. pos = log2lin(lin2log(i) * intermediate[j]);
  7679. if (pos > min && (!minor || lastPos <= max) && lastPos !== UNDEFINED) { // #1670, lastPos is #3113
  7680. positions.push(lastPos);
  7681. }
  7682. if (lastPos > max) {
  7683. break2 = true;
  7684. }
  7685. lastPos = pos;
  7686. }
  7687. }
  7688. // Third case: We are so deep in between whole logarithmic values that
  7689. // we might as well handle the tick positions like a linear axis. For
  7690. // example 1.01, 1.02, 1.03, 1.04.
  7691. } else {
  7692. var realMin = lin2log(min),
  7693. realMax = lin2log(max),
  7694. tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'],
  7695. filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption,
  7696. tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1),
  7697. totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength;
  7698. interval = pick(
  7699. filteredTickIntervalOption,
  7700. axis._minorAutoInterval,
  7701. (realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1)
  7702. );
  7703. interval = normalizeTickInterval(
  7704. interval,
  7705. null,
  7706. getMagnitude(interval)
  7707. );
  7708. positions = map(axis.getLinearTickPositions(
  7709. interval,
  7710. realMin,
  7711. realMax
  7712. ), log2lin);
  7713. if (!minor) {
  7714. axis._minorAutoInterval = interval / 5;
  7715. }
  7716. }
  7717. // Set the axis-level tickInterval variable
  7718. if (!minor) {
  7719. axis.tickInterval = interval;
  7720. }
  7721. return positions;
  7722. };/**
  7723. * The tooltip object
  7724. * @param {Object} chart The chart instance
  7725. * @param {Object} options Tooltip options
  7726. */
  7727. var Tooltip = Highcharts.Tooltip = function () {
  7728. this.init.apply(this, arguments);
  7729. };
  7730. Tooltip.prototype = {
  7731. init: function (chart, options) {
  7732. var borderWidth = options.borderWidth,
  7733. style = options.style,
  7734. padding = pInt(style.padding);
  7735. // Save the chart and options
  7736. this.chart = chart;
  7737. this.options = options;
  7738. // Keep track of the current series
  7739. //this.currentSeries = UNDEFINED;
  7740. // List of crosshairs
  7741. this.crosshairs = [];
  7742. // Current values of x and y when animating
  7743. this.now = { x: 0, y: 0 };
  7744. // The tooltip is initially hidden
  7745. this.isHidden = true;
  7746. // create the label
  7747. this.label = chart.renderer.label('', 0, 0, options.shape || 'callout', null, null, options.useHTML, null, 'tooltip')
  7748. .attr({
  7749. padding: padding,
  7750. fill: options.backgroundColor,
  7751. 'stroke-width': borderWidth,
  7752. r: options.borderRadius,
  7753. zIndex: 8
  7754. })
  7755. .css(style)
  7756. .css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117)
  7757. .add()
  7758. .attr({ y: -9999 }); // #2301, #2657
  7759. // When using canVG the shadow shows up as a gray circle
  7760. // even if the tooltip is hidden.
  7761. if (!useCanVG) {
  7762. this.label.shadow(options.shadow);
  7763. }
  7764. // Public property for getting the shared state.
  7765. this.shared = options.shared;
  7766. },
  7767. /**
  7768. * Destroy the tooltip and its elements.
  7769. */
  7770. destroy: function () {
  7771. // Destroy and clear local variables
  7772. if (this.label) {
  7773. this.label = this.label.destroy();
  7774. }
  7775. clearTimeout(this.hideTimer);
  7776. clearTimeout(this.tooltipTimeout);
  7777. },
  7778. /**
  7779. * Provide a soft movement for the tooltip
  7780. *
  7781. * @param {Number} x
  7782. * @param {Number} y
  7783. * @private
  7784. */
  7785. move: function (x, y, anchorX, anchorY) {
  7786. var tooltip = this,
  7787. now = tooltip.now,
  7788. animate = tooltip.options.animation !== false && !tooltip.isHidden &&
  7789. // When we get close to the target position, abort animation and land on the right place (#3056)
  7790. (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1),
  7791. skipAnchor = tooltip.followPointer || tooltip.len > 1;
  7792. // Get intermediate values for animation
  7793. extend(now, {
  7794. x: animate ? (2 * now.x + x) / 3 : x,
  7795. y: animate ? (now.y + y) / 2 : y,
  7796. anchorX: skipAnchor ? UNDEFINED : animate ? (2 * now.anchorX + anchorX) / 3 : anchorX,
  7797. anchorY: skipAnchor ? UNDEFINED : animate ? (now.anchorY + anchorY) / 2 : anchorY
  7798. });
  7799. // Move to the intermediate value
  7800. tooltip.label.attr(now);
  7801. // Run on next tick of the mouse tracker
  7802. if (animate) {
  7803. // Never allow two timeouts
  7804. clearTimeout(this.tooltipTimeout);
  7805. // Set the fixed interval ticking for the smooth tooltip
  7806. this.tooltipTimeout = setTimeout(function () {
  7807. // The interval function may still be running during destroy, so check that the chart is really there before calling.
  7808. if (tooltip) {
  7809. tooltip.move(x, y, anchorX, anchorY);
  7810. }
  7811. }, 32);
  7812. }
  7813. },
  7814. /**
  7815. * Hide the tooltip
  7816. */
  7817. hide: function (delay) {
  7818. var tooltip = this,
  7819. hoverPoints;
  7820. clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766)
  7821. if (!this.isHidden) {
  7822. hoverPoints = this.chart.hoverPoints;
  7823. this.hideTimer = setTimeout(function () {
  7824. tooltip.label.fadeOut();
  7825. tooltip.isHidden = true;
  7826. }, pick(delay, this.options.hideDelay, 500));
  7827. // hide previous hoverPoints and set new
  7828. if (hoverPoints) {
  7829. each(hoverPoints, function (point) {
  7830. point.setState();
  7831. });
  7832. }
  7833. this.chart.hoverPoints = null;
  7834. this.chart.hoverSeries = null;
  7835. }
  7836. },
  7837. /**
  7838. * Extendable method to get the anchor position of the tooltip
  7839. * from a point or set of points
  7840. */
  7841. getAnchor: function (points, mouseEvent) {
  7842. var ret,
  7843. chart = this.chart,
  7844. inverted = chart.inverted,
  7845. plotTop = chart.plotTop,
  7846. plotLeft = chart.plotLeft,
  7847. plotX = 0,
  7848. plotY = 0,
  7849. yAxis,
  7850. xAxis;
  7851. points = splat(points);
  7852. // Pie uses a special tooltipPos
  7853. ret = points[0].tooltipPos;
  7854. // When tooltip follows mouse, relate the position to the mouse
  7855. if (this.followPointer && mouseEvent) {
  7856. if (mouseEvent.chartX === UNDEFINED) {
  7857. mouseEvent = chart.pointer.normalize(mouseEvent);
  7858. }
  7859. ret = [
  7860. mouseEvent.chartX - chart.plotLeft,
  7861. mouseEvent.chartY - plotTop
  7862. ];
  7863. }
  7864. // When shared, use the average position
  7865. if (!ret) {
  7866. each(points, function (point) {
  7867. yAxis = point.series.yAxis;
  7868. xAxis = point.series.xAxis;
  7869. plotX += point.plotX + (!inverted && xAxis ? xAxis.left - plotLeft : 0);
  7870. plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) +
  7871. (!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151
  7872. });
  7873. plotX /= points.length;
  7874. plotY /= points.length;
  7875. ret = [
  7876. inverted ? chart.plotWidth - plotY : plotX,
  7877. this.shared && !inverted && points.length > 1 && mouseEvent ?
  7878. mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424)
  7879. inverted ? chart.plotHeight - plotX : plotY
  7880. ];
  7881. }
  7882. return map(ret, mathRound);
  7883. },
  7884. /**
  7885. * Place the tooltip in a chart without spilling over
  7886. * and not covering the point it self.
  7887. */
  7888. getPosition: function (boxWidth, boxHeight, point) {
  7889. var chart = this.chart,
  7890. distance = this.distance,
  7891. ret = {},
  7892. h = point.h,
  7893. swapped,
  7894. first = ['y', chart.chartHeight, boxHeight, point.plotY + chart.plotTop],
  7895. second = ['x', chart.chartWidth, boxWidth, point.plotX + chart.plotLeft],
  7896. // The far side is right or bottom
  7897. preferFarSide = pick(point.ttBelow, (chart.inverted && !point.negative) || (!chart.inverted && point.negative)),
  7898. /**
  7899. * Handle the preferred dimension. When the preferred dimension is tooltip
  7900. * on top or bottom of the point, it will look for space there.
  7901. */
  7902. firstDimension = function (dim, outerSize, innerSize, point) {
  7903. var roomLeft = innerSize < point - distance,
  7904. roomRight = point + distance + innerSize < outerSize,
  7905. alignedLeft = point - distance - innerSize,
  7906. alignedRight = point + distance;
  7907. if (preferFarSide && roomRight) {
  7908. ret[dim] = alignedRight;
  7909. } else if (!preferFarSide && roomLeft) {
  7910. ret[dim] = alignedLeft;
  7911. } else if (roomLeft) {
  7912. ret[dim] = alignedLeft - h < 0 ? alignedLeft : alignedLeft - h;
  7913. } else if (roomRight) {
  7914. ret[dim] = alignedRight + h + innerSize > outerSize ? alignedRight : alignedRight + h;
  7915. } else {
  7916. return false;
  7917. }
  7918. },
  7919. /**
  7920. * Handle the secondary dimension. If the preferred dimension is tooltip
  7921. * on top or bottom of the point, the second dimension is to align the tooltip
  7922. * above the point, trying to align center but allowing left or right
  7923. * align within the chart box.
  7924. */
  7925. secondDimension = function (dim, outerSize, innerSize, point) {
  7926. // Too close to the edge, return false and swap dimensions
  7927. if (point < distance || point > outerSize - distance) {
  7928. return false;
  7929. // Align left/top
  7930. } else if (point < innerSize / 2) {
  7931. ret[dim] = 1;
  7932. // Align right/bottom
  7933. } else if (point > outerSize - innerSize / 2) {
  7934. ret[dim] = outerSize - innerSize - 2;
  7935. // Align center
  7936. } else {
  7937. ret[dim] = point - innerSize / 2;
  7938. }
  7939. },
  7940. /**
  7941. * Swap the dimensions
  7942. */
  7943. swap = function (count) {
  7944. var temp = first;
  7945. first = second;
  7946. second = temp;
  7947. swapped = count;
  7948. },
  7949. run = function () {
  7950. if (firstDimension.apply(0, first) !== false) {
  7951. if (secondDimension.apply(0, second) === false && !swapped) {
  7952. swap(true);
  7953. run();
  7954. }
  7955. } else if (!swapped) {
  7956. swap(true);
  7957. run();
  7958. } else {
  7959. ret.x = ret.y = 0;
  7960. }
  7961. };
  7962. // Under these conditions, prefer the tooltip on the side of the point
  7963. if (chart.inverted || this.len > 1) {
  7964. swap();
  7965. }
  7966. run();
  7967. return ret;
  7968. },
  7969. /**
  7970. * In case no user defined formatter is given, this will be used. Note that the context
  7971. * here is an object holding point, series, x, y etc.
  7972. */
  7973. defaultFormatter: function (tooltip) {
  7974. var items = this.points || splat(this),
  7975. s;
  7976. // build the header
  7977. s = [tooltip.tooltipFooterHeaderFormatter(items[0])]; //#3397: abstraction to enable formatting of footer and header
  7978. // build the values
  7979. s = s.concat(tooltip.bodyFormatter(items));
  7980. // footer
  7981. s.push(tooltip.tooltipFooterHeaderFormatter(items[0], true)); //#3397: abstraction to enable formatting of footer and header
  7982. return s.join('');
  7983. },
  7984. /**
  7985. * Refresh the tooltip's text and position.
  7986. * @param {Object} point
  7987. */
  7988. refresh: function (point, mouseEvent) {
  7989. var tooltip = this,
  7990. chart = tooltip.chart,
  7991. label = tooltip.label,
  7992. options = tooltip.options,
  7993. x,
  7994. y,
  7995. anchor,
  7996. textConfig = {},
  7997. text,
  7998. pointConfig = [],
  7999. formatter = options.formatter || tooltip.defaultFormatter,
  8000. hoverPoints = chart.hoverPoints,
  8001. borderColor,
  8002. shared = tooltip.shared,
  8003. currentSeries;
  8004. clearTimeout(this.hideTimer);
  8005. // get the reference point coordinates (pie charts use tooltipPos)
  8006. tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer;
  8007. anchor = tooltip.getAnchor(point, mouseEvent);
  8008. x = anchor[0];
  8009. y = anchor[1];
  8010. // shared tooltip, array is sent over
  8011. if (shared && !(point.series && point.series.noSharedTooltip)) {
  8012. // hide previous hoverPoints and set new
  8013. chart.hoverPoints = point;
  8014. if (hoverPoints) {
  8015. each(hoverPoints, function (point) {
  8016. point.setState();
  8017. });
  8018. }
  8019. each(point, function (item) {
  8020. item.setState(HOVER_STATE);
  8021. pointConfig.push(item.getLabelConfig());
  8022. });
  8023. textConfig = {
  8024. x: point[0].category,
  8025. y: point[0].y
  8026. };
  8027. textConfig.points = pointConfig;
  8028. this.len = pointConfig.length;
  8029. point = point[0];
  8030. // single point tooltip
  8031. } else {
  8032. textConfig = point.getLabelConfig();
  8033. }
  8034. text = formatter.call(textConfig, tooltip);
  8035. // register the current series
  8036. currentSeries = point.series;
  8037. this.distance = pick(currentSeries.tooltipOptions.distance, 16);
  8038. // update the inner HTML
  8039. if (text === false) {
  8040. this.hide();
  8041. } else {
  8042. // show it
  8043. if (tooltip.isHidden) {
  8044. stop(label);
  8045. label.attr('opacity', 1).show();
  8046. }
  8047. // update text
  8048. label.attr({
  8049. text: text
  8050. });
  8051. // set the stroke color of the box
  8052. borderColor = options.borderColor || point.color || currentSeries.color || '#606060';
  8053. label.attr({
  8054. stroke: borderColor
  8055. });
  8056. tooltip.updatePosition({
  8057. plotX: x,
  8058. plotY: y,
  8059. negative: point.negative,
  8060. ttBelow: point.ttBelow,
  8061. h: (point.shapeArgs && point.shapeArgs.height) || 0
  8062. });
  8063. this.isHidden = false;
  8064. }
  8065. fireEvent(chart, 'tooltipRefresh', {
  8066. text: text,
  8067. x: x + chart.plotLeft,
  8068. y: y + chart.plotTop,
  8069. borderColor: borderColor
  8070. });
  8071. },
  8072. /**
  8073. * Find the new position and perform the move
  8074. */
  8075. updatePosition: function (point) {
  8076. var chart = this.chart,
  8077. label = this.label,
  8078. pos = (this.options.positioner || this.getPosition).call(
  8079. this,
  8080. label.width,
  8081. label.height,
  8082. point
  8083. );
  8084. // do the move
  8085. this.move(
  8086. mathRound(pos.x),
  8087. mathRound(pos.y),
  8088. point.plotX + chart.plotLeft,
  8089. point.plotY + chart.plotTop
  8090. );
  8091. },
  8092. /**
  8093. * Get the best X date format based on the closest point range on the axis.
  8094. */
  8095. getXDateFormat: function (point, options, xAxis) {
  8096. var xDateFormat,
  8097. dateTimeLabelFormats = options.dateTimeLabelFormats,
  8098. closestPointRange = xAxis && xAxis.closestPointRange,
  8099. n,
  8100. blank = '01-01 00:00:00.000',
  8101. strpos = {
  8102. millisecond: 15,
  8103. second: 12,
  8104. minute: 9,
  8105. hour: 6,
  8106. day: 3
  8107. },
  8108. date,
  8109. lastN;
  8110. if (closestPointRange) {
  8111. date = dateFormat('%m-%d %H:%M:%S.%L', point.x);
  8112. for (n in timeUnits) {
  8113. // If the range is exactly one week and we're looking at a Sunday/Monday, go for the week format
  8114. if (closestPointRange === timeUnits.week && +dateFormat('%w', point.x) === xAxis.options.startOfWeek &&
  8115. date.substr(6) === blank.substr(6)) {
  8116. n = 'week';
  8117. break;
  8118. // The first format that is too great for the range
  8119. } else if (timeUnits[n] > closestPointRange) {
  8120. n = lastN;
  8121. break;
  8122. // If the point is placed every day at 23:59, we need to show
  8123. // the minutes as well. #2637.
  8124. } else if (strpos[n] && date.substr(strpos[n]) !== blank.substr(strpos[n])) {
  8125. break;
  8126. }
  8127. // Weeks are outside the hierarchy, only apply them on Mondays/Sundays like in the first condition
  8128. if (n !== 'week') {
  8129. lastN = n;
  8130. }
  8131. }
  8132. if (n) {
  8133. xDateFormat = dateTimeLabelFormats[n];
  8134. }
  8135. } else {
  8136. xDateFormat = dateTimeLabelFormats.day;
  8137. }
  8138. return xDateFormat || dateTimeLabelFormats.year; // #2546, 2581
  8139. },
  8140. /**
  8141. * Format the footer/header of the tooltip
  8142. * #3397: abstraction to enable formatting of footer and header
  8143. */
  8144. tooltipFooterHeaderFormatter: function (point, isFooter) {
  8145. var footOrHead = isFooter ? 'footer' : 'header',
  8146. series = point.series,
  8147. tooltipOptions = series.tooltipOptions,
  8148. xDateFormat = tooltipOptions.xDateFormat,
  8149. xAxis = series.xAxis,
  8150. isDateTime = xAxis && xAxis.options.type === 'datetime' && isNumber(point.key),
  8151. formatString = tooltipOptions[footOrHead+'Format'];
  8152. // Guess the best date format based on the closest point distance (#568, #3418)
  8153. if (isDateTime && !xDateFormat) {
  8154. xDateFormat = this.getXDateFormat(point, tooltipOptions, xAxis);
  8155. }
  8156. // Insert the footer date format if any
  8157. if (isDateTime && xDateFormat) {
  8158. formatString = formatString.replace('{point.key}', '{point.key:' + xDateFormat + '}');
  8159. }
  8160. return format(formatString, {
  8161. point: point,
  8162. series: series
  8163. });
  8164. },
  8165. /**
  8166. * Build the body (lines) of the tooltip by iterating over the items and returning one entry for each item,
  8167. * abstracting this functionality allows to easily overwrite and extend it.
  8168. */
  8169. bodyFormatter: function (items) {
  8170. return map(items, function (item) {
  8171. var tooltipOptions = item.series.tooltipOptions;
  8172. return (tooltipOptions.pointFormatter || item.point.tooltipFormatter).call(item.point, tooltipOptions.pointFormat);
  8173. });
  8174. }
  8175. };
  8176. var hoverChartIndex;
  8177. // Global flag for touch support
  8178. hasTouch = doc.documentElement.ontouchstart !== UNDEFINED;
  8179. /**
  8180. * The mouse tracker object. All methods starting with "on" are primary DOM event handlers.
  8181. * Subsequent methods should be named differently from what they are doing.
  8182. * @param {Object} chart The Chart instance
  8183. * @param {Object} options The root options object
  8184. */
  8185. var Pointer = Highcharts.Pointer = function (chart, options) {
  8186. this.init(chart, options);
  8187. };
  8188. Pointer.prototype = {
  8189. /**
  8190. * Initialize Pointer
  8191. */
  8192. init: function (chart, options) {
  8193. var chartOptions = options.chart,
  8194. chartEvents = chartOptions.events,
  8195. zoomType = useCanVG ? '' : chartOptions.zoomType,
  8196. inverted = chart.inverted,
  8197. zoomX,
  8198. zoomY;
  8199. // Store references
  8200. this.options = options;
  8201. this.chart = chart;
  8202. // Zoom status
  8203. this.zoomX = zoomX = /x/.test(zoomType);
  8204. this.zoomY = zoomY = /y/.test(zoomType);
  8205. this.zoomHor = (zoomX && !inverted) || (zoomY && inverted);
  8206. this.zoomVert = (zoomY && !inverted) || (zoomX && inverted);
  8207. this.hasZoom = zoomX || zoomY;
  8208. // Do we need to handle click on a touch device?
  8209. this.runChartClick = chartEvents && !!chartEvents.click;
  8210. this.pinchDown = [];
  8211. this.lastValidTouch = {};
  8212. if (Highcharts.Tooltip && options.tooltip.enabled) {
  8213. chart.tooltip = new Tooltip(chart, options.tooltip);
  8214. this.followTouchMove = pick(options.tooltip.followTouchMove, true);
  8215. }
  8216. this.setDOMEvents();
  8217. },
  8218. /**
  8219. * Add crossbrowser support for chartX and chartY
  8220. * @param {Object} e The event object in standard browsers
  8221. */
  8222. normalize: function (e, chartPosition) {
  8223. var chartX,
  8224. chartY,
  8225. ePos;
  8226. // common IE normalizing
  8227. e = e || window.event;
  8228. // Framework specific normalizing (#1165)
  8229. e = washMouseEvent(e);
  8230. // More IE normalizing, needs to go after washMouseEvent
  8231. if (!e.target) {
  8232. e.target = e.srcElement;
  8233. }
  8234. // iOS (#2757)
  8235. ePos = e.touches ? (e.touches.length ? e.touches.item(0) : e.changedTouches[0]) : e;
  8236. // Get mouse position
  8237. if (!chartPosition) {
  8238. this.chartPosition = chartPosition = offset(this.chart.container);
  8239. }
  8240. // chartX and chartY
  8241. if (ePos.pageX === UNDEFINED) { // IE < 9. #886.
  8242. chartX = mathMax(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is
  8243. // for IE10 quirks mode within framesets
  8244. chartY = e.y;
  8245. } else {
  8246. chartX = ePos.pageX - chartPosition.left;
  8247. chartY = ePos.pageY - chartPosition.top;
  8248. }
  8249. return extend(e, {
  8250. chartX: mathRound(chartX),
  8251. chartY: mathRound(chartY)
  8252. });
  8253. },
  8254. /**
  8255. * Get the click position in terms of axis values.
  8256. *
  8257. * @param {Object} e A pointer event
  8258. */
  8259. getCoordinates: function (e) {
  8260. var coordinates = {
  8261. xAxis: [],
  8262. yAxis: []
  8263. };
  8264. each(this.chart.axes, function (axis) {
  8265. coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({
  8266. axis: axis,
  8267. value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY'])
  8268. });
  8269. });
  8270. return coordinates;
  8271. },
  8272. /**
  8273. * With line type charts with a single tracker, get the point closest to the mouse.
  8274. * Run Point.onMouseOver and display tooltip for the point or points.
  8275. */
  8276. runPointActions: function (e) {
  8277. var pointer = this,
  8278. chart = pointer.chart,
  8279. series = chart.series,
  8280. tooltip = chart.tooltip,
  8281. shared = tooltip ? tooltip.shared : false,
  8282. followPointer,
  8283. //point,
  8284. //points,
  8285. hoverPoint = chart.hoverPoint,
  8286. hoverSeries = chart.hoverSeries,
  8287. i,
  8288. //j,
  8289. distance = chart.chartWidth,
  8290. rdistance = chart.chartWidth,
  8291. anchor,
  8292. noSharedTooltip,
  8293. kdpoints = [],
  8294. kdpoint,
  8295. kdpointT;
  8296. // For hovering over the empty parts of the plot area (hoverSeries is undefined).
  8297. // If there is one series with point tracking (combo chart), don't go to nearest neighbour.
  8298. if (!shared && !hoverSeries) {
  8299. for (i = 0; i < series.length; i++) {
  8300. if (series[i].directTouch || !series[i].options.stickyTracking) {
  8301. series = [];
  8302. }
  8303. }
  8304. }
  8305. // If it has a hoverPoint and that series requires direct touch (like columns),
  8306. // use the hoverPoint (#3899). Otherwise, search the k-d tree.
  8307. if (!shared && hoverSeries && hoverSeries.directTouch && hoverPoint) {
  8308. kdpoint = hoverPoint;
  8309. // Handle shared tooltip or cases where a series is not yet hovered
  8310. } else {
  8311. // Find nearest points on all series
  8312. each(series, function (s) {
  8313. // Skip hidden series
  8314. noSharedTooltip = s.noSharedTooltip && shared;
  8315. if (s.visible && !noSharedTooltip && pick(s.options.enableMouseTracking, true)) { // #3821
  8316. kdpointT = s.searchPoint(e); // #3828
  8317. if (kdpointT) {
  8318. kdpoints.push(kdpointT);
  8319. }
  8320. }
  8321. });
  8322. // Find absolute nearest point
  8323. each(kdpoints, function (p) {
  8324. if (p && defined(p.plotX) && defined(p.plotY)) {
  8325. if ((p.dist.distX < distance) || ((p.dist.distX === distance || p.series.kdDimensions > 1) &&
  8326. p.dist.distR < rdistance)) {
  8327. distance = p.dist.distX;
  8328. rdistance = p.dist.distR;
  8329. kdpoint = p;
  8330. }
  8331. }
  8332. });
  8333. }
  8334. // Refresh tooltip for kdpoint if new hover point or tooltip was hidden // #3926
  8335. if (kdpoint && (kdpoint !== hoverPoint || (tooltip && tooltip.isHidden))) {
  8336. // Draw tooltip if necessary
  8337. if (shared && !kdpoint.series.noSharedTooltip) {
  8338. i = kdpoints.length;
  8339. while (i--) {
  8340. if (kdpoints[i].clientX !== kdpoint.clientX || kdpoints[i].series.noSharedTooltip) {
  8341. kdpoints.splice(i, 1);
  8342. }
  8343. }
  8344. if (kdpoints.length && tooltip) {
  8345. tooltip.refresh(kdpoints, e);
  8346. }
  8347. // do mouseover on all points except the closest
  8348. each(kdpoints, function (point) {
  8349. if (point !== kdpoint) {
  8350. point.onMouseOver(e);
  8351. }
  8352. });
  8353. // #3919, #3985 do mouseover on the closest point last to ensure it is the hoverpoint
  8354. ((hoverSeries && hoverSeries.directTouch && hoverPoint) || kdpoint).onMouseOver(e);
  8355. } else {
  8356. if (tooltip) {
  8357. tooltip.refresh(kdpoint, e);
  8358. }
  8359. kdpoint.onMouseOver(e);
  8360. }
  8361. // Update positions (regardless of kdpoint or hoverPoint)
  8362. } else {
  8363. followPointer = hoverSeries && hoverSeries.tooltipOptions.followPointer;
  8364. if (tooltip && followPointer && !tooltip.isHidden) {
  8365. anchor = tooltip.getAnchor([{}], e);
  8366. tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] });
  8367. }
  8368. }
  8369. // Start the event listener to pick up the tooltip
  8370. if (tooltip && !pointer._onDocumentMouseMove) {
  8371. pointer._onDocumentMouseMove = function (e) {
  8372. if (charts[hoverChartIndex]) {
  8373. charts[hoverChartIndex].pointer.onDocumentMouseMove(e);
  8374. }
  8375. };
  8376. addEvent(doc, 'mousemove', pointer._onDocumentMouseMove);
  8377. }
  8378. // Crosshair
  8379. each(chart.axes, function (axis) {
  8380. axis.drawCrosshair(e, pick(kdpoint, hoverPoint));
  8381. });
  8382. },
  8383. /**
  8384. * Reset the tracking by hiding the tooltip, the hover series state and the hover point
  8385. *
  8386. * @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible
  8387. */
  8388. reset: function (allowMove, delay) {
  8389. var pointer = this,
  8390. chart = pointer.chart,
  8391. hoverSeries = chart.hoverSeries,
  8392. hoverPoint = chart.hoverPoint,
  8393. tooltip = chart.tooltip,
  8394. tooltipPoints = tooltip && tooltip.shared ? chart.hoverPoints : hoverPoint;
  8395. // Narrow in allowMove
  8396. allowMove = allowMove && tooltip && tooltipPoints;
  8397. // Check if the points have moved outside the plot area, #1003
  8398. if (allowMove && splat(tooltipPoints)[0].plotX === UNDEFINED) {
  8399. allowMove = false;
  8400. }
  8401. // Just move the tooltip, #349
  8402. if (allowMove) {
  8403. tooltip.refresh(tooltipPoints);
  8404. if (hoverPoint) { // #2500
  8405. hoverPoint.setState(hoverPoint.state, true);
  8406. each(chart.axes, function (axis) {
  8407. if (pick(axis.options.crosshair && axis.options.crosshair.snap, true)) {
  8408. axis.drawCrosshair(null, allowMove);
  8409. } else {
  8410. axis.hideCrosshair();
  8411. }
  8412. });
  8413. }
  8414. // Full reset
  8415. } else {
  8416. if (hoverPoint) {
  8417. hoverPoint.onMouseOut();
  8418. }
  8419. if (hoverSeries) {
  8420. hoverSeries.onMouseOut();
  8421. }
  8422. if (tooltip) {
  8423. tooltip.hide(delay);
  8424. }
  8425. if (pointer._onDocumentMouseMove) {
  8426. removeEvent(doc, 'mousemove', pointer._onDocumentMouseMove);
  8427. pointer._onDocumentMouseMove = null;
  8428. }
  8429. // Remove crosshairs
  8430. each(chart.axes, function (axis) {
  8431. axis.hideCrosshair();
  8432. });
  8433. pointer.hoverX = null;
  8434. }
  8435. },
  8436. /**
  8437. * Scale series groups to a certain scale and translation
  8438. */
  8439. scaleGroups: function (attribs, clip) {
  8440. var chart = this.chart,
  8441. seriesAttribs;
  8442. // Scale each series
  8443. each(chart.series, function (series) {
  8444. seriesAttribs = attribs || series.getPlotBox(); // #1701
  8445. if (series.xAxis && series.xAxis.zoomEnabled) {
  8446. series.group.attr(seriesAttribs);
  8447. if (series.markerGroup) {
  8448. series.markerGroup.attr(seriesAttribs);
  8449. series.markerGroup.clip(clip ? chart.clipRect : null);
  8450. }
  8451. if (series.dataLabelsGroup) {
  8452. series.dataLabelsGroup.attr(seriesAttribs);
  8453. }
  8454. }
  8455. });
  8456. // Clip
  8457. chart.clipRect.attr(clip || chart.clipBox);
  8458. },
  8459. /**
  8460. * Start a drag operation
  8461. */
  8462. dragStart: function (e) {
  8463. var chart = this.chart;
  8464. // Record the start position
  8465. chart.mouseIsDown = e.type;
  8466. chart.cancelClick = false;
  8467. chart.mouseDownX = this.mouseDownX = e.chartX;
  8468. chart.mouseDownY = this.mouseDownY = e.chartY;
  8469. },
  8470. /**
  8471. * Perform a drag operation in response to a mousemove event while the mouse is down
  8472. */
  8473. drag: function (e) {
  8474. var chart = this.chart,
  8475. chartOptions = chart.options.chart,
  8476. chartX = e.chartX,
  8477. chartY = e.chartY,
  8478. zoomHor = this.zoomHor,
  8479. zoomVert = this.zoomVert,
  8480. plotLeft = chart.plotLeft,
  8481. plotTop = chart.plotTop,
  8482. plotWidth = chart.plotWidth,
  8483. plotHeight = chart.plotHeight,
  8484. clickedInside,
  8485. size,
  8486. mouseDownX = this.mouseDownX,
  8487. mouseDownY = this.mouseDownY,
  8488. panKey = chartOptions.panKey && e[chartOptions.panKey + 'Key'];
  8489. // If the mouse is outside the plot area, adjust to cooordinates
  8490. // inside to prevent the selection marker from going outside
  8491. if (chartX < plotLeft) {
  8492. chartX = plotLeft;
  8493. } else if (chartX > plotLeft + plotWidth) {
  8494. chartX = plotLeft + plotWidth;
  8495. }
  8496. if (chartY < plotTop) {
  8497. chartY = plotTop;
  8498. } else if (chartY > plotTop + plotHeight) {
  8499. chartY = plotTop + plotHeight;
  8500. }
  8501. // determine if the mouse has moved more than 10px
  8502. this.hasDragged = Math.sqrt(
  8503. Math.pow(mouseDownX - chartX, 2) +
  8504. Math.pow(mouseDownY - chartY, 2)
  8505. );
  8506. if (this.hasDragged > 10) {
  8507. clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop);
  8508. // make a selection
  8509. if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside && !panKey) {
  8510. if (!this.selectionMarker) {
  8511. this.selectionMarker = chart.renderer.rect(
  8512. plotLeft,
  8513. plotTop,
  8514. zoomHor ? 1 : plotWidth,
  8515. zoomVert ? 1 : plotHeight,
  8516. 0
  8517. )
  8518. .attr({
  8519. fill: chartOptions.selectionMarkerFill || 'rgba(69,114,167,0.25)',
  8520. zIndex: 7
  8521. })
  8522. .add();
  8523. }
  8524. }
  8525. // adjust the width of the selection marker
  8526. if (this.selectionMarker && zoomHor) {
  8527. size = chartX - mouseDownX;
  8528. this.selectionMarker.attr({
  8529. width: mathAbs(size),
  8530. x: (size > 0 ? 0 : size) + mouseDownX
  8531. });
  8532. }
  8533. // adjust the height of the selection marker
  8534. if (this.selectionMarker && zoomVert) {
  8535. size = chartY - mouseDownY;
  8536. this.selectionMarker.attr({
  8537. height: mathAbs(size),
  8538. y: (size > 0 ? 0 : size) + mouseDownY
  8539. });
  8540. }
  8541. // panning
  8542. if (clickedInside && !this.selectionMarker && chartOptions.panning) {
  8543. chart.pan(e, chartOptions.panning);
  8544. }
  8545. }
  8546. },
  8547. /**
  8548. * On mouse up or touch end across the entire document, drop the selection.
  8549. */
  8550. drop: function (e) {
  8551. var pointer = this,
  8552. chart = this.chart,
  8553. hasPinched = this.hasPinched;
  8554. if (this.selectionMarker) {
  8555. var selectionData = {
  8556. xAxis: [],
  8557. yAxis: [],
  8558. originalEvent: e.originalEvent || e
  8559. },
  8560. selectionBox = this.selectionMarker,
  8561. selectionLeft = selectionBox.attr ? selectionBox.attr('x') : selectionBox.x,
  8562. selectionTop = selectionBox.attr ? selectionBox.attr('y') : selectionBox.y,
  8563. selectionWidth = selectionBox.attr ? selectionBox.attr('width') : selectionBox.width,
  8564. selectionHeight = selectionBox.attr ? selectionBox.attr('height') : selectionBox.height,
  8565. runZoom;
  8566. // a selection has been made
  8567. if (this.hasDragged || hasPinched) {
  8568. // record each axis' min and max
  8569. each(chart.axes, function (axis) {
  8570. if (axis.zoomEnabled && defined(axis.min) && (hasPinched || pointer[{ xAxis: 'zoomX', yAxis: 'zoomY' }[axis.coll]])) { // #859, #3569
  8571. var horiz = axis.horiz,
  8572. minPixelPadding = e.type === 'touchend' ? axis.minPixelPadding: 0, // #1207, #3075
  8573. selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop) + minPixelPadding),
  8574. selectionMax = axis.toValue((horiz ? selectionLeft + selectionWidth : selectionTop + selectionHeight) - minPixelPadding);
  8575. selectionData[axis.coll].push({
  8576. axis: axis,
  8577. min: mathMin(selectionMin, selectionMax), // for reversed axes
  8578. max: mathMax(selectionMin, selectionMax)
  8579. });
  8580. runZoom = true;
  8581. }
  8582. });
  8583. if (runZoom) {
  8584. fireEvent(chart, 'selection', selectionData, function (args) {
  8585. chart.zoom(extend(args, hasPinched ? { animation: false } : null));
  8586. });
  8587. }
  8588. }
  8589. this.selectionMarker = this.selectionMarker.destroy();
  8590. // Reset scaling preview
  8591. if (hasPinched) {
  8592. this.scaleGroups();
  8593. }
  8594. }
  8595. // Reset all
  8596. if (chart) { // it may be destroyed on mouse up - #877
  8597. css(chart.container, { cursor: chart._cursor });
  8598. chart.cancelClick = this.hasDragged > 10; // #370
  8599. chart.mouseIsDown = this.hasDragged = this.hasPinched = false;
  8600. this.pinchDown = [];
  8601. }
  8602. },
  8603. onContainerMouseDown: function (e) {
  8604. e = this.normalize(e);
  8605. // issue #295, dragging not always working in Firefox
  8606. if (e.preventDefault) {
  8607. e.preventDefault();
  8608. }
  8609. this.dragStart(e);
  8610. },
  8611. onDocumentMouseUp: function (e) {
  8612. if (charts[hoverChartIndex]) {
  8613. charts[hoverChartIndex].pointer.drop(e);
  8614. }
  8615. },
  8616. /**
  8617. * Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea.
  8618. * Issue #149 workaround. The mouseleave event does not always fire.
  8619. */
  8620. onDocumentMouseMove: function (e) {
  8621. var chart = this.chart,
  8622. chartPosition = this.chartPosition;
  8623. e = this.normalize(e, chartPosition);
  8624. // If we're outside, hide the tooltip
  8625. if (chartPosition && !this.inClass(e.target, 'highcharts-tracker') &&
  8626. !chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
  8627. this.reset();
  8628. }
  8629. },
  8630. /**
  8631. * When mouse leaves the container, hide the tooltip.
  8632. */
  8633. onContainerMouseLeave: function () {
  8634. var chart = charts[hoverChartIndex];
  8635. if (chart) {
  8636. chart.pointer.reset();
  8637. chart.pointer.chartPosition = null; // also reset the chart position, used in #149 fix
  8638. }
  8639. },
  8640. // The mousemove, touchmove and touchstart event handler
  8641. onContainerMouseMove: function (e) {
  8642. var chart = this.chart;
  8643. hoverChartIndex = chart.index;
  8644. e = this.normalize(e);
  8645. e.returnValue = false; // #2251, #3224
  8646. if (chart.mouseIsDown === 'mousedown') {
  8647. this.drag(e);
  8648. }
  8649. // Show the tooltip and run mouse over events (#977)
  8650. if ((this.inClass(e.target, 'highcharts-tracker') ||
  8651. chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) {
  8652. this.runPointActions(e);
  8653. }
  8654. },
  8655. /**
  8656. * Utility to detect whether an element has, or has a parent with, a specific
  8657. * class name. Used on detection of tracker objects and on deciding whether
  8658. * hovering the tooltip should cause the active series to mouse out.
  8659. */
  8660. inClass: function (element, className) {
  8661. var elemClassName;
  8662. while (element) {
  8663. elemClassName = attr(element, 'class');
  8664. if (elemClassName) {
  8665. if (elemClassName.indexOf(className) !== -1) {
  8666. return true;
  8667. } else if (elemClassName.indexOf(PREFIX + 'container') !== -1) {
  8668. return false;
  8669. }
  8670. }
  8671. element = element.parentNode;
  8672. }
  8673. },
  8674. onTrackerMouseOut: function (e) {
  8675. var series = this.chart.hoverSeries,
  8676. relatedTarget = e.relatedTarget || e.toElement,
  8677. relatedSeries = relatedTarget && relatedTarget.point && relatedTarget.point.series; // #2499
  8678. if (series && !series.options.stickyTracking && !this.inClass(relatedTarget, PREFIX + 'tooltip') &&
  8679. relatedSeries !== series) {
  8680. series.onMouseOut();
  8681. }
  8682. },
  8683. onContainerClick: function (e) {
  8684. var chart = this.chart,
  8685. hoverPoint = chart.hoverPoint,
  8686. plotLeft = chart.plotLeft,
  8687. plotTop = chart.plotTop;
  8688. e = this.normalize(e);
  8689. e.originalEvent = e; // #3913
  8690. e.cancelBubble = true; // IE specific
  8691. if (!chart.cancelClick) {
  8692. // On tracker click, fire the series and point events. #783, #1583
  8693. if (hoverPoint && this.inClass(e.target, PREFIX + 'tracker')) {
  8694. // the series click event
  8695. fireEvent(hoverPoint.series, 'click', extend(e, {
  8696. point: hoverPoint
  8697. }));
  8698. // the point click event
  8699. if (chart.hoverPoint) { // it may be destroyed (#1844)
  8700. hoverPoint.firePointEvent('click', e);
  8701. }
  8702. // When clicking outside a tracker, fire a chart event
  8703. } else {
  8704. extend(e, this.getCoordinates(e));
  8705. // fire a click event in the chart
  8706. if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) {
  8707. fireEvent(chart, 'click', e);
  8708. }
  8709. }
  8710. }
  8711. },
  8712. /**
  8713. * Set the JS DOM events on the container and document. This method should contain
  8714. * a one-to-one assignment between methods and their handlers. Any advanced logic should
  8715. * be moved to the handler reflecting the event's name.
  8716. */
  8717. setDOMEvents: function () {
  8718. var pointer = this,
  8719. container = pointer.chart.container;
  8720. container.onmousedown = function (e) {
  8721. pointer.onContainerMouseDown(e);
  8722. };
  8723. container.onmousemove = function (e) {
  8724. pointer.onContainerMouseMove(e);
  8725. };
  8726. container.onclick = function (e) {
  8727. pointer.onContainerClick(e);
  8728. };
  8729. addEvent(container, 'mouseleave', pointer.onContainerMouseLeave);
  8730. if (chartCount === 1) {
  8731. addEvent(doc, 'mouseup', pointer.onDocumentMouseUp);
  8732. }
  8733. if (hasTouch) {
  8734. container.ontouchstart = function (e) {
  8735. pointer.onContainerTouchStart(e);
  8736. };
  8737. container.ontouchmove = function (e) {
  8738. pointer.onContainerTouchMove(e);
  8739. };
  8740. if (chartCount === 1) {
  8741. addEvent(doc, 'touchend', pointer.onDocumentTouchEnd);
  8742. }
  8743. }
  8744. },
  8745. /**
  8746. * Destroys the Pointer object and disconnects DOM events.
  8747. */
  8748. destroy: function () {
  8749. var prop;
  8750. removeEvent(this.chart.container, 'mouseleave', this.onContainerMouseLeave);
  8751. if (!chartCount) {
  8752. removeEvent(doc, 'mouseup', this.onDocumentMouseUp);
  8753. removeEvent(doc, 'touchend', this.onDocumentTouchEnd);
  8754. }
  8755. // memory and CPU leak
  8756. clearInterval(this.tooltipTimeout);
  8757. for (prop in this) {
  8758. this[prop] = null;
  8759. }
  8760. }
  8761. };
  8762. /* Support for touch devices */
  8763. extend(Highcharts.Pointer.prototype, {
  8764. /**
  8765. * Run translation operations
  8766. */
  8767. pinchTranslate: function (pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) {
  8768. if (this.zoomHor || this.pinchHor) {
  8769. this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
  8770. }
  8771. if (this.zoomVert || this.pinchVert) {
  8772. this.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
  8773. }
  8774. },
  8775. /**
  8776. * Run translation operations for each direction (horizontal and vertical) independently
  8777. */
  8778. pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch, forcedScale) {
  8779. var chart = this.chart,
  8780. xy = horiz ? 'x' : 'y',
  8781. XY = horiz ? 'X' : 'Y',
  8782. sChartXY = 'chart' + XY,
  8783. wh = horiz ? 'width' : 'height',
  8784. plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')],
  8785. selectionWH,
  8786. selectionXY,
  8787. clipXY,
  8788. scale = forcedScale || 1,
  8789. inverted = chart.inverted,
  8790. bounds = chart.bounds[horiz ? 'h' : 'v'],
  8791. singleTouch = pinchDown.length === 1,
  8792. touch0Start = pinchDown[0][sChartXY],
  8793. touch0Now = touches[0][sChartXY],
  8794. touch1Start = !singleTouch && pinchDown[1][sChartXY],
  8795. touch1Now = !singleTouch && touches[1][sChartXY],
  8796. outOfBounds,
  8797. transformScale,
  8798. scaleKey,
  8799. setScale = function () {
  8800. if (!singleTouch && mathAbs(touch0Start - touch1Start) > 20) { // Don't zoom if fingers are too close on this axis
  8801. scale = forcedScale || mathAbs(touch0Now - touch1Now) / mathAbs(touch0Start - touch1Start);
  8802. }
  8803. clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start;
  8804. selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale;
  8805. };
  8806. // Set the scale, first pass
  8807. setScale();
  8808. selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not
  8809. // Out of bounds
  8810. if (selectionXY < bounds.min) {
  8811. selectionXY = bounds.min;
  8812. outOfBounds = true;
  8813. } else if (selectionXY + selectionWH > bounds.max) {
  8814. selectionXY = bounds.max - selectionWH;
  8815. outOfBounds = true;
  8816. }
  8817. // Is the chart dragged off its bounds, determined by dataMin and dataMax?
  8818. if (outOfBounds) {
  8819. // Modify the touchNow position in order to create an elastic drag movement. This indicates
  8820. // to the user that the chart is responsive but can't be dragged further.
  8821. touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]);
  8822. if (!singleTouch) {
  8823. touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]);
  8824. }
  8825. // Set the scale, second pass to adapt to the modified touchNow positions
  8826. setScale();
  8827. } else {
  8828. lastValidTouch[xy] = [touch0Now, touch1Now];
  8829. }
  8830. // Set geometry for clipping, selection and transformation
  8831. if (!inverted) { // TODO: implement clipping for inverted charts
  8832. clip[xy] = clipXY - plotLeftTop;
  8833. clip[wh] = selectionWH;
  8834. }
  8835. scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY;
  8836. transformScale = inverted ? 1 / scale : scale;
  8837. selectionMarker[wh] = selectionWH;
  8838. selectionMarker[xy] = selectionXY;
  8839. transform[scaleKey] = scale;
  8840. transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start));
  8841. },
  8842. /**
  8843. * Handle touch events with two touches
  8844. */
  8845. pinch: function (e) {
  8846. var self = this,
  8847. chart = self.chart,
  8848. pinchDown = self.pinchDown,
  8849. touches = e.touches,
  8850. touchesLength = touches.length,
  8851. lastValidTouch = self.lastValidTouch,
  8852. hasZoom = self.hasZoom,
  8853. selectionMarker = self.selectionMarker,
  8854. transform = {},
  8855. fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, PREFIX + 'tracker') &&
  8856. chart.runTrackerClick) || self.runChartClick),
  8857. clip = {};
  8858. // On touch devices, only proceed to trigger click if a handler is defined
  8859. if (hasZoom && !fireClickEvent) {
  8860. e.preventDefault();
  8861. }
  8862. // Normalize each touch
  8863. map(touches, function (e) {
  8864. return self.normalize(e);
  8865. });
  8866. // Register the touch start position
  8867. if (e.type === 'touchstart') {
  8868. each(touches, function (e, i) {
  8869. pinchDown[i] = { chartX: e.chartX, chartY: e.chartY };
  8870. });
  8871. lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX];
  8872. lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY];
  8873. // Identify the data bounds in pixels
  8874. each(chart.axes, function (axis) {
  8875. if (axis.zoomEnabled) {
  8876. var bounds = chart.bounds[axis.horiz ? 'h' : 'v'],
  8877. minPixelPadding = axis.minPixelPadding,
  8878. min = axis.toPixels(pick(axis.options.min, axis.dataMin)),
  8879. max = axis.toPixels(pick(axis.options.max, axis.dataMax)),
  8880. absMin = mathMin(min, max),
  8881. absMax = mathMax(min, max);
  8882. // Store the bounds for use in the touchmove handler
  8883. bounds.min = mathMin(axis.pos, absMin - minPixelPadding);
  8884. bounds.max = mathMax(axis.pos + axis.len, absMax + minPixelPadding);
  8885. }
  8886. });
  8887. self.res = true; // reset on next move
  8888. // Event type is touchmove, handle panning and pinching
  8889. } else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first
  8890. // Set the marker
  8891. if (!selectionMarker) {
  8892. self.selectionMarker = selectionMarker = extend({
  8893. destroy: noop
  8894. }, chart.plotBox);
  8895. }
  8896. self.pinchTranslate(pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
  8897. self.hasPinched = hasZoom;
  8898. // Scale and translate the groups to provide visual feedback during pinching
  8899. self.scaleGroups(transform, clip);
  8900. // Optionally move the tooltip on touchmove
  8901. if (!hasZoom && self.followTouchMove && touchesLength === 1) {
  8902. this.runPointActions(self.normalize(e));
  8903. } else if (self.res) {
  8904. self.res = false;
  8905. this.reset(false, 0);
  8906. }
  8907. }
  8908. },
  8909. onContainerTouchStart: function (e) {
  8910. var chart = this.chart;
  8911. hoverChartIndex = chart.index;
  8912. if (e.touches.length === 1) {
  8913. e = this.normalize(e);
  8914. if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop) && !chart.openMenu) {
  8915. // Run mouse events and display tooltip etc
  8916. this.runPointActions(e);
  8917. this.pinch(e);
  8918. } else {
  8919. // Hide the tooltip on touching outside the plot area (#1203)
  8920. this.reset();
  8921. }
  8922. } else if (e.touches.length === 2) {
  8923. this.pinch(e);
  8924. }
  8925. },
  8926. onContainerTouchMove: function (e) {
  8927. if (e.touches.length === 1 || e.touches.length === 2) {
  8928. this.pinch(e);
  8929. }
  8930. },
  8931. onDocumentTouchEnd: function (e) {
  8932. if (charts[hoverChartIndex]) {
  8933. charts[hoverChartIndex].pointer.drop(e);
  8934. }
  8935. }
  8936. });
  8937. if (win.PointerEvent || win.MSPointerEvent) {
  8938. // The touches object keeps track of the points being touched at all times
  8939. var touches = {},
  8940. hasPointerEvent = !!win.PointerEvent,
  8941. getWebkitTouches = function () {
  8942. var key, fake = [];
  8943. fake.item = function (i) { return this[i]; };
  8944. for (key in touches) {
  8945. if (touches.hasOwnProperty(key)) {
  8946. fake.push({
  8947. pageX: touches[key].pageX,
  8948. pageY: touches[key].pageY,
  8949. target: touches[key].target
  8950. });
  8951. }
  8952. }
  8953. return fake;
  8954. },
  8955. translateMSPointer = function (e, method, wktype, callback) {
  8956. var p;
  8957. e = e.originalEvent || e;
  8958. if ((e.pointerType === 'touch' || e.pointerType === e.MSPOINTER_TYPE_TOUCH) && charts[hoverChartIndex]) {
  8959. callback(e);
  8960. p = charts[hoverChartIndex].pointer;
  8961. p[method]({
  8962. type: wktype,
  8963. target: e.currentTarget,
  8964. preventDefault: noop,
  8965. touches: getWebkitTouches()
  8966. });
  8967. }
  8968. };
  8969. /**
  8970. * Extend the Pointer prototype with methods for each event handler and more
  8971. */
  8972. extend(Pointer.prototype, {
  8973. onContainerPointerDown: function (e) {
  8974. translateMSPointer(e, 'onContainerTouchStart', 'touchstart', function (e) {
  8975. touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY, target: e.currentTarget };
  8976. });
  8977. },
  8978. onContainerPointerMove: function (e) {
  8979. translateMSPointer(e, 'onContainerTouchMove', 'touchmove', function (e) {
  8980. touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY };
  8981. if (!touches[e.pointerId].target) {
  8982. touches[e.pointerId].target = e.currentTarget;
  8983. }
  8984. });
  8985. },
  8986. onDocumentPointerUp: function (e) {
  8987. translateMSPointer(e, 'onDocumentTouchEnd', 'touchend', function (e) {
  8988. delete touches[e.pointerId];
  8989. });
  8990. },
  8991. /**
  8992. * Add or remove the MS Pointer specific events
  8993. */
  8994. batchMSEvents: function (fn) {
  8995. fn(this.chart.container, hasPointerEvent ? 'pointerdown' : 'MSPointerDown', this.onContainerPointerDown);
  8996. fn(this.chart.container, hasPointerEvent ? 'pointermove' : 'MSPointerMove', this.onContainerPointerMove);
  8997. fn(doc, hasPointerEvent ? 'pointerup' : 'MSPointerUp', this.onDocumentPointerUp);
  8998. }
  8999. });
  9000. // Disable default IE actions for pinch and such on chart element
  9001. wrap(Pointer.prototype, 'init', function (proceed, chart, options) {
  9002. proceed.call(this, chart, options);
  9003. if (this.hasZoom) { // #4014
  9004. css(chart.container, {
  9005. '-ms-touch-action': NONE,
  9006. 'touch-action': NONE
  9007. });
  9008. }
  9009. });
  9010. // Add IE specific touch events to chart
  9011. wrap(Pointer.prototype, 'setDOMEvents', function (proceed) {
  9012. proceed.apply(this);
  9013. if (this.hasZoom || this.followTouchMove) {
  9014. this.batchMSEvents(addEvent);
  9015. }
  9016. });
  9017. // Destroy MS events also
  9018. wrap(Pointer.prototype, 'destroy', function (proceed) {
  9019. this.batchMSEvents(removeEvent);
  9020. proceed.call(this);
  9021. });
  9022. }
  9023. /**
  9024. * The overview of the chart's series
  9025. */
  9026. var Legend = Highcharts.Legend = function (chart, options) {
  9027. this.init(chart, options);
  9028. };
  9029. Legend.prototype = {
  9030. /**
  9031. * Initialize the legend
  9032. */
  9033. init: function (chart, options) {
  9034. var legend = this,
  9035. itemStyle = options.itemStyle,
  9036. padding,
  9037. itemMarginTop = options.itemMarginTop || 0;
  9038. this.options = options;
  9039. if (!options.enabled) {
  9040. return;
  9041. }
  9042. legend.itemStyle = itemStyle;
  9043. legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle);
  9044. legend.itemMarginTop = itemMarginTop;
  9045. legend.padding = padding = pick(options.padding, 8);
  9046. legend.initialItemX = padding;
  9047. legend.initialItemY = padding - 5; // 5 is the number of pixels above the text
  9048. legend.maxItemWidth = 0;
  9049. legend.chart = chart;
  9050. legend.itemHeight = 0;
  9051. legend.symbolWidth = pick(options.symbolWidth, 16);
  9052. legend.pages = [];
  9053. // Render it
  9054. legend.render();
  9055. // move checkboxes
  9056. addEvent(legend.chart, 'endResize', function () {
  9057. legend.positionCheckboxes();
  9058. });
  9059. },
  9060. /**
  9061. * Set the colors for the legend item
  9062. * @param {Object} item A Series or Point instance
  9063. * @param {Object} visible Dimmed or colored
  9064. */
  9065. colorizeItem: function (item, visible) {
  9066. var legend = this,
  9067. options = legend.options,
  9068. legendItem = item.legendItem,
  9069. legendLine = item.legendLine,
  9070. legendSymbol = item.legendSymbol,
  9071. hiddenColor = legend.itemHiddenStyle.color,
  9072. textColor = visible ? options.itemStyle.color : hiddenColor,
  9073. symbolColor = visible ? (item.legendColor || item.color || '#CCC') : hiddenColor,
  9074. markerOptions = item.options && item.options.marker,
  9075. symbolAttr = { fill: symbolColor },
  9076. key,
  9077. val;
  9078. if (legendItem) {
  9079. legendItem.css({ fill: textColor, color: textColor }); // color for #1553, oldIE
  9080. }
  9081. if (legendLine) {
  9082. legendLine.attr({ stroke: symbolColor });
  9083. }
  9084. if (legendSymbol) {
  9085. // Apply marker options
  9086. if (markerOptions && legendSymbol.isMarker) { // #585
  9087. symbolAttr.stroke = symbolColor;
  9088. markerOptions = item.convertAttribs(markerOptions);
  9089. for (key in markerOptions) {
  9090. val = markerOptions[key];
  9091. if (val !== UNDEFINED) {
  9092. symbolAttr[key] = val;
  9093. }
  9094. }
  9095. }
  9096. legendSymbol.attr(symbolAttr);
  9097. }
  9098. },
  9099. /**
  9100. * Position the legend item
  9101. * @param {Object} item A Series or Point instance
  9102. */
  9103. positionItem: function (item) {
  9104. var legend = this,
  9105. options = legend.options,
  9106. symbolPadding = options.symbolPadding,
  9107. ltr = !options.rtl,
  9108. legendItemPos = item._legendItemPos,
  9109. itemX = legendItemPos[0],
  9110. itemY = legendItemPos[1],
  9111. checkbox = item.checkbox;
  9112. if (item.legendGroup) {
  9113. item.legendGroup.translate(
  9114. ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4,
  9115. itemY
  9116. );
  9117. }
  9118. if (checkbox) {
  9119. checkbox.x = itemX;
  9120. checkbox.y = itemY;
  9121. }
  9122. },
  9123. /**
  9124. * Destroy a single legend item
  9125. * @param {Object} item The series or point
  9126. */
  9127. destroyItem: function (item) {
  9128. var checkbox = item.checkbox;
  9129. // destroy SVG elements
  9130. each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) {
  9131. if (item[key]) {
  9132. item[key] = item[key].destroy();
  9133. }
  9134. });
  9135. if (checkbox) {
  9136. discardElement(item.checkbox);
  9137. }
  9138. },
  9139. /**
  9140. * Destroy all items.
  9141. */
  9142. clearItems: function () {
  9143. var legend = this;
  9144. each(legend.getAllItems(), function (item) {
  9145. legend.destroyItem(item);
  9146. });
  9147. },
  9148. /**
  9149. * Destroys the legend.
  9150. */
  9151. destroy: function () {
  9152. var legend = this,
  9153. legendGroup = legend.group,
  9154. box = legend.box;
  9155. if (box) {
  9156. legend.box = box.destroy();
  9157. }
  9158. if (legendGroup) {
  9159. legend.group = legendGroup.destroy();
  9160. }
  9161. },
  9162. /**
  9163. * Position the checkboxes after the width is determined
  9164. */
  9165. positionCheckboxes: function (scrollOffset) {
  9166. var alignAttr = this.group.alignAttr,
  9167. translateY,
  9168. clipHeight = this.clipHeight || this.legendHeight;
  9169. if (alignAttr) {
  9170. translateY = alignAttr.translateY;
  9171. each(this.allItems, function (item) {
  9172. var checkbox = item.checkbox,
  9173. top;
  9174. if (checkbox) {
  9175. top = (translateY + checkbox.y + (scrollOffset || 0) + 3);
  9176. css(checkbox, {
  9177. left: (alignAttr.translateX + item.checkboxOffset + checkbox.x - 20) + PX,
  9178. top: top + PX,
  9179. display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE
  9180. });
  9181. }
  9182. });
  9183. }
  9184. },
  9185. /**
  9186. * Render the legend title on top of the legend
  9187. */
  9188. renderTitle: function () {
  9189. var options = this.options,
  9190. padding = this.padding,
  9191. titleOptions = options.title,
  9192. titleHeight = 0,
  9193. bBox;
  9194. if (titleOptions.text) {
  9195. if (!this.title) {
  9196. this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title')
  9197. .attr({ zIndex: 1 })
  9198. .css(titleOptions.style)
  9199. .add(this.group);
  9200. }
  9201. bBox = this.title.getBBox();
  9202. titleHeight = bBox.height;
  9203. this.offsetWidth = bBox.width; // #1717
  9204. this.contentGroup.attr({ translateY: titleHeight });
  9205. }
  9206. this.titleHeight = titleHeight;
  9207. },
  9208. /**
  9209. * Render a single specific legend item
  9210. * @param {Object} item A series or point
  9211. */
  9212. renderItem: function (item) {
  9213. var legend = this,
  9214. chart = legend.chart,
  9215. renderer = chart.renderer,
  9216. options = legend.options,
  9217. horizontal = options.layout === 'horizontal',
  9218. symbolWidth = legend.symbolWidth,
  9219. symbolPadding = options.symbolPadding,
  9220. itemStyle = legend.itemStyle,
  9221. itemHiddenStyle = legend.itemHiddenStyle,
  9222. padding = legend.padding,
  9223. itemDistance = horizontal ? pick(options.itemDistance, 20) : 0,
  9224. ltr = !options.rtl,
  9225. itemHeight,
  9226. widthOption = options.width,
  9227. itemMarginBottom = options.itemMarginBottom || 0,
  9228. itemMarginTop = legend.itemMarginTop,
  9229. initialItemX = legend.initialItemX,
  9230. bBox,
  9231. itemWidth,
  9232. li = item.legendItem,
  9233. series = item.series && item.series.drawLegendSymbol ? item.series : item,
  9234. seriesOptions = series.options,
  9235. showCheckbox = legend.createCheckboxForItem && seriesOptions && seriesOptions.showCheckbox,
  9236. useHTML = options.useHTML;
  9237. if (!li) { // generate it once, later move it
  9238. // Generate the group box
  9239. // A group to hold the symbol and text. Text is to be appended in Legend class.
  9240. item.legendGroup = renderer.g('legend-item')
  9241. .attr({ zIndex: 1 })
  9242. .add(legend.scrollGroup);
  9243. // Generate the list item text and add it to the group
  9244. item.legendItem = li = renderer.text(
  9245. options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item),
  9246. ltr ? symbolWidth + symbolPadding : -symbolPadding,
  9247. legend.baseline || 0,
  9248. useHTML
  9249. )
  9250. .css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021)
  9251. .attr({
  9252. align: ltr ? 'left' : 'right',
  9253. zIndex: 2
  9254. })
  9255. .add(item.legendGroup);
  9256. // Get the baseline for the first item - the font size is equal for all
  9257. if (!legend.baseline) {
  9258. legend.fontMetrics = renderer.fontMetrics(itemStyle.fontSize, li);
  9259. legend.baseline = legend.fontMetrics.f + 3 + itemMarginTop;
  9260. li.attr('y', legend.baseline);
  9261. }
  9262. // Draw the legend symbol inside the group box
  9263. series.drawLegendSymbol(legend, item);
  9264. if (legend.setItemEvents) {
  9265. legend.setItemEvents(item, li, useHTML, itemStyle, itemHiddenStyle);
  9266. }
  9267. // Colorize the items
  9268. legend.colorizeItem(item, item.visible);
  9269. // add the HTML checkbox on top
  9270. if (showCheckbox) {
  9271. legend.createCheckboxForItem(item);
  9272. }
  9273. }
  9274. // calculate the positions for the next line
  9275. bBox = li.getBBox();
  9276. itemWidth = item.checkboxOffset =
  9277. options.itemWidth ||
  9278. item.legendItemWidth ||
  9279. symbolWidth + symbolPadding + bBox.width + itemDistance + (showCheckbox ? 20 : 0);
  9280. legend.itemHeight = itemHeight = mathRound(item.legendItemHeight || bBox.height);
  9281. // if the item exceeds the width, start a new line
  9282. if (horizontal && legend.itemX - initialItemX + itemWidth >
  9283. (widthOption || (chart.chartWidth - 2 * padding - initialItemX - options.x))) {
  9284. legend.itemX = initialItemX;
  9285. legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom;
  9286. legend.lastLineHeight = 0; // reset for next line (#915, #3976)
  9287. }
  9288. // If the item exceeds the height, start a new column
  9289. /*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) {
  9290. legend.itemY = legend.initialItemY;
  9291. legend.itemX += legend.maxItemWidth;
  9292. legend.maxItemWidth = 0;
  9293. }*/
  9294. // Set the edge positions
  9295. legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth);
  9296. legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom;
  9297. legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915
  9298. // cache the position of the newly generated or reordered items
  9299. item._legendItemPos = [legend.itemX, legend.itemY];
  9300. // advance
  9301. if (horizontal) {
  9302. legend.itemX += itemWidth;
  9303. } else {
  9304. legend.itemY += itemMarginTop + itemHeight + itemMarginBottom;
  9305. legend.lastLineHeight = itemHeight;
  9306. }
  9307. // the width of the widest item
  9308. legend.offsetWidth = widthOption || mathMax(
  9309. (horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding,
  9310. legend.offsetWidth
  9311. );
  9312. },
  9313. /**
  9314. * Get all items, which is one item per series for normal series and one item per point
  9315. * for pie series.
  9316. */
  9317. getAllItems: function () {
  9318. var allItems = [];
  9319. each(this.chart.series, function (series) {
  9320. var seriesOptions = series.options;
  9321. // Handle showInLegend. If the series is linked to another series, defaults to false.
  9322. if (!pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? UNDEFINED : false, true)) {
  9323. return;
  9324. }
  9325. // use points or series for the legend item depending on legendType
  9326. allItems = allItems.concat(
  9327. series.legendItems ||
  9328. (seriesOptions.legendType === 'point' ?
  9329. series.data :
  9330. series)
  9331. );
  9332. });
  9333. return allItems;
  9334. },
  9335. /**
  9336. * Adjust the chart margins by reserving space for the legend on only one side
  9337. * of the chart. If the position is set to a corner, top or bottom is reserved
  9338. * for horizontal legends and left or right for vertical ones.
  9339. */
  9340. adjustMargins: function (margin, spacing) {
  9341. var chart = this.chart,
  9342. options = this.options,
  9343. // Use the first letter of each alignment option in order to detect the side
  9344. alignment = options.align[0] + options.verticalAlign[0] + options.layout[0];
  9345. if (this.display && !options.floating) {
  9346. each([
  9347. /(lth|ct|rth)/,
  9348. /(rtv|rm|rbv)/,
  9349. /(rbh|cb|lbh)/,
  9350. /(lbv|lm|ltv)/
  9351. ], function (alignments, side) {
  9352. if (alignments.test(alignment) && !defined(margin[side])) {
  9353. // Now we have detected on which side of the chart we should reserve space for the legend
  9354. chart[marginNames[side]] = mathMax(
  9355. chart[marginNames[side]],
  9356. chart.legend[(side + 1) % 2 ? 'legendHeight' : 'legendWidth'] +
  9357. [1, -1, -1, 1][side] * options[(side % 2) ? 'x' : 'y'] +
  9358. pick(options.margin, 12) +
  9359. spacing[side]
  9360. );
  9361. }
  9362. });
  9363. }
  9364. },
  9365. /**
  9366. * Render the legend. This method can be called both before and after
  9367. * chart.render. If called after, it will only rearrange items instead
  9368. * of creating new ones.
  9369. */
  9370. render: function () {
  9371. var legend = this,
  9372. chart = legend.chart,
  9373. renderer = chart.renderer,
  9374. legendGroup = legend.group,
  9375. allItems,
  9376. display,
  9377. legendWidth,
  9378. legendHeight,
  9379. box = legend.box,
  9380. options = legend.options,
  9381. padding = legend.padding,
  9382. legendBorderWidth = options.borderWidth,
  9383. legendBackgroundColor = options.backgroundColor;
  9384. legend.itemX = legend.initialItemX;
  9385. legend.itemY = legend.initialItemY;
  9386. legend.offsetWidth = 0;
  9387. legend.lastItemY = 0;
  9388. if (!legendGroup) {
  9389. legend.group = legendGroup = renderer.g('legend')
  9390. .attr({ zIndex: 7 })
  9391. .add();
  9392. legend.contentGroup = renderer.g()
  9393. .attr({ zIndex: 1 }) // above background
  9394. .add(legendGroup);
  9395. legend.scrollGroup = renderer.g()
  9396. .add(legend.contentGroup);
  9397. }
  9398. legend.renderTitle();
  9399. // add each series or point
  9400. allItems = legend.getAllItems();
  9401. // sort by legendIndex
  9402. stableSort(allItems, function (a, b) {
  9403. return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0);
  9404. });
  9405. // reversed legend
  9406. if (options.reversed) {
  9407. allItems.reverse();
  9408. }
  9409. legend.allItems = allItems;
  9410. legend.display = display = !!allItems.length;
  9411. // render the items
  9412. legend.lastLineHeight = 0;
  9413. each(allItems, function (item) {
  9414. legend.renderItem(item);
  9415. });
  9416. // Get the box
  9417. legendWidth = (options.width || legend.offsetWidth) + padding;
  9418. legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight;
  9419. legendHeight = legend.handleOverflow(legendHeight);
  9420. legendHeight += padding;
  9421. // Draw the border and/or background
  9422. if (legendBorderWidth || legendBackgroundColor) {
  9423. if (!box) {
  9424. legend.box = box = renderer.rect(
  9425. 0,
  9426. 0,
  9427. legendWidth,
  9428. legendHeight,
  9429. options.borderRadius,
  9430. legendBorderWidth || 0
  9431. ).attr({
  9432. stroke: options.borderColor,
  9433. 'stroke-width': legendBorderWidth || 0,
  9434. fill: legendBackgroundColor || NONE
  9435. })
  9436. .add(legendGroup)
  9437. .shadow(options.shadow);
  9438. box.isNew = true;
  9439. } else if (legendWidth > 0 && legendHeight > 0) {
  9440. box[box.isNew ? 'attr' : 'animate'](
  9441. box.crisp({ width: legendWidth, height: legendHeight })
  9442. );
  9443. box.isNew = false;
  9444. }
  9445. // hide the border if no items
  9446. box[display ? 'show' : 'hide']();
  9447. }
  9448. legend.legendWidth = legendWidth;
  9449. legend.legendHeight = legendHeight;
  9450. // Now that the legend width and height are established, put the items in the
  9451. // final position
  9452. each(allItems, function (item) {
  9453. legend.positionItem(item);
  9454. });
  9455. // 1.x compatibility: positioning based on style
  9456. /*var props = ['left', 'right', 'top', 'bottom'],
  9457. prop,
  9458. i = 4;
  9459. while (i--) {
  9460. prop = props[i];
  9461. if (options.style[prop] && options.style[prop] !== 'auto') {
  9462. options[i < 2 ? 'align' : 'verticalAlign'] = prop;
  9463. options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1);
  9464. }
  9465. }*/
  9466. if (display) {
  9467. legendGroup.align(extend({
  9468. width: legendWidth,
  9469. height: legendHeight
  9470. }, options), true, 'spacingBox');
  9471. }
  9472. if (!chart.isResizing) {
  9473. this.positionCheckboxes();
  9474. }
  9475. },
  9476. /**
  9477. * Set up the overflow handling by adding navigation with up and down arrows below the
  9478. * legend.
  9479. */
  9480. handleOverflow: function (legendHeight) {
  9481. var legend = this,
  9482. chart = this.chart,
  9483. renderer = chart.renderer,
  9484. options = this.options,
  9485. optionsY = options.y,
  9486. alignTop = options.verticalAlign === 'top',
  9487. spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding,
  9488. maxHeight = options.maxHeight,
  9489. clipHeight,
  9490. clipRect = this.clipRect,
  9491. navOptions = options.navigation,
  9492. animation = pick(navOptions.animation, true),
  9493. arrowSize = navOptions.arrowSize || 12,
  9494. nav = this.nav,
  9495. pages = this.pages,
  9496. lastY,
  9497. allItems = this.allItems;
  9498. // Adjust the height
  9499. if (options.layout === 'horizontal') {
  9500. spaceHeight /= 2;
  9501. }
  9502. if (maxHeight) {
  9503. spaceHeight = mathMin(spaceHeight, maxHeight);
  9504. }
  9505. // Reset the legend height and adjust the clipping rectangle
  9506. pages.length = 0;
  9507. if (legendHeight > spaceHeight && !options.useHTML) {
  9508. this.clipHeight = clipHeight = mathMax(spaceHeight - 20 - this.titleHeight - this.padding, 0);
  9509. this.currentPage = pick(this.currentPage, 1);
  9510. this.fullHeight = legendHeight;
  9511. // Fill pages with Y positions so that the top of each a legend item defines
  9512. // the scroll top for each page (#2098)
  9513. each(allItems, function (item, i) {
  9514. var y = item._legendItemPos[1],
  9515. h = mathRound(item.legendItem.getBBox().height),
  9516. len = pages.length;
  9517. if (!len || (y - pages[len - 1] > clipHeight && (lastY || y) !== pages[len - 1])) {
  9518. pages.push(lastY || y);
  9519. len++;
  9520. }
  9521. if (i === allItems.length - 1 && y + h - pages[len - 1] > clipHeight) {
  9522. pages.push(y);
  9523. }
  9524. if (y !== lastY) {
  9525. lastY = y;
  9526. }
  9527. });
  9528. // Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787)
  9529. if (!clipRect) {
  9530. clipRect = legend.clipRect = renderer.clipRect(0, this.padding, 9999, 0);
  9531. legend.contentGroup.clip(clipRect);
  9532. }
  9533. clipRect.attr({
  9534. height: clipHeight
  9535. });
  9536. // Add navigation elements
  9537. if (!nav) {
  9538. this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group);
  9539. this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize)
  9540. .on('click', function () {
  9541. legend.scroll(-1, animation);
  9542. })
  9543. .add(nav);
  9544. this.pager = renderer.text('', 15, 10)
  9545. .css(navOptions.style)
  9546. .add(nav);
  9547. this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize)
  9548. .on('click', function () {
  9549. legend.scroll(1, animation);
  9550. })
  9551. .add(nav);
  9552. }
  9553. // Set initial position
  9554. legend.scroll(0);
  9555. legendHeight = spaceHeight;
  9556. } else if (nav) {
  9557. clipRect.attr({
  9558. height: chart.chartHeight
  9559. });
  9560. nav.hide();
  9561. this.scrollGroup.attr({
  9562. translateY: 1
  9563. });
  9564. this.clipHeight = 0; // #1379
  9565. }
  9566. return legendHeight;
  9567. },
  9568. /**
  9569. * Scroll the legend by a number of pages
  9570. * @param {Object} scrollBy
  9571. * @param {Object} animation
  9572. */
  9573. scroll: function (scrollBy, animation) {
  9574. var pages = this.pages,
  9575. pageCount = pages.length,
  9576. currentPage = this.currentPage + scrollBy,
  9577. clipHeight = this.clipHeight,
  9578. navOptions = this.options.navigation,
  9579. activeColor = navOptions.activeColor,
  9580. inactiveColor = navOptions.inactiveColor,
  9581. pager = this.pager,
  9582. padding = this.padding,
  9583. scrollOffset;
  9584. // When resizing while looking at the last page
  9585. if (currentPage > pageCount) {
  9586. currentPage = pageCount;
  9587. }
  9588. if (currentPage > 0) {
  9589. if (animation !== UNDEFINED) {
  9590. setAnimation(animation, this.chart);
  9591. }
  9592. this.nav.attr({
  9593. translateX: padding,
  9594. translateY: clipHeight + this.padding + 7 + this.titleHeight,
  9595. visibility: VISIBLE
  9596. });
  9597. this.up.attr({
  9598. fill: currentPage === 1 ? inactiveColor : activeColor
  9599. })
  9600. .css({
  9601. cursor: currentPage === 1 ? 'default' : 'pointer'
  9602. });
  9603. pager.attr({
  9604. text: currentPage + '/' + pageCount
  9605. });
  9606. this.down.attr({
  9607. x: 18 + this.pager.getBBox().width, // adjust to text width
  9608. fill: currentPage === pageCount ? inactiveColor : activeColor
  9609. })
  9610. .css({
  9611. cursor: currentPage === pageCount ? 'default' : 'pointer'
  9612. });
  9613. scrollOffset = -pages[currentPage - 1] + this.initialItemY;
  9614. this.scrollGroup.animate({
  9615. translateY: scrollOffset
  9616. });
  9617. this.currentPage = currentPage;
  9618. this.positionCheckboxes(scrollOffset);
  9619. }
  9620. }
  9621. };
  9622. /*
  9623. * LegendSymbolMixin
  9624. */
  9625. var LegendSymbolMixin = Highcharts.LegendSymbolMixin = {
  9626. /**
  9627. * Get the series' symbol in the legend
  9628. *
  9629. * @param {Object} legend The legend object
  9630. * @param {Object} item The series (this) or point
  9631. */
  9632. drawRectangle: function (legend, item) {
  9633. var symbolHeight = legend.options.symbolHeight || legend.fontMetrics.f;
  9634. item.legendSymbol = this.chart.renderer.rect(
  9635. 0,
  9636. legend.baseline - symbolHeight + 1, // #3988
  9637. legend.symbolWidth,
  9638. symbolHeight,
  9639. legend.options.symbolRadius || 0
  9640. ).attr({
  9641. zIndex: 3
  9642. }).add(item.legendGroup);
  9643. },
  9644. /**
  9645. * Get the series' symbol in the legend. This method should be overridable to create custom
  9646. * symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols.
  9647. *
  9648. * @param {Object} legend The legend object
  9649. */
  9650. drawLineMarker: function (legend) {
  9651. var options = this.options,
  9652. markerOptions = options.marker,
  9653. radius,
  9654. legendSymbol,
  9655. symbolWidth = legend.symbolWidth,
  9656. renderer = this.chart.renderer,
  9657. legendItemGroup = this.legendGroup,
  9658. verticalCenter = legend.baseline - mathRound(legend.fontMetrics.b * 0.3),
  9659. attr;
  9660. // Draw the line
  9661. if (options.lineWidth) {
  9662. attr = {
  9663. 'stroke-width': options.lineWidth
  9664. };
  9665. if (options.dashStyle) {
  9666. attr.dashstyle = options.dashStyle;
  9667. }
  9668. this.legendLine = renderer.path([
  9669. M,
  9670. 0,
  9671. verticalCenter,
  9672. L,
  9673. symbolWidth,
  9674. verticalCenter
  9675. ])
  9676. .attr(attr)
  9677. .add(legendItemGroup);
  9678. }
  9679. // Draw the marker
  9680. if (markerOptions && markerOptions.enabled !== false) {
  9681. radius = markerOptions.radius;
  9682. this.legendSymbol = legendSymbol = renderer.symbol(
  9683. this.symbol,
  9684. (symbolWidth / 2) - radius,
  9685. verticalCenter - radius,
  9686. 2 * radius,
  9687. 2 * radius
  9688. )
  9689. .add(legendItemGroup);
  9690. legendSymbol.isMarker = true;
  9691. }
  9692. }
  9693. };
  9694. // Workaround for #2030, horizontal legend items not displaying in IE11 Preview,
  9695. // and for #2580, a similar drawing flaw in Firefox 26.
  9696. // TODO: Explore if there's a general cause for this. The problem may be related
  9697. // to nested group elements, as the legend item texts are within 4 group elements.
  9698. if (/Trident\/7\.0/.test(userAgent) || isFirefox) {
  9699. wrap(Legend.prototype, 'positionItem', function (proceed, item) {
  9700. var legend = this,
  9701. runPositionItem = function () { // If chart destroyed in sync, this is undefined (#2030)
  9702. if (item._legendItemPos) {
  9703. proceed.call(legend, item);
  9704. }
  9705. };
  9706. // Do it now, for export and to get checkbox placement
  9707. runPositionItem();
  9708. // Do it after to work around the core issue
  9709. setTimeout(runPositionItem);
  9710. });
  9711. }
  9712. /**
  9713. * The chart class
  9714. * @param {Object} options
  9715. * @param {Function} callback Function to run when the chart has loaded
  9716. */
  9717. var Chart = Highcharts.Chart = function () {
  9718. this.init.apply(this, arguments);
  9719. };
  9720. Chart.prototype = {
  9721. /**
  9722. * Hook for modules
  9723. */
  9724. callbacks: [],
  9725. /**
  9726. * Initialize the chart
  9727. */
  9728. init: function (userOptions, callback) {
  9729. // Handle regular options
  9730. var options,
  9731. seriesOptions = userOptions.series; // skip merging data points to increase performance
  9732. userOptions.series = null;
  9733. options = merge(defaultOptions, userOptions); // do the merge
  9734. options.series = userOptions.series = seriesOptions; // set back the series data
  9735. this.userOptions = userOptions;
  9736. var optionsChart = options.chart;
  9737. // Create margin & spacing array
  9738. this.margin = this.splashArray('margin', optionsChart);
  9739. this.spacing = this.splashArray('spacing', optionsChart);
  9740. var chartEvents = optionsChart.events;
  9741. //this.runChartClick = chartEvents && !!chartEvents.click;
  9742. this.bounds = { h: {}, v: {} }; // Pixel data bounds for touch zoom
  9743. this.callback = callback;
  9744. this.isResizing = 0;
  9745. this.options = options;
  9746. //chartTitleOptions = UNDEFINED;
  9747. //chartSubtitleOptions = UNDEFINED;
  9748. this.axes = [];
  9749. this.series = [];
  9750. this.hasCartesianSeries = optionsChart.showAxes;
  9751. //this.axisOffset = UNDEFINED;
  9752. //this.maxTicks = UNDEFINED; // handle the greatest amount of ticks on grouped axes
  9753. //this.inverted = UNDEFINED;
  9754. //this.loadingShown = UNDEFINED;
  9755. //this.container = UNDEFINED;
  9756. //this.chartWidth = UNDEFINED;
  9757. //this.chartHeight = UNDEFINED;
  9758. //this.marginRight = UNDEFINED;
  9759. //this.marginBottom = UNDEFINED;
  9760. //this.containerWidth = UNDEFINED;
  9761. //this.containerHeight = UNDEFINED;
  9762. //this.oldChartWidth = UNDEFINED;
  9763. //this.oldChartHeight = UNDEFINED;
  9764. //this.renderTo = UNDEFINED;
  9765. //this.renderToClone = UNDEFINED;
  9766. //this.spacingBox = UNDEFINED
  9767. //this.legend = UNDEFINED;
  9768. // Elements
  9769. //this.chartBackground = UNDEFINED;
  9770. //this.plotBackground = UNDEFINED;
  9771. //this.plotBGImage = UNDEFINED;
  9772. //this.plotBorder = UNDEFINED;
  9773. //this.loadingDiv = UNDEFINED;
  9774. //this.loadingSpan = UNDEFINED;
  9775. var chart = this,
  9776. eventType;
  9777. // Add the chart to the global lookup
  9778. chart.index = charts.length;
  9779. charts.push(chart);
  9780. chartCount++;
  9781. // Set up auto resize
  9782. if (optionsChart.reflow !== false) {
  9783. addEvent(chart, 'load', function () {
  9784. chart.initReflow();
  9785. });
  9786. }
  9787. // Chart event handlers
  9788. if (chartEvents) {
  9789. for (eventType in chartEvents) {
  9790. addEvent(chart, eventType, chartEvents[eventType]);
  9791. }
  9792. }
  9793. chart.xAxis = [];
  9794. chart.yAxis = [];
  9795. // Expose methods and variables
  9796. chart.animation = useCanVG ? false : pick(optionsChart.animation, true);
  9797. chart.pointCount = chart.colorCounter = chart.symbolCounter = 0;
  9798. chart.firstRender();
  9799. },
  9800. /**
  9801. * Initialize an individual series, called internally before render time
  9802. */
  9803. initSeries: function (options) {
  9804. var chart = this,
  9805. optionsChart = chart.options.chart,
  9806. type = options.type || optionsChart.type || optionsChart.defaultSeriesType,
  9807. series,
  9808. constr = seriesTypes[type];
  9809. // No such series type
  9810. if (!constr) {
  9811. error(17, true);
  9812. }
  9813. series = new constr();
  9814. series.init(this, options);
  9815. return series;
  9816. },
  9817. /**
  9818. * Check whether a given point is within the plot area
  9819. *
  9820. * @param {Number} plotX Pixel x relative to the plot area
  9821. * @param {Number} plotY Pixel y relative to the plot area
  9822. * @param {Boolean} inverted Whether the chart is inverted
  9823. */
  9824. isInsidePlot: function (plotX, plotY, inverted) {
  9825. var x = inverted ? plotY : plotX,
  9826. y = inverted ? plotX : plotY;
  9827. return x >= 0 &&
  9828. x <= this.plotWidth &&
  9829. y >= 0 &&
  9830. y <= this.plotHeight;
  9831. },
  9832. /**
  9833. * Redraw legend, axes or series based on updated data
  9834. *
  9835. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  9836. * configuration
  9837. */
  9838. redraw: function (animation) {
  9839. var chart = this,
  9840. axes = chart.axes,
  9841. series = chart.series,
  9842. pointer = chart.pointer,
  9843. legend = chart.legend,
  9844. redrawLegend = chart.isDirtyLegend,
  9845. hasStackedSeries,
  9846. hasDirtyStacks,
  9847. hasCartesianSeries = chart.hasCartesianSeries,
  9848. isDirtyBox = chart.isDirtyBox, // todo: check if it has actually changed?
  9849. seriesLength = series.length,
  9850. i = seriesLength,
  9851. serie,
  9852. renderer = chart.renderer,
  9853. isHiddenChart = renderer.isHidden(),
  9854. afterRedraw = [];
  9855. setAnimation(animation, chart);
  9856. if (isHiddenChart) {
  9857. chart.cloneRenderTo();
  9858. }
  9859. // Adjust title layout (reflow multiline text)
  9860. chart.layOutTitles();
  9861. // link stacked series
  9862. while (i--) {
  9863. serie = series[i];
  9864. if (serie.options.stacking) {
  9865. hasStackedSeries = true;
  9866. if (serie.isDirty) {
  9867. hasDirtyStacks = true;
  9868. break;
  9869. }
  9870. }
  9871. }
  9872. if (hasDirtyStacks) { // mark others as dirty
  9873. i = seriesLength;
  9874. while (i--) {
  9875. serie = series[i];
  9876. if (serie.options.stacking) {
  9877. serie.isDirty = true;
  9878. }
  9879. }
  9880. }
  9881. // handle updated data in the series
  9882. each(series, function (serie) {
  9883. if (serie.isDirty) { // prepare the data so axis can read it
  9884. if (serie.options.legendType === 'point') {
  9885. redrawLegend = true;
  9886. }
  9887. }
  9888. });
  9889. // handle added or removed series
  9890. if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed
  9891. // draw legend graphics
  9892. legend.render();
  9893. chart.isDirtyLegend = false;
  9894. }
  9895. // reset stacks
  9896. if (hasStackedSeries) {
  9897. chart.getStacks();
  9898. }
  9899. if (hasCartesianSeries) {
  9900. if (!chart.isResizing) {
  9901. // reset maxTicks
  9902. chart.maxTicks = null;
  9903. // set axes scales
  9904. each(axes, function (axis) {
  9905. axis.setScale();
  9906. });
  9907. }
  9908. }
  9909. chart.getMargins(); // #3098
  9910. if (hasCartesianSeries) {
  9911. // If one axis is dirty, all axes must be redrawn (#792, #2169)
  9912. each(axes, function (axis) {
  9913. if (axis.isDirty) {
  9914. isDirtyBox = true;
  9915. }
  9916. });
  9917. // redraw axes
  9918. each(axes, function (axis) {
  9919. // Fire 'afterSetExtremes' only if extremes are set
  9920. if (axis.isDirtyExtremes) { // #821
  9921. axis.isDirtyExtremes = false;
  9922. afterRedraw.push(function () { // prevent a recursive call to chart.redraw() (#1119)
  9923. fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751
  9924. delete axis.eventArgs;
  9925. });
  9926. }
  9927. if (isDirtyBox || hasStackedSeries) {
  9928. axis.redraw();
  9929. }
  9930. });
  9931. }
  9932. // the plot areas size has changed
  9933. if (isDirtyBox) {
  9934. chart.drawChartBox();
  9935. }
  9936. // redraw affected series
  9937. each(series, function (serie) {
  9938. if (serie.isDirty && serie.visible &&
  9939. (!serie.isCartesian || serie.xAxis)) { // issue #153
  9940. serie.redraw();
  9941. }
  9942. });
  9943. // move tooltip or reset
  9944. if (pointer) {
  9945. pointer.reset(true);
  9946. }
  9947. // redraw if canvas
  9948. renderer.draw();
  9949. // fire the event
  9950. fireEvent(chart, 'redraw'); // jQuery breaks this when calling it from addEvent. Overwrites chart.redraw
  9951. if (isHiddenChart) {
  9952. chart.cloneRenderTo(true);
  9953. }
  9954. // Fire callbacks that are put on hold until after the redraw
  9955. each(afterRedraw, function (callback) {
  9956. callback.call();
  9957. });
  9958. },
  9959. /**
  9960. * Get an axis, series or point object by id.
  9961. * @param id {String} The id as given in the configuration options
  9962. */
  9963. get: function (id) {
  9964. var chart = this,
  9965. axes = chart.axes,
  9966. series = chart.series;
  9967. var i,
  9968. j,
  9969. points;
  9970. // search axes
  9971. for (i = 0; i < axes.length; i++) {
  9972. if (axes[i].options.id === id) {
  9973. return axes[i];
  9974. }
  9975. }
  9976. // search series
  9977. for (i = 0; i < series.length; i++) {
  9978. if (series[i].options.id === id) {
  9979. return series[i];
  9980. }
  9981. }
  9982. // search points
  9983. for (i = 0; i < series.length; i++) {
  9984. points = series[i].points || [];
  9985. for (j = 0; j < points.length; j++) {
  9986. if (points[j].id === id) {
  9987. return points[j];
  9988. }
  9989. }
  9990. }
  9991. return null;
  9992. },
  9993. /**
  9994. * Create the Axis instances based on the config options
  9995. */
  9996. getAxes: function () {
  9997. var chart = this,
  9998. options = this.options,
  9999. xAxisOptions = options.xAxis = splat(options.xAxis || {}),
  10000. yAxisOptions = options.yAxis = splat(options.yAxis || {}),
  10001. optionsArray,
  10002. axis;
  10003. // make sure the options are arrays and add some members
  10004. each(xAxisOptions, function (axis, i) {
  10005. axis.index = i;
  10006. axis.isX = true;
  10007. });
  10008. each(yAxisOptions, function (axis, i) {
  10009. axis.index = i;
  10010. });
  10011. // concatenate all axis options into one array
  10012. optionsArray = xAxisOptions.concat(yAxisOptions);
  10013. each(optionsArray, function (axisOptions) {
  10014. axis = new Axis(chart, axisOptions);
  10015. });
  10016. },
  10017. /**
  10018. * Get the currently selected points from all series
  10019. */
  10020. getSelectedPoints: function () {
  10021. var points = [];
  10022. each(this.series, function (serie) {
  10023. points = points.concat(grep(serie.points || [], function (point) {
  10024. return point.selected;
  10025. }));
  10026. });
  10027. return points;
  10028. },
  10029. /**
  10030. * Get the currently selected series
  10031. */
  10032. getSelectedSeries: function () {
  10033. return grep(this.series, function (serie) {
  10034. return serie.selected;
  10035. });
  10036. },
  10037. /**
  10038. * Generate stacks for each series and calculate stacks total values
  10039. */
  10040. getStacks: function () {
  10041. var chart = this;
  10042. // reset stacks for each yAxis
  10043. each(chart.yAxis, function (axis) {
  10044. if (axis.stacks && axis.hasVisibleSeries) {
  10045. axis.oldStacks = axis.stacks;
  10046. }
  10047. });
  10048. each(chart.series, function (series) {
  10049. if (series.options.stacking && (series.visible === true || chart.options.chart.ignoreHiddenSeries === false)) {
  10050. series.stackKey = series.type + pick(series.options.stack, '');
  10051. }
  10052. });
  10053. },
  10054. /**
  10055. * Show the title and subtitle of the chart
  10056. *
  10057. * @param titleOptions {Object} New title options
  10058. * @param subtitleOptions {Object} New subtitle options
  10059. *
  10060. */
  10061. setTitle: function (titleOptions, subtitleOptions, redraw) {
  10062. var chart = this,
  10063. options = chart.options,
  10064. chartTitleOptions,
  10065. chartSubtitleOptions;
  10066. chartTitleOptions = options.title = merge(options.title, titleOptions);
  10067. chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions);
  10068. // add title and subtitle
  10069. each([
  10070. ['title', titleOptions, chartTitleOptions],
  10071. ['subtitle', subtitleOptions, chartSubtitleOptions]
  10072. ], function (arr) {
  10073. var name = arr[0],
  10074. title = chart[name],
  10075. titleOptions = arr[1],
  10076. chartTitleOptions = arr[2];
  10077. if (title && titleOptions) {
  10078. chart[name] = title = title.destroy(); // remove old
  10079. }
  10080. if (chartTitleOptions && chartTitleOptions.text && !title) {
  10081. chart[name] = chart.renderer.text(
  10082. chartTitleOptions.text,
  10083. 0,
  10084. 0,
  10085. chartTitleOptions.useHTML
  10086. )
  10087. .attr({
  10088. align: chartTitleOptions.align,
  10089. 'class': PREFIX + name,
  10090. zIndex: chartTitleOptions.zIndex || 4
  10091. })
  10092. .css(chartTitleOptions.style)
  10093. .add();
  10094. }
  10095. });
  10096. chart.layOutTitles(redraw);
  10097. },
  10098. /**
  10099. * Lay out the chart titles and cache the full offset height for use in getMargins
  10100. */
  10101. layOutTitles: function (redraw) {
  10102. var titleOffset = 0,
  10103. title = this.title,
  10104. subtitle = this.subtitle,
  10105. options = this.options,
  10106. titleOptions = options.title,
  10107. subtitleOptions = options.subtitle,
  10108. requiresDirtyBox,
  10109. renderer = this.renderer,
  10110. autoWidth = this.spacingBox.width - 44; // 44 makes room for default context button
  10111. if (title) {
  10112. title
  10113. .css({ width: (titleOptions.width || autoWidth) + PX })
  10114. .align(extend({
  10115. y: renderer.fontMetrics(titleOptions.style.fontSize, title).b - 3
  10116. }, titleOptions), false, 'spacingBox');
  10117. if (!titleOptions.floating && !titleOptions.verticalAlign) {
  10118. titleOffset = title.getBBox().height;
  10119. }
  10120. }
  10121. if (subtitle) {
  10122. subtitle
  10123. .css({ width: (subtitleOptions.width || autoWidth) + PX })
  10124. .align(extend({
  10125. y: titleOffset + (titleOptions.margin - 13) + renderer.fontMetrics(titleOptions.style.fontSize, subtitle).b
  10126. }, subtitleOptions), false, 'spacingBox');
  10127. if (!subtitleOptions.floating && !subtitleOptions.verticalAlign) {
  10128. titleOffset = mathCeil(titleOffset + subtitle.getBBox().height);
  10129. }
  10130. }
  10131. requiresDirtyBox = this.titleOffset !== titleOffset;
  10132. this.titleOffset = titleOffset; // used in getMargins
  10133. if (!this.isDirtyBox && requiresDirtyBox) {
  10134. this.isDirtyBox = requiresDirtyBox;
  10135. // Redraw if necessary (#2719, #2744)
  10136. if (this.hasRendered && pick(redraw, true) && this.isDirtyBox) {
  10137. this.redraw();
  10138. }
  10139. }
  10140. },
  10141. /**
  10142. * Get chart width and height according to options and container size
  10143. */
  10144. getChartSize: function () {
  10145. var chart = this,
  10146. optionsChart = chart.options.chart,
  10147. widthOption = optionsChart.width,
  10148. heightOption = optionsChart.height,
  10149. renderTo = chart.renderToClone || chart.renderTo;
  10150. // get inner width and height from jQuery (#824)
  10151. if (!defined(widthOption)) {
  10152. chart.containerWidth = adapterRun(renderTo, 'width');
  10153. }
  10154. if (!defined(heightOption)) {
  10155. chart.containerHeight = adapterRun(renderTo, 'height');
  10156. }
  10157. chart.chartWidth = mathMax(0, widthOption || chart.containerWidth || 600); // #1393, 1460
  10158. chart.chartHeight = mathMax(0, pick(heightOption,
  10159. // the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7:
  10160. chart.containerHeight > 19 ? chart.containerHeight : 400));
  10161. },
  10162. /**
  10163. * Create a clone of the chart's renderTo div and place it outside the viewport to allow
  10164. * size computation on chart.render and chart.redraw
  10165. */
  10166. cloneRenderTo: function (revert) {
  10167. var clone = this.renderToClone,
  10168. container = this.container;
  10169. // Destroy the clone and bring the container back to the real renderTo div
  10170. if (revert) {
  10171. if (clone) {
  10172. this.renderTo.appendChild(container);
  10173. discardElement(clone);
  10174. delete this.renderToClone;
  10175. }
  10176. // Set up the clone
  10177. } else {
  10178. if (container && container.parentNode === this.renderTo) {
  10179. this.renderTo.removeChild(container); // do not clone this
  10180. }
  10181. this.renderToClone = clone = this.renderTo.cloneNode(0);
  10182. css(clone, {
  10183. position: ABSOLUTE,
  10184. top: '-9999px',
  10185. display: 'block' // #833
  10186. });
  10187. if (clone.style.setProperty) { // #2631
  10188. clone.style.setProperty('display', 'block', 'important');
  10189. }
  10190. doc.body.appendChild(clone);
  10191. if (container) {
  10192. clone.appendChild(container);
  10193. }
  10194. }
  10195. },
  10196. /**
  10197. * Get the containing element, determine the size and create the inner container
  10198. * div to hold the chart
  10199. */
  10200. getContainer: function () {
  10201. var chart = this,
  10202. container,
  10203. optionsChart = chart.options.chart,
  10204. chartWidth,
  10205. chartHeight,
  10206. renderTo,
  10207. indexAttrName = 'data-highcharts-chart',
  10208. oldChartIndex,
  10209. containerId;
  10210. chart.renderTo = renderTo = optionsChart.renderTo;
  10211. containerId = PREFIX + idCounter++;
  10212. if (isString(renderTo)) {
  10213. chart.renderTo = renderTo = doc.getElementById(renderTo);
  10214. }
  10215. // Display an error if the renderTo is wrong
  10216. if (!renderTo) {
  10217. error(13, true);
  10218. }
  10219. // If the container already holds a chart, destroy it. The check for hasRendered is there
  10220. // because web pages that are saved to disk from the browser, will preserve the data-highcharts-chart
  10221. // attribute and the SVG contents, but not an interactive chart. So in this case,
  10222. // charts[oldChartIndex] will point to the wrong chart if any (#2609).
  10223. oldChartIndex = pInt(attr(renderTo, indexAttrName));
  10224. if (!isNaN(oldChartIndex) && charts[oldChartIndex] && charts[oldChartIndex].hasRendered) {
  10225. charts[oldChartIndex].destroy();
  10226. }
  10227. // Make a reference to the chart from the div
  10228. attr(renderTo, indexAttrName, chart.index);
  10229. // remove previous chart
  10230. renderTo.innerHTML = '';
  10231. // If the container doesn't have an offsetWidth, it has or is a child of a node
  10232. // that has display:none. We need to temporarily move it out to a visible
  10233. // state to determine the size, else the legend and tooltips won't render
  10234. // properly. The allowClone option is used in sparklines as a micro optimization,
  10235. // saving about 1-2 ms each chart.
  10236. if (!optionsChart.skipClone && !renderTo.offsetWidth) {
  10237. chart.cloneRenderTo();
  10238. }
  10239. // get the width and height
  10240. chart.getChartSize();
  10241. chartWidth = chart.chartWidth;
  10242. chartHeight = chart.chartHeight;
  10243. // create the inner container
  10244. chart.container = container = createElement(DIV, {
  10245. className: PREFIX + 'container' +
  10246. (optionsChart.className ? ' ' + optionsChart.className : ''),
  10247. id: containerId
  10248. }, extend({
  10249. position: RELATIVE,
  10250. overflow: HIDDEN, // needed for context menu (avoid scrollbars) and
  10251. // content overflow in IE
  10252. width: chartWidth + PX,
  10253. height: chartHeight + PX,
  10254. textAlign: 'left',
  10255. lineHeight: 'normal', // #427
  10256. zIndex: 0, // #1072
  10257. '-webkit-tap-highlight-color': 'rgba(0,0,0,0)'
  10258. }, optionsChart.style),
  10259. chart.renderToClone || renderTo
  10260. );
  10261. // cache the cursor (#1650)
  10262. chart._cursor = container.style.cursor;
  10263. // Initialize the renderer
  10264. chart.renderer =
  10265. optionsChart.forExport ? // force SVG, used for SVG export
  10266. new SVGRenderer(container, chartWidth, chartHeight, optionsChart.style, true) :
  10267. new Renderer(container, chartWidth, chartHeight, optionsChart.style);
  10268. if (useCanVG) {
  10269. // If we need canvg library, extend and configure the renderer
  10270. // to get the tracker for translating mouse events
  10271. chart.renderer.create(chart, container, chartWidth, chartHeight);
  10272. }
  10273. // Add a reference to the charts index
  10274. chart.renderer.chartIndex = chart.index;
  10275. },
  10276. /**
  10277. * Calculate margins by rendering axis labels in a preliminary position. Title,
  10278. * subtitle and legend have already been rendered at this stage, but will be
  10279. * moved into their final positions
  10280. */
  10281. getMargins: function (skipAxes) {
  10282. var chart = this,
  10283. spacing = chart.spacing,
  10284. margin = chart.margin,
  10285. titleOffset = chart.titleOffset;
  10286. chart.resetMargins();
  10287. // Adjust for title and subtitle
  10288. if (titleOffset && !defined(margin[0])) {
  10289. chart.plotTop = mathMax(chart.plotTop, titleOffset + chart.options.title.margin + spacing[0]);
  10290. }
  10291. // Adjust for legend
  10292. chart.legend.adjustMargins(margin, spacing);
  10293. // adjust for scroller
  10294. if (chart.extraBottomMargin) {
  10295. chart.marginBottom += chart.extraBottomMargin;
  10296. }
  10297. if (chart.extraTopMargin) {
  10298. chart.plotTop += chart.extraTopMargin;
  10299. }
  10300. if (!skipAxes) {
  10301. this.getAxisMargins();
  10302. }
  10303. },
  10304. getAxisMargins: function () {
  10305. var chart = this,
  10306. axisOffset = chart.axisOffset = [0, 0, 0, 0], // top, right, bottom, left
  10307. margin = chart.margin;
  10308. // pre-render axes to get labels offset width
  10309. if (chart.hasCartesianSeries) {
  10310. each(chart.axes, function (axis) {
  10311. axis.getOffset();
  10312. });
  10313. }
  10314. // Add the axis offsets
  10315. each(marginNames, function (m, side) {
  10316. if (!defined(margin[side])) {
  10317. chart[m] += axisOffset[side];
  10318. }
  10319. });
  10320. chart.setChartSize();
  10321. },
  10322. /**
  10323. * Resize the chart to its container if size is not explicitly set
  10324. */
  10325. reflow: function (e) {
  10326. var chart = this,
  10327. optionsChart = chart.options.chart,
  10328. renderTo = chart.renderTo,
  10329. width = optionsChart.width || adapterRun(renderTo, 'width'),
  10330. height = optionsChart.height || adapterRun(renderTo, 'height'),
  10331. target = e ? e.target : win, // #805 - MooTools doesn't supply e
  10332. doReflow = function () {
  10333. if (chart.container) { // It may have been destroyed in the meantime (#1257)
  10334. chart.setSize(width, height, false);
  10335. chart.hasUserSize = null;
  10336. }
  10337. };
  10338. // Width and height checks for display:none. Target is doc in IE8 and Opera,
  10339. // win in Firefox, Chrome and IE9.
  10340. if (!chart.hasUserSize && !chart.isPrinting && width && height && (target === win || target === doc)) { // #1093
  10341. if (width !== chart.containerWidth || height !== chart.containerHeight) {
  10342. clearTimeout(chart.reflowTimeout);
  10343. if (e) { // Called from window.resize
  10344. chart.reflowTimeout = setTimeout(doReflow, 100);
  10345. } else { // Called directly (#2224)
  10346. doReflow();
  10347. }
  10348. }
  10349. chart.containerWidth = width;
  10350. chart.containerHeight = height;
  10351. }
  10352. },
  10353. /**
  10354. * Add the event handlers necessary for auto resizing
  10355. */
  10356. initReflow: function () {
  10357. var chart = this,
  10358. reflow = function (e) {
  10359. chart.reflow(e);
  10360. };
  10361. addEvent(win, 'resize', reflow);
  10362. addEvent(chart, 'destroy', function () {
  10363. removeEvent(win, 'resize', reflow);
  10364. });
  10365. },
  10366. /**
  10367. * Resize the chart to a given width and height
  10368. * @param {Number} width
  10369. * @param {Number} height
  10370. * @param {Object|Boolean} animation
  10371. */
  10372. setSize: function (width, height, animation) {
  10373. var chart = this,
  10374. chartWidth,
  10375. chartHeight,
  10376. fireEndResize;
  10377. // Handle the isResizing counter
  10378. chart.isResizing += 1;
  10379. fireEndResize = function () {
  10380. if (chart) {
  10381. fireEvent(chart, 'endResize', null, function () {
  10382. chart.isResizing -= 1;
  10383. });
  10384. }
  10385. };
  10386. // set the animation for the current process
  10387. setAnimation(animation, chart);
  10388. chart.oldChartHeight = chart.chartHeight;
  10389. chart.oldChartWidth = chart.chartWidth;
  10390. if (defined(width)) {
  10391. chart.chartWidth = chartWidth = mathMax(0, mathRound(width));
  10392. chart.hasUserSize = !!chartWidth;
  10393. }
  10394. if (defined(height)) {
  10395. chart.chartHeight = chartHeight = mathMax(0, mathRound(height));
  10396. }
  10397. // Resize the container with the global animation applied if enabled (#2503)
  10398. (globalAnimation ? animate : css)(chart.container, {
  10399. width: chartWidth + PX,
  10400. height: chartHeight + PX
  10401. }, globalAnimation);
  10402. chart.setChartSize(true);
  10403. chart.renderer.setSize(chartWidth, chartHeight, animation);
  10404. // handle axes
  10405. chart.maxTicks = null;
  10406. each(chart.axes, function (axis) {
  10407. axis.isDirty = true;
  10408. axis.setScale();
  10409. });
  10410. // make sure non-cartesian series are also handled
  10411. each(chart.series, function (serie) {
  10412. serie.isDirty = true;
  10413. });
  10414. chart.isDirtyLegend = true; // force legend redraw
  10415. chart.isDirtyBox = true; // force redraw of plot and chart border
  10416. chart.layOutTitles(); // #2857
  10417. chart.getMargins();
  10418. chart.redraw(animation);
  10419. chart.oldChartHeight = null;
  10420. fireEvent(chart, 'resize');
  10421. // fire endResize and set isResizing back
  10422. // If animation is disabled, fire without delay
  10423. if (globalAnimation === false) {
  10424. fireEndResize();
  10425. } else { // else set a timeout with the animation duration
  10426. setTimeout(fireEndResize, (globalAnimation && globalAnimation.duration) || 500);
  10427. }
  10428. },
  10429. /**
  10430. * Set the public chart properties. This is done before and after the pre-render
  10431. * to determine margin sizes
  10432. */
  10433. setChartSize: function (skipAxes) {
  10434. var chart = this,
  10435. inverted = chart.inverted,
  10436. renderer = chart.renderer,
  10437. chartWidth = chart.chartWidth,
  10438. chartHeight = chart.chartHeight,
  10439. optionsChart = chart.options.chart,
  10440. spacing = chart.spacing,
  10441. clipOffset = chart.clipOffset,
  10442. clipX,
  10443. clipY,
  10444. plotLeft,
  10445. plotTop,
  10446. plotWidth,
  10447. plotHeight,
  10448. plotBorderWidth;
  10449. chart.plotLeft = plotLeft = mathRound(chart.plotLeft);
  10450. chart.plotTop = plotTop = mathRound(chart.plotTop);
  10451. chart.plotWidth = plotWidth = mathMax(0, mathRound(chartWidth - plotLeft - chart.marginRight));
  10452. chart.plotHeight = plotHeight = mathMax(0, mathRound(chartHeight - plotTop - chart.marginBottom));
  10453. chart.plotSizeX = inverted ? plotHeight : plotWidth;
  10454. chart.plotSizeY = inverted ? plotWidth : plotHeight;
  10455. chart.plotBorderWidth = optionsChart.plotBorderWidth || 0;
  10456. // Set boxes used for alignment
  10457. chart.spacingBox = renderer.spacingBox = {
  10458. x: spacing[3],
  10459. y: spacing[0],
  10460. width: chartWidth - spacing[3] - spacing[1],
  10461. height: chartHeight - spacing[0] - spacing[2]
  10462. };
  10463. chart.plotBox = renderer.plotBox = {
  10464. x: plotLeft,
  10465. y: plotTop,
  10466. width: plotWidth,
  10467. height: plotHeight
  10468. };
  10469. plotBorderWidth = 2 * mathFloor(chart.plotBorderWidth / 2);
  10470. clipX = mathCeil(mathMax(plotBorderWidth, clipOffset[3]) / 2);
  10471. clipY = mathCeil(mathMax(plotBorderWidth, clipOffset[0]) / 2);
  10472. chart.clipBox = {
  10473. x: clipX,
  10474. y: clipY,
  10475. width: mathFloor(chart.plotSizeX - mathMax(plotBorderWidth, clipOffset[1]) / 2 - clipX),
  10476. height: mathMax(0, mathFloor(chart.plotSizeY - mathMax(plotBorderWidth, clipOffset[2]) / 2 - clipY))
  10477. };
  10478. if (!skipAxes) {
  10479. each(chart.axes, function (axis) {
  10480. axis.setAxisSize();
  10481. axis.setAxisTranslation();
  10482. });
  10483. }
  10484. },
  10485. /**
  10486. * Initial margins before auto size margins are applied
  10487. */
  10488. resetMargins: function () {
  10489. var chart = this;
  10490. each(marginNames, function (m, side) {
  10491. chart[m] = pick(chart.margin[side], chart.spacing[side]);
  10492. });
  10493. chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left
  10494. chart.clipOffset = [0, 0, 0, 0];
  10495. },
  10496. /**
  10497. * Draw the borders and backgrounds for chart and plot area
  10498. */
  10499. drawChartBox: function () {
  10500. var chart = this,
  10501. optionsChart = chart.options.chart,
  10502. renderer = chart.renderer,
  10503. chartWidth = chart.chartWidth,
  10504. chartHeight = chart.chartHeight,
  10505. chartBackground = chart.chartBackground,
  10506. plotBackground = chart.plotBackground,
  10507. plotBorder = chart.plotBorder,
  10508. plotBGImage = chart.plotBGImage,
  10509. chartBorderWidth = optionsChart.borderWidth || 0,
  10510. chartBackgroundColor = optionsChart.backgroundColor,
  10511. plotBackgroundColor = optionsChart.plotBackgroundColor,
  10512. plotBackgroundImage = optionsChart.plotBackgroundImage,
  10513. plotBorderWidth = optionsChart.plotBorderWidth || 0,
  10514. mgn,
  10515. bgAttr,
  10516. plotLeft = chart.plotLeft,
  10517. plotTop = chart.plotTop,
  10518. plotWidth = chart.plotWidth,
  10519. plotHeight = chart.plotHeight,
  10520. plotBox = chart.plotBox,
  10521. clipRect = chart.clipRect,
  10522. clipBox = chart.clipBox;
  10523. // Chart area
  10524. mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0);
  10525. if (chartBorderWidth || chartBackgroundColor) {
  10526. if (!chartBackground) {
  10527. bgAttr = {
  10528. fill: chartBackgroundColor || NONE
  10529. };
  10530. if (chartBorderWidth) { // #980
  10531. bgAttr.stroke = optionsChart.borderColor;
  10532. bgAttr['stroke-width'] = chartBorderWidth;
  10533. }
  10534. chart.chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn,
  10535. optionsChart.borderRadius, chartBorderWidth)
  10536. .attr(bgAttr)
  10537. .addClass(PREFIX + 'background')
  10538. .add()
  10539. .shadow(optionsChart.shadow);
  10540. } else { // resize
  10541. chartBackground.animate(
  10542. chartBackground.crisp({ width: chartWidth - mgn, height: chartHeight - mgn })
  10543. );
  10544. }
  10545. }
  10546. // Plot background
  10547. if (plotBackgroundColor) {
  10548. if (!plotBackground) {
  10549. chart.plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0)
  10550. .attr({
  10551. fill: plotBackgroundColor
  10552. })
  10553. .add()
  10554. .shadow(optionsChart.plotShadow);
  10555. } else {
  10556. plotBackground.animate(plotBox);
  10557. }
  10558. }
  10559. if (plotBackgroundImage) {
  10560. if (!plotBGImage) {
  10561. chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight)
  10562. .add();
  10563. } else {
  10564. plotBGImage.animate(plotBox);
  10565. }
  10566. }
  10567. // Plot clip
  10568. if (!clipRect) {
  10569. chart.clipRect = renderer.clipRect(clipBox);
  10570. } else {
  10571. clipRect.animate({
  10572. width: clipBox.width,
  10573. height: clipBox.height
  10574. });
  10575. }
  10576. // Plot area border
  10577. if (plotBorderWidth) {
  10578. if (!plotBorder) {
  10579. chart.plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, -plotBorderWidth)
  10580. .attr({
  10581. stroke: optionsChart.plotBorderColor,
  10582. 'stroke-width': plotBorderWidth,
  10583. fill: NONE,
  10584. zIndex: 1
  10585. })
  10586. .add();
  10587. } else {
  10588. plotBorder.animate(
  10589. plotBorder.crisp({ x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight, strokeWidth: -plotBorderWidth }) //#3282 plotBorder should be negative
  10590. );
  10591. }
  10592. }
  10593. // reset
  10594. chart.isDirtyBox = false;
  10595. },
  10596. /**
  10597. * Detect whether a certain chart property is needed based on inspecting its options
  10598. * and series. This mainly applies to the chart.invert property, and in extensions to
  10599. * the chart.angular and chart.polar properties.
  10600. */
  10601. propFromSeries: function () {
  10602. var chart = this,
  10603. optionsChart = chart.options.chart,
  10604. klass,
  10605. seriesOptions = chart.options.series,
  10606. i,
  10607. value;
  10608. each(['inverted', 'angular', 'polar'], function (key) {
  10609. // The default series type's class
  10610. klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType];
  10611. // Get the value from available chart-wide properties
  10612. value = (
  10613. chart[key] || // 1. it is set before
  10614. optionsChart[key] || // 2. it is set in the options
  10615. (klass && klass.prototype[key]) // 3. it's default series class requires it
  10616. );
  10617. // 4. Check if any the chart's series require it
  10618. i = seriesOptions && seriesOptions.length;
  10619. while (!value && i--) {
  10620. klass = seriesTypes[seriesOptions[i].type];
  10621. if (klass && klass.prototype[key]) {
  10622. value = true;
  10623. }
  10624. }
  10625. // Set the chart property
  10626. chart[key] = value;
  10627. });
  10628. },
  10629. /**
  10630. * Link two or more series together. This is done initially from Chart.render,
  10631. * and after Chart.addSeries and Series.remove.
  10632. */
  10633. linkSeries: function () {
  10634. var chart = this,
  10635. chartSeries = chart.series;
  10636. // Reset links
  10637. each(chartSeries, function (series) {
  10638. series.linkedSeries.length = 0;
  10639. });
  10640. // Apply new links
  10641. each(chartSeries, function (series) {
  10642. var linkedTo = series.options.linkedTo;
  10643. if (isString(linkedTo)) {
  10644. if (linkedTo === ':previous') {
  10645. linkedTo = chart.series[series.index - 1];
  10646. } else {
  10647. linkedTo = chart.get(linkedTo);
  10648. }
  10649. if (linkedTo) {
  10650. linkedTo.linkedSeries.push(series);
  10651. series.linkedParent = linkedTo;
  10652. }
  10653. }
  10654. });
  10655. },
  10656. /**
  10657. * Render series for the chart
  10658. */
  10659. renderSeries: function () {
  10660. each(this.series, function (serie) {
  10661. serie.translate();
  10662. serie.render();
  10663. });
  10664. },
  10665. /**
  10666. * Render labels for the chart
  10667. */
  10668. renderLabels: function () {
  10669. var chart = this,
  10670. labels = chart.options.labels;
  10671. if (labels.items) {
  10672. each(labels.items, function (label) {
  10673. var style = extend(labels.style, label.style),
  10674. x = pInt(style.left) + chart.plotLeft,
  10675. y = pInt(style.top) + chart.plotTop + 12;
  10676. // delete to prevent rewriting in IE
  10677. delete style.left;
  10678. delete style.top;
  10679. chart.renderer.text(
  10680. label.html,
  10681. x,
  10682. y
  10683. )
  10684. .attr({ zIndex: 2 })
  10685. .css(style)
  10686. .add();
  10687. });
  10688. }
  10689. },
  10690. /**
  10691. * Render all graphics for the chart
  10692. */
  10693. render: function () {
  10694. var chart = this,
  10695. axes = chart.axes,
  10696. renderer = chart.renderer,
  10697. options = chart.options,
  10698. tempWidth,
  10699. tempHeight,
  10700. redoHorizontal,
  10701. redoVertical;
  10702. // Title
  10703. chart.setTitle();
  10704. // Legend
  10705. chart.legend = new Legend(chart, options.legend);
  10706. chart.getStacks(); // render stacks
  10707. // Get chart margins
  10708. chart.getMargins(true);
  10709. chart.setChartSize();
  10710. // Record preliminary dimensions for later comparison
  10711. tempWidth = chart.plotWidth;
  10712. tempHeight = chart.plotHeight = chart.plotHeight - 13; // 13 is the most common height of X axis labels
  10713. // Get margins by pre-rendering axes
  10714. each(axes, function (axis) {
  10715. axis.setScale();
  10716. });
  10717. chart.getAxisMargins();
  10718. // If the plot area size has changed significantly, calculate tick positions again
  10719. redoHorizontal = tempWidth / chart.plotWidth > 1.1;
  10720. redoVertical = tempHeight / chart.plotHeight > 1.1;
  10721. if (redoHorizontal || redoVertical) {
  10722. chart.maxTicks = null; // reset for second pass
  10723. each(axes, function (axis) {
  10724. if ((axis.horiz && redoHorizontal) || (!axis.horiz && redoVertical)) {
  10725. axis.setTickInterval(true); // update to reflect the new margins
  10726. }
  10727. });
  10728. chart.getMargins(); // second pass to check for new labels
  10729. }
  10730. // Draw the borders and backgrounds
  10731. chart.drawChartBox();
  10732. // Axes
  10733. if (chart.hasCartesianSeries) {
  10734. each(axes, function (axis) {
  10735. axis.render();
  10736. });
  10737. }
  10738. // The series
  10739. if (!chart.seriesGroup) {
  10740. chart.seriesGroup = renderer.g('series-group')
  10741. .attr({ zIndex: 3 })
  10742. .add();
  10743. }
  10744. chart.renderSeries();
  10745. // Labels
  10746. chart.renderLabels();
  10747. // Credits
  10748. chart.showCredits(options.credits);
  10749. // Set flag
  10750. chart.hasRendered = true;
  10751. },
  10752. /**
  10753. * Show chart credits based on config options
  10754. */
  10755. showCredits: function (credits) {
  10756. if (credits.enabled && !this.credits) {
  10757. this.credits = this.renderer.text(
  10758. credits.text,
  10759. 0,
  10760. 0
  10761. )
  10762. .on('click', function () {
  10763. if (credits.href) {
  10764. location.href = credits.href;
  10765. }
  10766. })
  10767. .attr({
  10768. align: credits.position.align,
  10769. zIndex: 8
  10770. })
  10771. .css(credits.style)
  10772. .add()
  10773. .align(credits.position);
  10774. }
  10775. },
  10776. /**
  10777. * Clean up memory usage
  10778. */
  10779. destroy: function () {
  10780. var chart = this,
  10781. axes = chart.axes,
  10782. series = chart.series,
  10783. container = chart.container,
  10784. i,
  10785. parentNode = container && container.parentNode;
  10786. // fire the chart.destoy event
  10787. fireEvent(chart, 'destroy');
  10788. // Delete the chart from charts lookup array
  10789. charts[chart.index] = UNDEFINED;
  10790. chartCount--;
  10791. chart.renderTo.removeAttribute('data-highcharts-chart');
  10792. // remove events
  10793. removeEvent(chart);
  10794. // ==== Destroy collections:
  10795. // Destroy axes
  10796. i = axes.length;
  10797. while (i--) {
  10798. axes[i] = axes[i].destroy();
  10799. }
  10800. // Destroy each series
  10801. i = series.length;
  10802. while (i--) {
  10803. series[i] = series[i].destroy();
  10804. }
  10805. // ==== Destroy chart properties:
  10806. each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage',
  10807. 'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer', 'scroller',
  10808. 'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'], function (name) {
  10809. var prop = chart[name];
  10810. if (prop && prop.destroy) {
  10811. chart[name] = prop.destroy();
  10812. }
  10813. });
  10814. // remove container and all SVG
  10815. if (container) { // can break in IE when destroyed before finished loading
  10816. container.innerHTML = '';
  10817. removeEvent(container);
  10818. if (parentNode) {
  10819. discardElement(container);
  10820. }
  10821. }
  10822. // clean it all up
  10823. for (i in chart) {
  10824. delete chart[i];
  10825. }
  10826. },
  10827. /**
  10828. * VML namespaces can't be added until after complete. Listening
  10829. * for Perini's doScroll hack is not enough.
  10830. */
  10831. isReadyToRender: function () {
  10832. var chart = this;
  10833. // Note: in spite of JSLint's complaints, win == win.top is required
  10834. /*jslint eqeq: true*/
  10835. if ((!hasSVG && (win == win.top && doc.readyState !== 'complete')) || (useCanVG && !win.canvg)) {
  10836. /*jslint eqeq: false*/
  10837. if (useCanVG) {
  10838. // Delay rendering until canvg library is downloaded and ready
  10839. CanVGController.push(function () { chart.firstRender(); }, chart.options.global.canvasToolsURL);
  10840. } else {
  10841. doc.attachEvent('onreadystatechange', function () {
  10842. doc.detachEvent('onreadystatechange', chart.firstRender);
  10843. if (doc.readyState === 'complete') {
  10844. chart.firstRender();
  10845. }
  10846. });
  10847. }
  10848. return false;
  10849. }
  10850. return true;
  10851. },
  10852. /**
  10853. * Prepare for first rendering after all data are loaded
  10854. */
  10855. firstRender: function () {
  10856. var chart = this,
  10857. options = chart.options,
  10858. callback = chart.callback;
  10859. // Check whether the chart is ready to render
  10860. if (!chart.isReadyToRender()) {
  10861. return;
  10862. }
  10863. // Create the container
  10864. chart.getContainer();
  10865. // Run an early event after the container and renderer are established
  10866. fireEvent(chart, 'init');
  10867. chart.resetMargins();
  10868. chart.setChartSize();
  10869. // Set the common chart properties (mainly invert) from the given series
  10870. chart.propFromSeries();
  10871. // get axes
  10872. chart.getAxes();
  10873. // Initialize the series
  10874. each(options.series || [], function (serieOptions) {
  10875. chart.initSeries(serieOptions);
  10876. });
  10877. chart.linkSeries();
  10878. // Run an event after axes and series are initialized, but before render. At this stage,
  10879. // the series data is indexed and cached in the xData and yData arrays, so we can access
  10880. // those before rendering. Used in Highstock.
  10881. fireEvent(chart, 'beforeRender');
  10882. // depends on inverted and on margins being set
  10883. if (Highcharts.Pointer) {
  10884. chart.pointer = new Pointer(chart, options);
  10885. }
  10886. chart.render();
  10887. // add canvas
  10888. chart.renderer.draw();
  10889. // run callbacks
  10890. if (callback) {
  10891. callback.apply(chart, [chart]);
  10892. }
  10893. each(chart.callbacks, function (fn) {
  10894. if (chart.index !== UNDEFINED) { // Chart destroyed in its own callback (#3600)
  10895. fn.apply(chart, [chart]);
  10896. }
  10897. });
  10898. // Fire the load event
  10899. fireEvent(chart, 'load');
  10900. // If the chart was rendered outside the top container, put it back in (#3679)
  10901. chart.cloneRenderTo(true);
  10902. },
  10903. /**
  10904. * Creates arrays for spacing and margin from given options.
  10905. */
  10906. splashArray: function (target, options) {
  10907. var oVar = options[target],
  10908. tArray = isObject(oVar) ? oVar : [oVar, oVar, oVar, oVar];
  10909. return [pick(options[target + 'Top'], tArray[0]),
  10910. pick(options[target + 'Right'], tArray[1]),
  10911. pick(options[target + 'Bottom'], tArray[2]),
  10912. pick(options[target + 'Left'], tArray[3])];
  10913. }
  10914. }; // end Chart
  10915. var CenteredSeriesMixin = Highcharts.CenteredSeriesMixin = {
  10916. /**
  10917. * Get the center of the pie based on the size and center options relative to the
  10918. * plot area. Borrowed by the polar and gauge series types.
  10919. */
  10920. getCenter: function () {
  10921. var options = this.options,
  10922. chart = this.chart,
  10923. slicingRoom = 2 * (options.slicedOffset || 0),
  10924. handleSlicingRoom,
  10925. plotWidth = chart.plotWidth - 2 * slicingRoom,
  10926. plotHeight = chart.plotHeight - 2 * slicingRoom,
  10927. centerOption = options.center,
  10928. positions = [pick(centerOption[0], '50%'), pick(centerOption[1], '50%'), options.size || '100%', options.innerSize || 0],
  10929. smallestSize = mathMin(plotWidth, plotHeight),
  10930. isPercent,
  10931. i,
  10932. value;
  10933. for (i = 0; i < 4; ++i) {
  10934. value = positions[i];
  10935. isPercent = /%$/.test(value);
  10936. handleSlicingRoom = i < 2 || (i === 2 && isPercent);
  10937. positions[i] = (isPercent ?
  10938. // i == 0: centerX, relative to width
  10939. // i == 1: centerY, relative to height
  10940. // i == 2: size, relative to smallestSize
  10941. // i == 3: innerSize, relative to size
  10942. [plotWidth, plotHeight, smallestSize, positions[2]][i] *
  10943. pInt(value) / 100 :
  10944. pInt(value)) + (handleSlicingRoom ? slicingRoom : 0);
  10945. }
  10946. return positions;
  10947. }
  10948. };
  10949. /**
  10950. * The Point object and prototype. Inheritable and used as base for PiePoint
  10951. */
  10952. var Point = function () {};
  10953. Point.prototype = {
  10954. /**
  10955. * Initialize the point
  10956. * @param {Object} series The series object containing this point
  10957. * @param {Object} options The data in either number, array or object format
  10958. */
  10959. init: function (series, options, x) {
  10960. var point = this,
  10961. colors;
  10962. point.series = series;
  10963. point.color = series.color; // #3445
  10964. point.applyOptions(options, x);
  10965. point.pointAttr = {};
  10966. if (series.options.colorByPoint) {
  10967. colors = series.options.colors || series.chart.options.colors;
  10968. point.color = point.color || colors[series.colorCounter++];
  10969. // loop back to zero
  10970. if (series.colorCounter === colors.length) {
  10971. series.colorCounter = 0;
  10972. }
  10973. }
  10974. series.chart.pointCount++;
  10975. return point;
  10976. },
  10977. /**
  10978. * Apply the options containing the x and y data and possible some extra properties.
  10979. * This is called on point init or from point.update.
  10980. *
  10981. * @param {Object} options
  10982. */
  10983. applyOptions: function (options, x) {
  10984. var point = this,
  10985. series = point.series,
  10986. pointValKey = series.options.pointValKey || series.pointValKey;
  10987. options = Point.prototype.optionsToObject.call(this, options);
  10988. // copy options directly to point
  10989. extend(point, options);
  10990. point.options = point.options ? extend(point.options, options) : options;
  10991. // For higher dimension series types. For instance, for ranges, point.y is mapped to point.low.
  10992. if (pointValKey) {
  10993. point.y = point[pointValKey];
  10994. }
  10995. // If no x is set by now, get auto incremented value. All points must have an
  10996. // x value, however the y value can be null to create a gap in the series
  10997. if (point.x === UNDEFINED && series) {
  10998. point.x = x === UNDEFINED ? series.autoIncrement() : x;
  10999. }
  11000. return point;
  11001. },
  11002. /**
  11003. * Transform number or array configs into objects
  11004. */
  11005. optionsToObject: function (options) {
  11006. var ret = {},
  11007. series = this.series,
  11008. keys = series.options.keys, // docs: http://jsfiddle.net/ch4v7n8v/1
  11009. pointArrayMap = keys || series.pointArrayMap || ['y'],
  11010. valueCount = pointArrayMap.length,
  11011. firstItemType,
  11012. i = 0,
  11013. j = 0;
  11014. if (typeof options === 'number' || options === null) {
  11015. ret[pointArrayMap[0]] = options;
  11016. } else if (isArray(options)) {
  11017. // with leading x value
  11018. if (!keys && options.length > valueCount) {
  11019. firstItemType = typeof options[0];
  11020. if (firstItemType === 'string') {
  11021. ret.name = options[0];
  11022. } else if (firstItemType === 'number') {
  11023. ret.x = options[0];
  11024. }
  11025. i++;
  11026. }
  11027. while (j < valueCount) {
  11028. ret[pointArrayMap[j++]] = options[i++];
  11029. }
  11030. } else if (typeof options === 'object') {
  11031. ret = options;
  11032. // This is the fastest way to detect if there are individual point dataLabels that need
  11033. // to be considered in drawDataLabels. These can only occur in object configs.
  11034. if (options.dataLabels) {
  11035. series._hasPointLabels = true;
  11036. }
  11037. // Same approach as above for markers
  11038. if (options.marker) {
  11039. series._hasPointMarkers = true;
  11040. }
  11041. }
  11042. return ret;
  11043. },
  11044. /**
  11045. * Destroy a point to clear memory. Its reference still stays in series.data.
  11046. */
  11047. destroy: function () {
  11048. var point = this,
  11049. series = point.series,
  11050. chart = series.chart,
  11051. hoverPoints = chart.hoverPoints,
  11052. prop;
  11053. chart.pointCount--;
  11054. if (hoverPoints) {
  11055. point.setState();
  11056. erase(hoverPoints, point);
  11057. if (!hoverPoints.length) {
  11058. chart.hoverPoints = null;
  11059. }
  11060. }
  11061. if (point === chart.hoverPoint) {
  11062. point.onMouseOut();
  11063. }
  11064. // remove all events
  11065. if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive
  11066. removeEvent(point);
  11067. point.destroyElements();
  11068. }
  11069. if (point.legendItem) { // pies have legend items
  11070. chart.legend.destroyItem(point);
  11071. }
  11072. for (prop in point) {
  11073. point[prop] = null;
  11074. }
  11075. },
  11076. /**
  11077. * Destroy SVG elements associated with the point
  11078. */
  11079. destroyElements: function () {
  11080. var point = this,
  11081. props = ['graphic', 'dataLabel', 'dataLabelUpper', 'group', 'connector', 'shadowGroup'],
  11082. prop,
  11083. i = 6;
  11084. while (i--) {
  11085. prop = props[i];
  11086. if (point[prop]) {
  11087. point[prop] = point[prop].destroy();
  11088. }
  11089. }
  11090. },
  11091. /**
  11092. * Return the configuration hash needed for the data label and tooltip formatters
  11093. */
  11094. getLabelConfig: function () {
  11095. var point = this;
  11096. return {
  11097. x: point.category,
  11098. y: point.y,
  11099. key: point.name || point.category,
  11100. series: point.series,
  11101. point: point,
  11102. percentage: point.percentage,
  11103. total: point.total || point.stackTotal
  11104. };
  11105. },
  11106. /**
  11107. * Extendable method for formatting each point's tooltip line
  11108. *
  11109. * @return {String} A string to be concatenated in to the common tooltip text
  11110. */
  11111. tooltipFormatter: function (pointFormat) {
  11112. // Insert options for valueDecimals, valuePrefix, and valueSuffix
  11113. var series = this.series,
  11114. seriesTooltipOptions = series.tooltipOptions,
  11115. valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''),
  11116. valuePrefix = seriesTooltipOptions.valuePrefix || '',
  11117. valueSuffix = seriesTooltipOptions.valueSuffix || '';
  11118. // Loop over the point array map and replace unformatted values with sprintf formatting markup
  11119. each(series.pointArrayMap || ['y'], function (key) {
  11120. key = '{point.' + key; // without the closing bracket
  11121. if (valuePrefix || valueSuffix) {
  11122. pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix);
  11123. }
  11124. pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}');
  11125. });
  11126. return format(pointFormat, {
  11127. point: this,
  11128. series: this.series
  11129. });
  11130. },
  11131. /**
  11132. * Fire an event on the Point object. Must not be renamed to fireEvent, as this
  11133. * causes a name clash in MooTools
  11134. * @param {String} eventType
  11135. * @param {Object} eventArgs Additional event arguments
  11136. * @param {Function} defaultFunction Default event handler
  11137. */
  11138. firePointEvent: function (eventType, eventArgs, defaultFunction) {
  11139. var point = this,
  11140. series = this.series,
  11141. seriesOptions = series.options;
  11142. // load event handlers on demand to save time on mouseover/out
  11143. if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) {
  11144. this.importEvents();
  11145. }
  11146. // add default handler if in selection mode
  11147. if (eventType === 'click' && seriesOptions.allowPointSelect) {
  11148. defaultFunction = function (event) {
  11149. // Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera
  11150. point.select(null, event.ctrlKey || event.metaKey || event.shiftKey);
  11151. };
  11152. }
  11153. fireEvent(this, eventType, eventArgs, defaultFunction);
  11154. }
  11155. };/**
  11156. * @classDescription The base function which all other series types inherit from. The data in the series is stored
  11157. * in various arrays.
  11158. *
  11159. * - First, series.options.data contains all the original config options for
  11160. * each point whether added by options or methods like series.addPoint.
  11161. * - Next, series.data contains those values converted to points, but in case the series data length
  11162. * exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It
  11163. * only contains the points that have been created on demand.
  11164. * - Then there's series.points that contains all currently visible point objects. In case of cropping,
  11165. * the cropped-away points are not part of this array. The series.points array starts at series.cropStart
  11166. * compared to series.data and series.options.data. If however the series data is grouped, these can't
  11167. * be correlated one to one.
  11168. * - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points.
  11169. * - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points.
  11170. *
  11171. * @param {Object} chart
  11172. * @param {Object} options
  11173. */
  11174. var Series = Highcharts.Series = function () {};
  11175. Series.prototype = {
  11176. isCartesian: true,
  11177. type: 'line',
  11178. pointClass: Point,
  11179. sorted: true, // requires the data to be sorted
  11180. requireSorting: true,
  11181. pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
  11182. stroke: 'lineColor',
  11183. 'stroke-width': 'lineWidth',
  11184. fill: 'fillColor',
  11185. r: 'radius'
  11186. },
  11187. axisTypes: ['xAxis', 'yAxis'],
  11188. colorCounter: 0,
  11189. parallelArrays: ['x', 'y'], // each point's x and y values are stored in this.xData and this.yData
  11190. init: function (chart, options) {
  11191. var series = this,
  11192. eventType,
  11193. events,
  11194. chartSeries = chart.series,
  11195. sortByIndex = function (a, b) {
  11196. return pick(a.options.index, a._i) - pick(b.options.index, b._i);
  11197. };
  11198. series.chart = chart;
  11199. series.options = options = series.setOptions(options); // merge with plotOptions
  11200. series.linkedSeries = [];
  11201. // bind the axes
  11202. series.bindAxes();
  11203. // set some variables
  11204. extend(series, {
  11205. name: options.name,
  11206. state: NORMAL_STATE,
  11207. pointAttr: {},
  11208. visible: options.visible !== false, // true by default
  11209. selected: options.selected === true // false by default
  11210. });
  11211. // special
  11212. if (useCanVG) {
  11213. options.animation = false;
  11214. }
  11215. // register event listeners
  11216. events = options.events;
  11217. for (eventType in events) {
  11218. addEvent(series, eventType, events[eventType]);
  11219. }
  11220. if (
  11221. (events && events.click) ||
  11222. (options.point && options.point.events && options.point.events.click) ||
  11223. options.allowPointSelect
  11224. ) {
  11225. chart.runTrackerClick = true;
  11226. }
  11227. series.getColor();
  11228. series.getSymbol();
  11229. // Set the data
  11230. each(series.parallelArrays, function (key) {
  11231. series[key + 'Data'] = [];
  11232. });
  11233. series.setData(options.data, false);
  11234. // Mark cartesian
  11235. if (series.isCartesian) {
  11236. chart.hasCartesianSeries = true;
  11237. }
  11238. // Register it in the chart
  11239. chartSeries.push(series);
  11240. series._i = chartSeries.length - 1;
  11241. // Sort series according to index option (#248, #1123, #2456)
  11242. stableSort(chartSeries, sortByIndex);
  11243. if (this.yAxis) {
  11244. stableSort(this.yAxis.series, sortByIndex);
  11245. }
  11246. each(chartSeries, function (series, i) {
  11247. series.index = i;
  11248. series.name = series.name || 'Series ' + (i + 1);
  11249. });
  11250. },
  11251. /**
  11252. * Set the xAxis and yAxis properties of cartesian series, and register the series
  11253. * in the axis.series array
  11254. */
  11255. bindAxes: function () {
  11256. var series = this,
  11257. seriesOptions = series.options,
  11258. chart = series.chart,
  11259. axisOptions;
  11260. each(series.axisTypes || [], function (AXIS) { // repeat for xAxis and yAxis
  11261. each(chart[AXIS], function (axis) { // loop through the chart's axis objects
  11262. axisOptions = axis.options;
  11263. // apply if the series xAxis or yAxis option mathches the number of the
  11264. // axis, or if undefined, use the first axis
  11265. if ((seriesOptions[AXIS] === axisOptions.index) ||
  11266. (seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) ||
  11267. (seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) {
  11268. // register this series in the axis.series lookup
  11269. axis.series.push(series);
  11270. // set this series.xAxis or series.yAxis reference
  11271. series[AXIS] = axis;
  11272. // mark dirty for redraw
  11273. axis.isDirty = true;
  11274. }
  11275. });
  11276. // The series needs an X and an Y axis
  11277. if (!series[AXIS] && series.optionalAxis !== AXIS) {
  11278. error(18, true);
  11279. }
  11280. });
  11281. },
  11282. /**
  11283. * For simple series types like line and column, the data values are held in arrays like
  11284. * xData and yData for quick lookup to find extremes and more. For multidimensional series
  11285. * like bubble and map, this can be extended with arrays like zData and valueData by
  11286. * adding to the series.parallelArrays array.
  11287. */
  11288. updateParallelArrays: function (point, i) {
  11289. var series = point.series,
  11290. args = arguments,
  11291. fn = typeof i === 'number' ?
  11292. // Insert the value in the given position
  11293. function (key) {
  11294. var val = key === 'y' && series.toYData ? series.toYData(point) : point[key];
  11295. series[key + 'Data'][i] = val;
  11296. } :
  11297. // Apply the method specified in i with the following arguments as arguments
  11298. function (key) {
  11299. Array.prototype[i].apply(series[key + 'Data'], Array.prototype.slice.call(args, 2));
  11300. };
  11301. each(series.parallelArrays, fn);
  11302. },
  11303. /**
  11304. * Return an auto incremented x value based on the pointStart and pointInterval options.
  11305. * This is only used if an x value is not given for the point that calls autoIncrement.
  11306. */
  11307. autoIncrement: function () {
  11308. var options = this.options,
  11309. xIncrement = this.xIncrement,
  11310. date,
  11311. pointInterval,
  11312. pointIntervalUnit = options.pointIntervalUnit;
  11313. xIncrement = pick(xIncrement, options.pointStart, 0);
  11314. this.pointInterval = pointInterval = pick(this.pointInterval, options.pointInterval, 1);
  11315. // Added code for pointInterval strings
  11316. if (pointIntervalUnit === 'month' || pointIntervalUnit === 'year') {
  11317. date = new Date(xIncrement);
  11318. date = (pointIntervalUnit === 'month') ?
  11319. +date[setMonth](date[getMonth]() + pointInterval) :
  11320. +date[setFullYear](date[getFullYear]() + pointInterval);
  11321. pointInterval = date - xIncrement;
  11322. }
  11323. this.xIncrement = xIncrement + pointInterval;
  11324. return xIncrement;
  11325. },
  11326. /**
  11327. * Divide the series data into segments divided by null values.
  11328. */
  11329. getSegments: function () {
  11330. var series = this,
  11331. lastNull = -1,
  11332. segments = [],
  11333. i,
  11334. points = series.points,
  11335. pointsLength = points.length;
  11336. if (pointsLength) { // no action required for []
  11337. // if connect nulls, just remove null points
  11338. if (series.options.connectNulls) {
  11339. i = pointsLength;
  11340. while (i--) {
  11341. if (points[i].y === null) {
  11342. points.splice(i, 1);
  11343. }
  11344. }
  11345. if (points.length) {
  11346. segments = [points];
  11347. }
  11348. // else, split on null points
  11349. } else {
  11350. each(points, function (point, i) {
  11351. if (point.y === null) {
  11352. if (i > lastNull + 1) {
  11353. segments.push(points.slice(lastNull + 1, i));
  11354. }
  11355. lastNull = i;
  11356. } else if (i === pointsLength - 1) { // last value
  11357. segments.push(points.slice(lastNull + 1, i + 1));
  11358. }
  11359. });
  11360. }
  11361. }
  11362. // register it
  11363. series.segments = segments;
  11364. },
  11365. /**
  11366. * Set the series options by merging from the options tree
  11367. * @param {Object} itemOptions
  11368. */
  11369. setOptions: function (itemOptions) {
  11370. var chart = this.chart,
  11371. chartOptions = chart.options,
  11372. plotOptions = chartOptions.plotOptions,
  11373. userOptions = chart.userOptions || {},
  11374. userPlotOptions = userOptions.plotOptions || {},
  11375. typeOptions = plotOptions[this.type],
  11376. options,
  11377. zones;
  11378. this.userOptions = itemOptions;
  11379. // General series options take precedence over type options because otherwise, default
  11380. // type options like column.animation would be overwritten by the general option.
  11381. // But issues have been raised here (#3881), and the solution may be to distinguish
  11382. // between default option and userOptions like in the tooltip below.
  11383. options = merge(
  11384. typeOptions,
  11385. plotOptions.series,
  11386. itemOptions
  11387. );
  11388. // The tooltip options are merged between global and series specific options
  11389. this.tooltipOptions = merge(
  11390. defaultOptions.tooltip,
  11391. defaultOptions.plotOptions[this.type].tooltip,
  11392. userOptions.tooltip,
  11393. userPlotOptions.series && userPlotOptions.series.tooltip,
  11394. userPlotOptions[this.type] && userPlotOptions[this.type].tooltip,
  11395. itemOptions.tooltip
  11396. );
  11397. // Delete marker object if not allowed (#1125)
  11398. if (typeOptions.marker === null) {
  11399. delete options.marker;
  11400. }
  11401. // Handle color zones
  11402. this.zoneAxis = options.zoneAxis;
  11403. zones = this.zones = (options.zones || []).slice();
  11404. if ((options.negativeColor || options.negativeFillColor) && !options.zones) {
  11405. zones.push({
  11406. value: options[this.zoneAxis + 'Threshold'] || options.threshold || 0,
  11407. color: options.negativeColor,
  11408. fillColor: options.negativeFillColor
  11409. });
  11410. }
  11411. if (zones.length) { // Push one extra zone for the rest
  11412. if (defined(zones[zones.length - 1].value)) {
  11413. zones.push({
  11414. color: this.color,
  11415. fillColor: this.fillColor
  11416. });
  11417. }
  11418. }
  11419. return options;
  11420. },
  11421. getCyclic: function (prop, value, defaults) {
  11422. var i,
  11423. userOptions = this.userOptions,
  11424. indexName = '_' + prop + 'Index',
  11425. counterName = prop + 'Counter';
  11426. if (!value) {
  11427. if (defined(userOptions[indexName])) { // after Series.update()
  11428. i = userOptions[indexName];
  11429. } else {
  11430. userOptions[indexName] = i = this.chart[counterName] % defaults.length;
  11431. this.chart[counterName] += 1;
  11432. }
  11433. value = defaults[i];
  11434. }
  11435. this[prop] = value;
  11436. },
  11437. /**
  11438. * Get the series' color
  11439. */
  11440. getColor: function () {
  11441. if (!this.options.colorByPoint) {
  11442. this.getCyclic('color', this.options.color || defaultPlotOptions[this.type].color, this.chart.options.colors);
  11443. }
  11444. },
  11445. /**
  11446. * Get the series' symbol
  11447. */
  11448. getSymbol: function () {
  11449. var seriesMarkerOption = this.options.marker;
  11450. this.getCyclic('symbol', seriesMarkerOption.symbol, this.chart.options.symbols);
  11451. // don't substract radius in image symbols (#604)
  11452. if (/^url/.test(this.symbol)) {
  11453. seriesMarkerOption.radius = 0;
  11454. }
  11455. },
  11456. drawLegendSymbol: LegendSymbolMixin.drawLineMarker,
  11457. /**
  11458. * Replace the series data with a new set of data
  11459. * @param {Object} data
  11460. * @param {Object} redraw
  11461. */
  11462. setData: function (data, redraw, animation, updatePoints) {
  11463. var series = this,
  11464. oldData = series.points,
  11465. oldDataLength = (oldData && oldData.length) || 0,
  11466. dataLength,
  11467. options = series.options,
  11468. chart = series.chart,
  11469. firstPoint = null,
  11470. xAxis = series.xAxis,
  11471. hasCategories = xAxis && !!xAxis.categories,
  11472. i,
  11473. turboThreshold = options.turboThreshold,
  11474. pt,
  11475. xData = this.xData,
  11476. yData = this.yData,
  11477. pointArrayMap = series.pointArrayMap,
  11478. valueCount = pointArrayMap && pointArrayMap.length;
  11479. data = data || [];
  11480. dataLength = data.length;
  11481. redraw = pick(redraw, true);
  11482. // If the point count is the same as is was, just run Point.update which is
  11483. // cheaper, allows animation, and keeps references to points.
  11484. if (updatePoints !== false && dataLength && oldDataLength === dataLength && !series.cropped && !series.hasGroupedData && series.visible) {
  11485. each(data, function (point, i) {
  11486. oldData[i].update(point, false, null, false);
  11487. });
  11488. } else {
  11489. // Reset properties
  11490. series.xIncrement = null;
  11491. series.pointRange = hasCategories ? 1 : options.pointRange;
  11492. series.colorCounter = 0; // for series with colorByPoint (#1547)
  11493. // Update parallel arrays
  11494. each(this.parallelArrays, function (key) {
  11495. series[key + 'Data'].length = 0;
  11496. });
  11497. // In turbo mode, only one- or twodimensional arrays of numbers are allowed. The
  11498. // first value is tested, and we assume that all the rest are defined the same
  11499. // way. Although the 'for' loops are similar, they are repeated inside each
  11500. // if-else conditional for max performance.
  11501. if (turboThreshold && dataLength > turboThreshold) {
  11502. // find the first non-null point
  11503. i = 0;
  11504. while (firstPoint === null && i < dataLength) {
  11505. firstPoint = data[i];
  11506. i++;
  11507. }
  11508. if (isNumber(firstPoint)) { // assume all points are numbers
  11509. var x = pick(options.pointStart, 0),
  11510. pointInterval = pick(options.pointInterval, 1);
  11511. for (i = 0; i < dataLength; i++) {
  11512. xData[i] = x;
  11513. yData[i] = data[i];
  11514. x += pointInterval;
  11515. }
  11516. series.xIncrement = x;
  11517. } else if (isArray(firstPoint)) { // assume all points are arrays
  11518. if (valueCount) { // [x, low, high] or [x, o, h, l, c]
  11519. for (i = 0; i < dataLength; i++) {
  11520. pt = data[i];
  11521. xData[i] = pt[0];
  11522. yData[i] = pt.slice(1, valueCount + 1);
  11523. }
  11524. } else { // [x, y]
  11525. for (i = 0; i < dataLength; i++) {
  11526. pt = data[i];
  11527. xData[i] = pt[0];
  11528. yData[i] = pt[1];
  11529. }
  11530. }
  11531. } else {
  11532. error(12); // Highcharts expects configs to be numbers or arrays in turbo mode
  11533. }
  11534. } else {
  11535. for (i = 0; i < dataLength; i++) {
  11536. if (data[i] !== UNDEFINED) { // stray commas in oldIE
  11537. pt = { series: series };
  11538. series.pointClass.prototype.applyOptions.apply(pt, [data[i]]);
  11539. series.updateParallelArrays(pt, i);
  11540. if (hasCategories && pt.name) {
  11541. xAxis.names[pt.x] = pt.name; // #2046
  11542. }
  11543. }
  11544. }
  11545. }
  11546. // Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON
  11547. if (isString(yData[0])) {
  11548. error(14, true);
  11549. }
  11550. series.data = [];
  11551. series.options.data = data;
  11552. //series.zData = zData;
  11553. // destroy old points
  11554. i = oldDataLength;
  11555. while (i--) {
  11556. if (oldData[i] && oldData[i].destroy) {
  11557. oldData[i].destroy();
  11558. }
  11559. }
  11560. // reset minRange (#878)
  11561. if (xAxis) {
  11562. xAxis.minRange = xAxis.userMinRange;
  11563. }
  11564. // redraw
  11565. series.isDirty = series.isDirtyData = chart.isDirtyBox = true;
  11566. animation = false;
  11567. }
  11568. if (redraw) {
  11569. chart.redraw(animation);
  11570. }
  11571. },
  11572. /**
  11573. * Process the data by cropping away unused data points if the series is longer
  11574. * than the crop threshold. This saves computing time for lage series.
  11575. */
  11576. processData: function (force) {
  11577. var series = this,
  11578. processedXData = series.xData, // copied during slice operation below
  11579. processedYData = series.yData,
  11580. dataLength = processedXData.length,
  11581. croppedData,
  11582. cropStart = 0,
  11583. cropped,
  11584. distance,
  11585. closestPointRange,
  11586. xAxis = series.xAxis,
  11587. i, // loop variable
  11588. options = series.options,
  11589. cropThreshold = options.cropThreshold,
  11590. isCartesian = series.isCartesian,
  11591. xExtremes,
  11592. min,
  11593. max;
  11594. // If the series data or axes haven't changed, don't go through this. Return false to pass
  11595. // the message on to override methods like in data grouping.
  11596. if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) {
  11597. return false;
  11598. }
  11599. if (xAxis) {
  11600. xExtremes = xAxis.getExtremes(); // corrected for log axis (#3053)
  11601. min = xExtremes.min;
  11602. max = xExtremes.max;
  11603. }
  11604. // optionally filter out points outside the plot area
  11605. if (isCartesian && series.sorted && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) {
  11606. // it's outside current extremes
  11607. if (processedXData[dataLength - 1] < min || processedXData[0] > max) {
  11608. processedXData = [];
  11609. processedYData = [];
  11610. // only crop if it's actually spilling out
  11611. } else if (processedXData[0] < min || processedXData[dataLength - 1] > max) {
  11612. croppedData = this.cropData(series.xData, series.yData, min, max);
  11613. processedXData = croppedData.xData;
  11614. processedYData = croppedData.yData;
  11615. cropStart = croppedData.start;
  11616. cropped = true;
  11617. }
  11618. }
  11619. // Find the closest distance between processed points
  11620. for (i = processedXData.length - 1; i >= 0; i--) {
  11621. distance = processedXData[i] - processedXData[i - 1];
  11622. if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) {
  11623. closestPointRange = distance;
  11624. // Unsorted data is not supported by the line tooltip, as well as data grouping and
  11625. // navigation in Stock charts (#725) and width calculation of columns (#1900)
  11626. } else if (distance < 0 && series.requireSorting) {
  11627. error(15);
  11628. }
  11629. }
  11630. // Record the properties
  11631. series.cropped = cropped; // undefined or true
  11632. series.cropStart = cropStart;
  11633. series.processedXData = processedXData;
  11634. series.processedYData = processedYData;
  11635. if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC
  11636. series.pointRange = closestPointRange || 1;
  11637. }
  11638. series.closestPointRange = closestPointRange;
  11639. },
  11640. /**
  11641. * Iterate over xData and crop values between min and max. Returns object containing crop start/end
  11642. * cropped xData with corresponding part of yData, dataMin and dataMax within the cropped range
  11643. */
  11644. cropData: function (xData, yData, min, max) {
  11645. var dataLength = xData.length,
  11646. cropStart = 0,
  11647. cropEnd = dataLength,
  11648. cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside
  11649. i;
  11650. // iterate up to find slice start
  11651. for (i = 0; i < dataLength; i++) {
  11652. if (xData[i] >= min) {
  11653. cropStart = mathMax(0, i - cropShoulder);
  11654. break;
  11655. }
  11656. }
  11657. // proceed to find slice end
  11658. for (; i < dataLength; i++) {
  11659. if (xData[i] > max) {
  11660. cropEnd = i + cropShoulder;
  11661. break;
  11662. }
  11663. }
  11664. return {
  11665. xData: xData.slice(cropStart, cropEnd),
  11666. yData: yData.slice(cropStart, cropEnd),
  11667. start: cropStart,
  11668. end: cropEnd
  11669. };
  11670. },
  11671. /**
  11672. * Generate the data point after the data has been processed by cropping away
  11673. * unused points and optionally grouped in Highcharts Stock.
  11674. */
  11675. generatePoints: function () {
  11676. var series = this,
  11677. options = series.options,
  11678. dataOptions = options.data,
  11679. data = series.data,
  11680. dataLength,
  11681. processedXData = series.processedXData,
  11682. processedYData = series.processedYData,
  11683. pointClass = series.pointClass,
  11684. processedDataLength = processedXData.length,
  11685. cropStart = series.cropStart || 0,
  11686. cursor,
  11687. hasGroupedData = series.hasGroupedData,
  11688. point,
  11689. points = [],
  11690. i;
  11691. if (!data && !hasGroupedData) {
  11692. var arr = [];
  11693. arr.length = dataOptions.length;
  11694. data = series.data = arr;
  11695. }
  11696. for (i = 0; i < processedDataLength; i++) {
  11697. cursor = cropStart + i;
  11698. if (!hasGroupedData) {
  11699. if (data[cursor]) {
  11700. point = data[cursor];
  11701. } else if (dataOptions[cursor] !== UNDEFINED) { // #970
  11702. data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]);
  11703. }
  11704. points[i] = point;
  11705. } else {
  11706. // splat the y data in case of ohlc data array
  11707. points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i])));
  11708. }
  11709. points[i].index = cursor; // For faster access in Point.update
  11710. }
  11711. // Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when
  11712. // swithching view from non-grouped data to grouped data (#637)
  11713. if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) {
  11714. for (i = 0; i < dataLength; i++) {
  11715. if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points
  11716. i += processedDataLength;
  11717. }
  11718. if (data[i]) {
  11719. data[i].destroyElements();
  11720. data[i].plotX = UNDEFINED; // #1003
  11721. }
  11722. }
  11723. }
  11724. series.data = data;
  11725. series.points = points;
  11726. },
  11727. /**
  11728. * Calculate Y extremes for visible data
  11729. */
  11730. getExtremes: function (yData) {
  11731. var xAxis = this.xAxis,
  11732. yAxis = this.yAxis,
  11733. xData = this.processedXData,
  11734. yDataLength,
  11735. activeYData = [],
  11736. activeCounter = 0,
  11737. xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis
  11738. xMin = xExtremes.min,
  11739. xMax = xExtremes.max,
  11740. validValue,
  11741. withinRange,
  11742. x,
  11743. y,
  11744. i,
  11745. j;
  11746. yData = yData || this.stackedYData || this.processedYData;
  11747. yDataLength = yData.length;
  11748. for (i = 0; i < yDataLength; i++) {
  11749. x = xData[i];
  11750. y = yData[i];
  11751. // For points within the visible range, including the first point outside the
  11752. // visible range, consider y extremes
  11753. validValue = y !== null && y !== UNDEFINED && (!yAxis.isLog || (y.length || y > 0));
  11754. withinRange = this.getExtremesFromAll || this.cropped || ((xData[i + 1] || x) >= xMin &&
  11755. (xData[i - 1] || x) <= xMax);
  11756. if (validValue && withinRange) {
  11757. j = y.length;
  11758. if (j) { // array, like ohlc or range data
  11759. while (j--) {
  11760. if (y[j] !== null) {
  11761. activeYData[activeCounter++] = y[j];
  11762. }
  11763. }
  11764. } else {
  11765. activeYData[activeCounter++] = y;
  11766. }
  11767. }
  11768. }
  11769. this.dataMin = arrayMin(activeYData);
  11770. this.dataMax = arrayMax(activeYData);
  11771. },
  11772. /**
  11773. * Translate data points from raw data values to chart specific positioning data
  11774. * needed later in drawPoints, drawGraph and drawTracker.
  11775. */
  11776. translate: function () {
  11777. if (!this.processedXData) { // hidden series
  11778. this.processData();
  11779. }
  11780. this.generatePoints();
  11781. var series = this,
  11782. options = series.options,
  11783. stacking = options.stacking,
  11784. xAxis = series.xAxis,
  11785. categories = xAxis.categories,
  11786. yAxis = series.yAxis,
  11787. points = series.points,
  11788. dataLength = points.length,
  11789. hasModifyValue = !!series.modifyValue,
  11790. i,
  11791. pointPlacement = options.pointPlacement,
  11792. dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement),
  11793. threshold = options.threshold,
  11794. plotX,
  11795. plotY,
  11796. lastPlotX,
  11797. closestPointRangePx = Number.MAX_VALUE;
  11798. // Translate each point
  11799. for (i = 0; i < dataLength; i++) {
  11800. var point = points[i],
  11801. xValue = point.x,
  11802. yValue = point.y,
  11803. yBottom = point.low,
  11804. stack = stacking && yAxis.stacks[(series.negStacks && yValue < threshold ? '-' : '') + series.stackKey],
  11805. pointStack,
  11806. stackValues;
  11807. // Discard disallowed y values for log axes (#3434)
  11808. if (yAxis.isLog && yValue !== null && yValue <= 0) {
  11809. point.y = yValue = null;
  11810. error(10);
  11811. }
  11812. // Get the plotX translation
  11813. point.plotX = plotX = xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags'); // Math.round fixes #591
  11814. // Calculate the bottom y value for stacked series
  11815. if (stacking && series.visible && stack && stack[xValue]) {
  11816. pointStack = stack[xValue];
  11817. stackValues = pointStack.points[series.index + ',' + i];
  11818. yBottom = stackValues[0];
  11819. yValue = stackValues[1];
  11820. if (yBottom === 0) {
  11821. yBottom = pick(threshold, yAxis.min);
  11822. }
  11823. if (yAxis.isLog && yBottom <= 0) { // #1200, #1232
  11824. yBottom = null;
  11825. }
  11826. point.total = point.stackTotal = pointStack.total;
  11827. point.percentage = pointStack.total && (point.y / pointStack.total * 100);
  11828. point.stackY = yValue;
  11829. // Place the stack label
  11830. pointStack.setOffset(series.pointXOffset || 0, series.barW || 0);
  11831. }
  11832. // Set translated yBottom or remove it
  11833. point.yBottom = defined(yBottom) ?
  11834. yAxis.translate(yBottom, 0, 1, 0, 1) :
  11835. null;
  11836. // general hook, used for Highstock compare mode
  11837. if (hasModifyValue) {
  11838. yValue = series.modifyValue(yValue, point);
  11839. }
  11840. // Set the the plotY value, reset it for redraws
  11841. point.plotY = plotY = (typeof yValue === 'number' && yValue !== Infinity) ?
  11842. mathMin(mathMax(-1e5, yAxis.translate(yValue, 0, 1, 0, 1)), 1e5) : // #3201
  11843. UNDEFINED;
  11844. point.isInside = plotY !== UNDEFINED && plotY >= 0 && plotY <= yAxis.len && // #3519
  11845. plotX >= 0 && plotX <= xAxis.len;
  11846. // Set client related positions for mouse tracking
  11847. point.clientX = dynamicallyPlaced ? xAxis.translate(xValue, 0, 0, 0, 1) : plotX; // #1514
  11848. point.negative = point.y < (threshold || 0);
  11849. // some API data
  11850. point.category = categories && categories[point.x] !== UNDEFINED ?
  11851. categories[point.x] : point.x;
  11852. // Determine auto enabling of markers (#3635)
  11853. if (i) {
  11854. closestPointRangePx = mathMin(closestPointRangePx, mathAbs(plotX - lastPlotX));
  11855. }
  11856. lastPlotX = plotX;
  11857. }
  11858. series.closestPointRangePx = closestPointRangePx;
  11859. // now that we have the cropped data, build the segments
  11860. series.getSegments();
  11861. },
  11862. /**
  11863. * Set the clipping for the series. For animated series it is called twice, first to initiate
  11864. * animating the clip then the second time without the animation to set the final clip.
  11865. */
  11866. setClip: function (animation) {
  11867. var chart = this.chart,
  11868. renderer = chart.renderer,
  11869. inverted = chart.inverted,
  11870. seriesClipBox = this.clipBox,
  11871. clipBox = seriesClipBox || chart.clipBox,
  11872. sharedClipKey = this.sharedClipKey || ['_sharedClip', animation && animation.duration, animation && animation.easing, clipBox.height].join(','),
  11873. clipRect = chart[sharedClipKey],
  11874. markerClipRect = chart[sharedClipKey + 'm'];
  11875. // If a clipping rectangle with the same properties is currently present in the chart, use that.
  11876. if (!clipRect) {
  11877. // When animation is set, prepare the initial positions
  11878. if (animation) {
  11879. clipBox.width = 0;
  11880. chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect(
  11881. -99, // include the width of the first marker
  11882. inverted ? -chart.plotLeft : -chart.plotTop,
  11883. 99,
  11884. inverted ? chart.chartWidth : chart.chartHeight
  11885. );
  11886. }
  11887. chart[sharedClipKey] = clipRect = renderer.clipRect(clipBox);
  11888. }
  11889. if (animation) {
  11890. clipRect.count += 1;
  11891. }
  11892. if (this.options.clip !== false) {
  11893. this.group.clip(animation || seriesClipBox ? clipRect : chart.clipRect);
  11894. this.markerGroup.clip(markerClipRect);
  11895. this.sharedClipKey = sharedClipKey;
  11896. }
  11897. // Remove the shared clipping rectangle when all series are shown
  11898. if (!animation) {
  11899. clipRect.count -= 1;
  11900. if (clipRect.count <= 0 && sharedClipKey && chart[sharedClipKey]) {
  11901. if (!seriesClipBox) {
  11902. chart[sharedClipKey] = chart[sharedClipKey].destroy();
  11903. }
  11904. if (chart[sharedClipKey + 'm']) {
  11905. chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy();
  11906. }
  11907. }
  11908. }
  11909. },
  11910. /**
  11911. * Animate in the series
  11912. */
  11913. animate: function (init) {
  11914. var series = this,
  11915. chart = series.chart,
  11916. clipRect,
  11917. animation = series.options.animation,
  11918. sharedClipKey;
  11919. // Animation option is set to true
  11920. if (animation && !isObject(animation)) {
  11921. animation = defaultPlotOptions[series.type].animation;
  11922. }
  11923. // Initialize the animation. Set up the clipping rectangle.
  11924. if (init) {
  11925. series.setClip(animation);
  11926. // Run the animation
  11927. } else {
  11928. sharedClipKey = this.sharedClipKey;
  11929. clipRect = chart[sharedClipKey];
  11930. if (clipRect) {
  11931. clipRect.animate({
  11932. width: chart.plotSizeX
  11933. }, animation);
  11934. }
  11935. if (chart[sharedClipKey + 'm']) {
  11936. chart[sharedClipKey + 'm'].animate({
  11937. width: chart.plotSizeX + 99
  11938. }, animation);
  11939. }
  11940. // Delete this function to allow it only once
  11941. series.animate = null;
  11942. }
  11943. },
  11944. /**
  11945. * This runs after animation to land on the final plot clipping
  11946. */
  11947. afterAnimate: function () {
  11948. this.setClip();
  11949. fireEvent(this, 'afterAnimate');
  11950. },
  11951. /**
  11952. * Draw the markers
  11953. */
  11954. drawPoints: function () {
  11955. var series = this,
  11956. pointAttr,
  11957. points = series.points,
  11958. chart = series.chart,
  11959. plotX,
  11960. plotY,
  11961. i,
  11962. point,
  11963. radius,
  11964. symbol,
  11965. isImage,
  11966. graphic,
  11967. options = series.options,
  11968. seriesMarkerOptions = options.marker,
  11969. seriesPointAttr = series.pointAttr[''],
  11970. pointMarkerOptions,
  11971. hasPointMarker,
  11972. enabled,
  11973. isInside,
  11974. markerGroup = series.markerGroup,
  11975. xAxis = series.xAxis,
  11976. globallyEnabled = pick(
  11977. seriesMarkerOptions.enabled,
  11978. xAxis.isRadial,
  11979. series.closestPointRangePx > 2 * seriesMarkerOptions.radius
  11980. );
  11981. if (seriesMarkerOptions.enabled !== false || series._hasPointMarkers) {
  11982. i = points.length;
  11983. while (i--) {
  11984. point = points[i];
  11985. plotX = mathFloor(point.plotX); // #1843
  11986. plotY = point.plotY;
  11987. graphic = point.graphic;
  11988. pointMarkerOptions = point.marker || {};
  11989. hasPointMarker = !!point.marker;
  11990. enabled = (globallyEnabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled;
  11991. isInside = point.isInside;
  11992. // only draw the point if y is defined
  11993. if (enabled && plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) {
  11994. // shortcuts
  11995. pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || seriesPointAttr;
  11996. radius = pointAttr.r;
  11997. symbol = pick(pointMarkerOptions.symbol, series.symbol);
  11998. isImage = symbol.indexOf('url') === 0;
  11999. if (graphic) { // update
  12000. graphic[isInside ? 'show' : 'hide'](true) // Since the marker group isn't clipped, each individual marker must be toggled
  12001. .animate(extend({
  12002. x: plotX - radius,
  12003. y: plotY - radius
  12004. }, graphic.symbolName ? { // don't apply to image symbols #507
  12005. width: 2 * radius,
  12006. height: 2 * radius
  12007. } : {}));
  12008. } else if (isInside && (radius > 0 || isImage)) {
  12009. point.graphic = graphic = chart.renderer.symbol(
  12010. symbol,
  12011. plotX - radius,
  12012. plotY - radius,
  12013. 2 * radius,
  12014. 2 * radius,
  12015. hasPointMarker ? pointMarkerOptions : seriesMarkerOptions
  12016. )
  12017. .attr(pointAttr)
  12018. .add(markerGroup);
  12019. }
  12020. } else if (graphic) {
  12021. point.graphic = graphic.destroy(); // #1269
  12022. }
  12023. }
  12024. }
  12025. },
  12026. /**
  12027. * Convert state properties from API naming conventions to SVG attributes
  12028. *
  12029. * @param {Object} options API options object
  12030. * @param {Object} base1 SVG attribute object to inherit from
  12031. * @param {Object} base2 Second level SVG attribute object to inherit from
  12032. */
  12033. convertAttribs: function (options, base1, base2, base3) {
  12034. var conversion = this.pointAttrToOptions,
  12035. attr,
  12036. option,
  12037. obj = {};
  12038. options = options || {};
  12039. base1 = base1 || {};
  12040. base2 = base2 || {};
  12041. base3 = base3 || {};
  12042. for (attr in conversion) {
  12043. option = conversion[attr];
  12044. obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]);
  12045. }
  12046. return obj;
  12047. },
  12048. /**
  12049. * Get the state attributes. Each series type has its own set of attributes
  12050. * that are allowed to change on a point's state change. Series wide attributes are stored for
  12051. * all series, and additionally point specific attributes are stored for all
  12052. * points with individual marker options. If such options are not defined for the point,
  12053. * a reference to the series wide attributes is stored in point.pointAttr.
  12054. */
  12055. getAttribs: function () {
  12056. var series = this,
  12057. seriesOptions = series.options,
  12058. normalOptions = defaultPlotOptions[series.type].marker ? seriesOptions.marker : seriesOptions,
  12059. stateOptions = normalOptions.states,
  12060. stateOptionsHover = stateOptions[HOVER_STATE],
  12061. pointStateOptionsHover,
  12062. seriesColor = series.color,
  12063. seriesNegativeColor = series.options.negativeColor,
  12064. normalDefaults = {
  12065. stroke: seriesColor,
  12066. fill: seriesColor
  12067. },
  12068. points = series.points || [], // #927
  12069. i,
  12070. point,
  12071. seriesPointAttr = [],
  12072. pointAttr,
  12073. pointAttrToOptions = series.pointAttrToOptions,
  12074. hasPointSpecificOptions = series.hasPointSpecificOptions,
  12075. defaultLineColor = normalOptions.lineColor,
  12076. defaultFillColor = normalOptions.fillColor,
  12077. turboThreshold = seriesOptions.turboThreshold,
  12078. zones = series.zones,
  12079. zoneAxis = series.zoneAxis || 'y',
  12080. attr,
  12081. key;
  12082. // series type specific modifications
  12083. if (seriesOptions.marker) { // line, spline, area, areaspline, scatter
  12084. // if no hover radius is given, default to normal radius + 2
  12085. stateOptionsHover.radius = stateOptionsHover.radius || normalOptions.radius + stateOptionsHover.radiusPlus;
  12086. stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + stateOptionsHover.lineWidthPlus;
  12087. } else { // column, bar, pie
  12088. // if no hover color is given, brighten the normal color
  12089. stateOptionsHover.color = stateOptionsHover.color ||
  12090. Color(stateOptionsHover.color || seriesColor)
  12091. .brighten(stateOptionsHover.brightness).get();
  12092. // if no hover negativeColor is given, brighten the normal negativeColor
  12093. stateOptionsHover.negativeColor = stateOptionsHover.negativeColor ||
  12094. Color(stateOptionsHover.negativeColor || seriesNegativeColor)
  12095. .brighten(stateOptionsHover.brightness).get();
  12096. }
  12097. // general point attributes for the series normal state
  12098. seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults);
  12099. // HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius
  12100. each([HOVER_STATE, SELECT_STATE], function (state) {
  12101. seriesPointAttr[state] =
  12102. series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]);
  12103. });
  12104. // set it
  12105. series.pointAttr = seriesPointAttr;
  12106. // Generate the point-specific attribute collections if specific point
  12107. // options are given. If not, create a referance to the series wide point
  12108. // attributes
  12109. i = points.length;
  12110. if (!turboThreshold || i < turboThreshold || hasPointSpecificOptions) {
  12111. while (i--) {
  12112. point = points[i];
  12113. normalOptions = (point.options && point.options.marker) || point.options;
  12114. if (normalOptions && normalOptions.enabled === false) {
  12115. normalOptions.radius = 0;
  12116. }
  12117. if (zones.length) {
  12118. var j = 0,
  12119. threshold = zones[j];
  12120. while (point[zoneAxis] >= threshold.value) {
  12121. threshold = zones[++j];
  12122. }
  12123. point.color = point.fillColor = threshold.color;
  12124. }
  12125. hasPointSpecificOptions = seriesOptions.colorByPoint || point.color; // #868
  12126. // check if the point has specific visual options
  12127. if (point.options) {
  12128. for (key in pointAttrToOptions) {
  12129. if (defined(normalOptions[pointAttrToOptions[key]])) {
  12130. hasPointSpecificOptions = true;
  12131. }
  12132. }
  12133. }
  12134. // a specific marker config object is defined for the individual point:
  12135. // create it's own attribute collection
  12136. if (hasPointSpecificOptions) {
  12137. normalOptions = normalOptions || {};
  12138. pointAttr = [];
  12139. stateOptions = normalOptions.states || {}; // reassign for individual point
  12140. pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {};
  12141. // Handle colors for column and pies
  12142. if (!seriesOptions.marker) { // column, bar, point
  12143. // If no hover color is given, brighten the normal color. #1619, #2579
  12144. pointStateOptionsHover.color = pointStateOptionsHover.color || (!point.options.color && stateOptionsHover[(point.negative && seriesNegativeColor ? 'negativeColor' : 'color')]) ||
  12145. Color(point.color)
  12146. .brighten(pointStateOptionsHover.brightness || stateOptionsHover.brightness)
  12147. .get();
  12148. }
  12149. // normal point state inherits series wide normal state
  12150. attr = { color: point.color }; // #868
  12151. if (!defaultFillColor) { // Individual point color or negative color markers (#2219)
  12152. attr.fillColor = point.color;
  12153. }
  12154. if (!defaultLineColor) {
  12155. attr.lineColor = point.color; // Bubbles take point color, line markers use white
  12156. }
  12157. // Color is explicitly set to null or undefined (#1288, #4068)
  12158. if (normalOptions.hasOwnProperty('color') && !normalOptions.color) {
  12159. delete normalOptions.color;
  12160. }
  12161. pointAttr[NORMAL_STATE] = series.convertAttribs(extend(attr, normalOptions), seriesPointAttr[NORMAL_STATE]);
  12162. // inherit from point normal and series hover
  12163. pointAttr[HOVER_STATE] = series.convertAttribs(
  12164. stateOptions[HOVER_STATE],
  12165. seriesPointAttr[HOVER_STATE],
  12166. pointAttr[NORMAL_STATE]
  12167. );
  12168. // inherit from point normal and series hover
  12169. pointAttr[SELECT_STATE] = series.convertAttribs(
  12170. stateOptions[SELECT_STATE],
  12171. seriesPointAttr[SELECT_STATE],
  12172. pointAttr[NORMAL_STATE]
  12173. );
  12174. // no marker config object is created: copy a reference to the series-wide
  12175. // attribute collection
  12176. } else {
  12177. pointAttr = seriesPointAttr;
  12178. }
  12179. point.pointAttr = pointAttr;
  12180. }
  12181. }
  12182. },
  12183. /**
  12184. * Clear DOM objects and free up memory
  12185. */
  12186. destroy: function () {
  12187. var series = this,
  12188. chart = series.chart,
  12189. issue134 = /AppleWebKit\/533/.test(userAgent),
  12190. destroy,
  12191. i,
  12192. data = series.data || [],
  12193. point,
  12194. prop,
  12195. axis;
  12196. // add event hook
  12197. fireEvent(series, 'destroy');
  12198. // remove all events
  12199. removeEvent(series);
  12200. // erase from axes
  12201. each(series.axisTypes || [], function (AXIS) {
  12202. axis = series[AXIS];
  12203. if (axis) {
  12204. erase(axis.series, series);
  12205. axis.isDirty = axis.forceRedraw = true;
  12206. }
  12207. });
  12208. // remove legend items
  12209. if (series.legendItem) {
  12210. series.chart.legend.destroyItem(series);
  12211. }
  12212. // destroy all points with their elements
  12213. i = data.length;
  12214. while (i--) {
  12215. point = data[i];
  12216. if (point && point.destroy) {
  12217. point.destroy();
  12218. }
  12219. }
  12220. series.points = null;
  12221. // Clear the animation timeout if we are destroying the series during initial animation
  12222. clearTimeout(series.animationTimeout);
  12223. // Destroy all SVGElements associated to the series
  12224. for (prop in series) {
  12225. if (series[prop] instanceof SVGElement && !series[prop].survive) { // Survive provides a hook for not destroying
  12226. // issue 134 workaround
  12227. destroy = issue134 && prop === 'group' ?
  12228. 'hide' :
  12229. 'destroy';
  12230. series[prop][destroy]();
  12231. }
  12232. }
  12233. // remove from hoverSeries
  12234. if (chart.hoverSeries === series) {
  12235. chart.hoverSeries = null;
  12236. }
  12237. erase(chart.series, series);
  12238. // clear all members
  12239. for (prop in series) {
  12240. delete series[prop];
  12241. }
  12242. },
  12243. /**
  12244. * Return the graph path of a segment
  12245. */
  12246. getSegmentPath: function (segment) {
  12247. var series = this,
  12248. segmentPath = [],
  12249. step = series.options.step;
  12250. // build the segment line
  12251. each(segment, function (point, i) {
  12252. var plotX = point.plotX,
  12253. plotY = point.plotY,
  12254. lastPoint;
  12255. if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object
  12256. segmentPath.push.apply(segmentPath, series.getPointSpline(segment, point, i));
  12257. } else {
  12258. // moveTo or lineTo
  12259. segmentPath.push(i ? L : M);
  12260. // step line?
  12261. if (step && i) {
  12262. lastPoint = segment[i - 1];
  12263. if (step === 'right') {
  12264. segmentPath.push(
  12265. lastPoint.plotX,
  12266. plotY
  12267. );
  12268. } else if (step === 'center') {
  12269. segmentPath.push(
  12270. (lastPoint.plotX + plotX) / 2,
  12271. lastPoint.plotY,
  12272. (lastPoint.plotX + plotX) / 2,
  12273. plotY
  12274. );
  12275. } else {
  12276. segmentPath.push(
  12277. plotX,
  12278. lastPoint.plotY
  12279. );
  12280. }
  12281. }
  12282. // normal line to next point
  12283. segmentPath.push(
  12284. point.plotX,
  12285. point.plotY
  12286. );
  12287. }
  12288. });
  12289. return segmentPath;
  12290. },
  12291. /**
  12292. * Get the graph path
  12293. */
  12294. getGraphPath: function () {
  12295. var series = this,
  12296. graphPath = [],
  12297. segmentPath,
  12298. singlePoints = []; // used in drawTracker
  12299. // Divide into segments and build graph and area paths
  12300. each(series.segments, function (segment) {
  12301. segmentPath = series.getSegmentPath(segment);
  12302. // add the segment to the graph, or a single point for tracking
  12303. if (segment.length > 1) {
  12304. graphPath = graphPath.concat(segmentPath);
  12305. } else {
  12306. singlePoints.push(segment[0]);
  12307. }
  12308. });
  12309. // Record it for use in drawGraph and drawTracker, and return graphPath
  12310. series.singlePoints = singlePoints;
  12311. series.graphPath = graphPath;
  12312. return graphPath;
  12313. },
  12314. /**
  12315. * Draw the actual graph
  12316. */
  12317. drawGraph: function () {
  12318. var series = this,
  12319. options = this.options,
  12320. props = [['graph', options.lineColor || this.color, options.dashStyle]],
  12321. lineWidth = options.lineWidth,
  12322. roundCap = options.linecap !== 'square',
  12323. graphPath = this.getGraphPath(),
  12324. fillColor = (this.fillGraph && this.color) || NONE, // polygon series use filled graph
  12325. zones = this.zones;
  12326. each(zones, function (threshold, i) {
  12327. props.push(['zoneGraph' + i, threshold.color || series.color, threshold.dashStyle || options.dashStyle]);
  12328. });
  12329. // Draw the graph
  12330. each(props, function (prop, i) {
  12331. var graphKey = prop[0],
  12332. graph = series[graphKey],
  12333. attribs;
  12334. if (graph) {
  12335. stop(graph); // cancel running animations, #459
  12336. graph.animate({ d: graphPath });
  12337. } else if ((lineWidth || fillColor) && graphPath.length) { // #1487
  12338. attribs = {
  12339. stroke: prop[1],
  12340. 'stroke-width': lineWidth,
  12341. fill: fillColor,
  12342. zIndex: 1 // #1069
  12343. };
  12344. if (prop[2]) {
  12345. attribs.dashstyle = prop[2];
  12346. } else if (roundCap) {
  12347. attribs['stroke-linecap'] = attribs['stroke-linejoin'] = 'round';
  12348. }
  12349. series[graphKey] = series.chart.renderer.path(graphPath)
  12350. .attr(attribs)
  12351. .add(series.group)
  12352. .shadow((i < 2) && options.shadow); // add shadow to normal series (0) or to first zone (1) #3932
  12353. }
  12354. });
  12355. },
  12356. /**
  12357. * Clip the graphs into the positive and negative coloured graphs
  12358. */
  12359. applyZones: function () {
  12360. var series = this,
  12361. chart = this.chart,
  12362. renderer = chart.renderer,
  12363. zones = this.zones,
  12364. translatedFrom,
  12365. translatedTo,
  12366. clips = this.clips || [],
  12367. clipAttr,
  12368. graph = this.graph,
  12369. area = this.area,
  12370. chartSizeMax = mathMax(chart.chartWidth, chart.chartHeight),
  12371. zoneAxis = this.zoneAxis || 'y',
  12372. axis = this[zoneAxis + 'Axis'],
  12373. reversed = axis.reversed,
  12374. horiz = axis.horiz,
  12375. ignoreZones = false;
  12376. if (zones.length && (graph || area)) {
  12377. // The use of the Color Threshold assumes there are no gaps
  12378. // so it is safe to hide the original graph and area
  12379. if (graph) {
  12380. graph.hide();
  12381. }
  12382. if (area) {
  12383. area.hide();
  12384. }
  12385. // Create the clips
  12386. each(zones, function (threshold, i) {
  12387. translatedFrom = pick(translatedTo, (reversed ? (horiz ? chart.plotWidth : 0) : (horiz ? 0 : axis.toPixels(axis.min))));
  12388. translatedTo = mathRound(axis.toPixels(pick(threshold.value, axis.max), true));
  12389. if (axis.isXAxis) {
  12390. translatedFrom = translatedFrom > translatedTo ? translatedTo : translatedFrom; //#4006 from should be less or equal then to
  12391. } else {
  12392. translatedFrom = translatedFrom < translatedTo ? translatedTo : translatedFrom; //#4006 from should be less or equal then to
  12393. }
  12394. if (ignoreZones) {
  12395. translatedFrom = translatedTo = axis.toPixels(axis.max);
  12396. }
  12397. if (axis.isXAxis) {
  12398. clipAttr = {
  12399. x: reversed ? translatedTo : translatedFrom,
  12400. y: 0,
  12401. width: Math.abs(translatedFrom - translatedTo),
  12402. height: chartSizeMax
  12403. };
  12404. if (!horiz) {
  12405. clipAttr.x = chart.plotHeight - clipAttr.x;
  12406. }
  12407. } else {
  12408. clipAttr = {
  12409. x: 0,
  12410. y: reversed ? translatedFrom : translatedTo,
  12411. width: chartSizeMax,
  12412. height: Math.abs(translatedFrom - translatedTo)
  12413. };
  12414. if (horiz) {
  12415. clipAttr.y = chart.plotWidth - clipAttr.y;
  12416. }
  12417. }
  12418. /// VML SUPPPORT
  12419. if (chart.inverted && renderer.isVML) {
  12420. if (axis.isXAxis) {
  12421. clipAttr = {
  12422. x: 0,
  12423. y: reversed ? translatedFrom : translatedTo,
  12424. height: clipAttr.width,
  12425. width: chart.chartWidth
  12426. };
  12427. } else {
  12428. clipAttr = {
  12429. x: clipAttr.y - chart.plotLeft - chart.spacingBox.x,
  12430. y: 0,
  12431. width: clipAttr.height,
  12432. height: chart.chartHeight
  12433. };
  12434. }
  12435. }
  12436. /// END OF VML SUPPORT
  12437. if (clips[i]) {
  12438. clips[i].animate(clipAttr);
  12439. } else {
  12440. clips[i] = renderer.clipRect(clipAttr);
  12441. if (graph) {
  12442. series['zoneGraph' + i].clip(clips[i]);
  12443. }
  12444. if (area) {
  12445. series['zoneArea' + i].clip(clips[i]);
  12446. }
  12447. }
  12448. // if this zone extends out of the axis, ignore the others
  12449. ignoreZones = threshold.value > axis.max;
  12450. });
  12451. this.clips = clips;
  12452. }
  12453. },
  12454. /**
  12455. * Initialize and perform group inversion on series.group and series.markerGroup
  12456. */
  12457. invertGroups: function () {
  12458. var series = this,
  12459. chart = series.chart;
  12460. // Pie, go away (#1736)
  12461. if (!series.xAxis) {
  12462. return;
  12463. }
  12464. // A fixed size is needed for inversion to work
  12465. function setInvert() {
  12466. var size = {
  12467. width: series.yAxis.len,
  12468. height: series.xAxis.len
  12469. };
  12470. each(['group', 'markerGroup'], function (groupName) {
  12471. if (series[groupName]) {
  12472. series[groupName].attr(size).invert();
  12473. }
  12474. });
  12475. }
  12476. addEvent(chart, 'resize', setInvert); // do it on resize
  12477. addEvent(series, 'destroy', function () {
  12478. removeEvent(chart, 'resize', setInvert);
  12479. });
  12480. // Do it now
  12481. setInvert(); // do it now
  12482. // On subsequent render and redraw, just do setInvert without setting up events again
  12483. series.invertGroups = setInvert;
  12484. },
  12485. /**
  12486. * General abstraction for creating plot groups like series.group, series.dataLabelsGroup and
  12487. * series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size.
  12488. */
  12489. plotGroup: function (prop, name, visibility, zIndex, parent) {
  12490. var group = this[prop],
  12491. isNew = !group;
  12492. // Generate it on first call
  12493. if (isNew) {
  12494. this[prop] = group = this.chart.renderer.g(name)
  12495. .attr({
  12496. visibility: visibility,
  12497. zIndex: zIndex || 0.1 // IE8 needs this
  12498. })
  12499. .add(parent);
  12500. }
  12501. // Place it on first and subsequent (redraw) calls
  12502. group[isNew ? 'attr' : 'animate'](this.getPlotBox());
  12503. return group;
  12504. },
  12505. /**
  12506. * Get the translation and scale for the plot area of this series
  12507. */
  12508. getPlotBox: function () {
  12509. var chart = this.chart,
  12510. xAxis = this.xAxis,
  12511. yAxis = this.yAxis;
  12512. // Swap axes for inverted (#2339)
  12513. if (chart.inverted) {
  12514. xAxis = yAxis;
  12515. yAxis = this.xAxis;
  12516. }
  12517. return {
  12518. translateX: xAxis ? xAxis.left : chart.plotLeft,
  12519. translateY: yAxis ? yAxis.top : chart.plotTop,
  12520. scaleX: 1, // #1623
  12521. scaleY: 1
  12522. };
  12523. },
  12524. /**
  12525. * Render the graph and markers
  12526. */
  12527. render: function () {
  12528. var series = this,
  12529. chart = series.chart,
  12530. group,
  12531. options = series.options,
  12532. animation = options.animation,
  12533. // Animation doesn't work in IE8 quirks when the group div is hidden,
  12534. // and looks bad in other oldIE
  12535. animDuration = (animation && !!series.animate && chart.renderer.isSVG && pick(animation.duration, 500)) || 0,
  12536. visibility = series.visible ? VISIBLE : HIDDEN,
  12537. zIndex = options.zIndex,
  12538. hasRendered = series.hasRendered,
  12539. chartSeriesGroup = chart.seriesGroup;
  12540. // the group
  12541. group = series.plotGroup(
  12542. 'group',
  12543. 'series',
  12544. visibility,
  12545. zIndex,
  12546. chartSeriesGroup
  12547. );
  12548. series.markerGroup = series.plotGroup(
  12549. 'markerGroup',
  12550. 'markers',
  12551. visibility,
  12552. zIndex,
  12553. chartSeriesGroup
  12554. );
  12555. // initiate the animation
  12556. if (animDuration) {
  12557. series.animate(true);
  12558. }
  12559. // cache attributes for shapes
  12560. series.getAttribs();
  12561. // SVGRenderer needs to know this before drawing elements (#1089, #1795)
  12562. group.inverted = series.isCartesian ? chart.inverted : false;
  12563. // draw the graph if any
  12564. if (series.drawGraph) {
  12565. series.drawGraph();
  12566. series.applyZones();
  12567. }
  12568. each(series.points, function (point) {
  12569. if (point.redraw) {
  12570. point.redraw();
  12571. }
  12572. });
  12573. // draw the data labels (inn pies they go before the points)
  12574. if (series.drawDataLabels) {
  12575. series.drawDataLabels();
  12576. }
  12577. // draw the points
  12578. if (series.visible) {
  12579. series.drawPoints();
  12580. }
  12581. // draw the mouse tracking area
  12582. if (series.drawTracker && series.options.enableMouseTracking !== false) {
  12583. series.drawTracker();
  12584. }
  12585. // Handle inverted series and tracker groups
  12586. if (chart.inverted) {
  12587. series.invertGroups();
  12588. }
  12589. // Initial clipping, must be defined after inverting groups for VML. Applies to columns etc. (#3839).
  12590. if (options.clip !== false && !series.sharedClipKey && !hasRendered) {
  12591. group.clip(chart.clipRect);
  12592. }
  12593. // Run the animation
  12594. if (animDuration) {
  12595. series.animate();
  12596. }
  12597. // Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option
  12598. // which should be available to the user).
  12599. if (!hasRendered) {
  12600. if (animDuration) {
  12601. series.animationTimeout = setTimeout(function () {
  12602. series.afterAnimate();
  12603. }, animDuration);
  12604. } else {
  12605. series.afterAnimate();
  12606. }
  12607. }
  12608. series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
  12609. // (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
  12610. series.hasRendered = true;
  12611. },
  12612. /**
  12613. * Redraw the series after an update in the axes.
  12614. */
  12615. redraw: function () {
  12616. var series = this,
  12617. chart = series.chart,
  12618. wasDirtyData = series.isDirtyData, // cache it here as it is set to false in render, but used after
  12619. wasDirty = series.isDirty,
  12620. group = series.group,
  12621. xAxis = series.xAxis,
  12622. yAxis = series.yAxis;
  12623. // reposition on resize
  12624. if (group) {
  12625. if (chart.inverted) {
  12626. group.attr({
  12627. width: chart.plotWidth,
  12628. height: chart.plotHeight
  12629. });
  12630. }
  12631. group.animate({
  12632. translateX: pick(xAxis && xAxis.left, chart.plotLeft),
  12633. translateY: pick(yAxis && yAxis.top, chart.plotTop)
  12634. });
  12635. }
  12636. series.translate();
  12637. series.render();
  12638. if (wasDirtyData) {
  12639. fireEvent(series, 'updatedData');
  12640. }
  12641. if (wasDirty || wasDirtyData) { // #3945 recalculate the kdtree when dirty
  12642. delete this.kdTree; // #3868 recalculate the kdtree with dirty data
  12643. }
  12644. },
  12645. /**
  12646. * KD Tree && PointSearching Implementation
  12647. */
  12648. kdDimensions: 1,
  12649. kdTree: null,
  12650. kdAxisArray: ['clientX', 'plotY'],
  12651. kdComparer: 'distX',
  12652. searchPoint: function (e) {
  12653. var series = this,
  12654. xAxis = series.xAxis,
  12655. yAxis = series.yAxis,
  12656. inverted = series.chart.inverted;
  12657. return this.searchKDTree({
  12658. clientX: inverted ? xAxis.len - e.chartY + xAxis.pos : e.chartX - xAxis.pos,
  12659. plotY: inverted ? yAxis.len - e.chartX + yAxis.pos : e.chartY - yAxis.pos
  12660. });
  12661. },
  12662. buildKDTree: function () {
  12663. var series = this,
  12664. dimensions = series.kdDimensions;
  12665. // Internal function
  12666. function _kdtree(points, depth, dimensions) {
  12667. var axis, median, length = points && points.length;
  12668. if (length) {
  12669. // alternate between the axis
  12670. axis = series.kdAxisArray[depth % dimensions];
  12671. // sort point array
  12672. points.sort(function(a, b) {
  12673. return a[axis] - b[axis];
  12674. });
  12675. median = Math.floor(length / 2);
  12676. // build and return node
  12677. return {
  12678. point: points[median],
  12679. left: _kdtree(points.slice(0, median), depth + 1, dimensions),
  12680. right: _kdtree(points.slice(median + 1), depth + 1, dimensions)
  12681. };
  12682. }
  12683. }
  12684. // Start the recursive build process with a clone of the points array and null points filtered out (#3873)
  12685. function startRecursive() {
  12686. var points = grep(series.points, function (point) {
  12687. return point.y !== null;
  12688. });
  12689. series.kdTree = _kdtree(points, dimensions, dimensions);
  12690. }
  12691. delete series.kdTree;
  12692. if (series.options.kdSync) { // For testing tooltips, don't build async
  12693. startRecursive();
  12694. } else {
  12695. setTimeout(startRecursive);
  12696. }
  12697. },
  12698. searchKDTree: function (point) {
  12699. var series = this,
  12700. kdComparer = this.kdComparer,
  12701. kdX = this.kdAxisArray[0],
  12702. kdY = this.kdAxisArray[1];
  12703. // Internal function
  12704. function _distance(p1, p2) {
  12705. var x = (defined(p1[kdX]) && defined(p2[kdX])) ? Math.pow(p1[kdX] - p2[kdX], 2) : null,
  12706. y = (defined(p1[kdY]) && defined(p2[kdY])) ? Math.pow(p1[kdY] - p2[kdY], 2) : null,
  12707. r = (x || 0) + (y || 0);
  12708. return {
  12709. distX: defined(x) ? Math.sqrt(x) : Number.MAX_VALUE,
  12710. distY: defined(y) ? Math.sqrt(y) : Number.MAX_VALUE,
  12711. distR: defined(r) ? Math.sqrt(r) : Number.MAX_VALUE
  12712. };
  12713. }
  12714. function _search(search, tree, depth, dimensions) {
  12715. var point = tree.point,
  12716. axis = series.kdAxisArray[depth % dimensions],
  12717. tdist,
  12718. sideA,
  12719. sideB,
  12720. ret = point,
  12721. nPoint1,
  12722. nPoint2;
  12723. point.dist = _distance(search, point);
  12724. // Pick side based on distance to splitting point
  12725. tdist = search[axis] - point[axis];
  12726. sideA = tdist < 0 ? 'left' : 'right';
  12727. // End of tree
  12728. if (tree[sideA]) {
  12729. nPoint1 =_search(search, tree[sideA], depth + 1, dimensions);
  12730. ret = (nPoint1.dist[kdComparer] < ret.dist[kdComparer] ? nPoint1 : point);
  12731. sideB = tdist < 0 ? 'right' : 'left';
  12732. if (tree[sideB]) {
  12733. // compare distance to current best to splitting point to decide wether to check side B or not
  12734. if (Math.sqrt(tdist*tdist) < ret.dist[kdComparer]) {
  12735. nPoint2 = _search(search, tree[sideB], depth + 1, dimensions);
  12736. ret = (nPoint2.dist[kdComparer] < ret.dist[kdComparer] ? nPoint2 : ret);
  12737. }
  12738. }
  12739. }
  12740. return ret;
  12741. }
  12742. if (!this.kdTree) {
  12743. this.buildKDTree();
  12744. }
  12745. if (this.kdTree) {
  12746. return _search(point,
  12747. this.kdTree, this.kdDimensions, this.kdDimensions);
  12748. }
  12749. }
  12750. }; // end Series prototype
  12751. /**
  12752. * The class for stack items
  12753. */
  12754. function StackItem(axis, options, isNegative, x, stackOption) {
  12755. var inverted = axis.chart.inverted;
  12756. this.axis = axis;
  12757. // Tells if the stack is negative
  12758. this.isNegative = isNegative;
  12759. // Save the options to be able to style the label
  12760. this.options = options;
  12761. // Save the x value to be able to position the label later
  12762. this.x = x;
  12763. // Initialize total value
  12764. this.total = null;
  12765. // This will keep each points' extremes stored by series.index and point index
  12766. this.points = {};
  12767. // Save the stack option on the series configuration object, and whether to treat it as percent
  12768. this.stack = stackOption;
  12769. // The align options and text align varies on whether the stack is negative and
  12770. // if the chart is inverted or not.
  12771. // First test the user supplied value, then use the dynamic.
  12772. this.alignOptions = {
  12773. align: options.align || (inverted ? (isNegative ? 'left' : 'right') : 'center'),
  12774. verticalAlign: options.verticalAlign || (inverted ? 'middle' : (isNegative ? 'bottom' : 'top')),
  12775. y: pick(options.y, inverted ? 4 : (isNegative ? 14 : -6)),
  12776. x: pick(options.x, inverted ? (isNegative ? -6 : 6) : 0)
  12777. };
  12778. this.textAlign = options.textAlign || (inverted ? (isNegative ? 'right' : 'left') : 'center');
  12779. }
  12780. StackItem.prototype = {
  12781. destroy: function () {
  12782. destroyObjectProperties(this, this.axis);
  12783. },
  12784. /**
  12785. * Renders the stack total label and adds it to the stack label group.
  12786. */
  12787. render: function (group) {
  12788. var options = this.options,
  12789. formatOption = options.format,
  12790. str = formatOption ?
  12791. format(formatOption, this) :
  12792. options.formatter.call(this); // format the text in the label
  12793. // Change the text to reflect the new total and set visibility to hidden in case the serie is hidden
  12794. if (this.label) {
  12795. this.label.attr({text: str, visibility: HIDDEN});
  12796. // Create new label
  12797. } else {
  12798. this.label =
  12799. this.axis.chart.renderer.text(str, null, null, options.useHTML) // dummy positions, actual position updated with setOffset method in columnseries
  12800. .css(options.style) // apply style
  12801. .attr({
  12802. align: this.textAlign, // fix the text-anchor
  12803. rotation: options.rotation, // rotation
  12804. visibility: HIDDEN // hidden until setOffset is called
  12805. })
  12806. .add(group); // add to the labels-group
  12807. }
  12808. },
  12809. /**
  12810. * Sets the offset that the stack has from the x value and repositions the label.
  12811. */
  12812. setOffset: function (xOffset, xWidth) {
  12813. var stackItem = this,
  12814. axis = stackItem.axis,
  12815. chart = axis.chart,
  12816. inverted = chart.inverted,
  12817. reversed = axis.reversed,
  12818. neg = (this.isNegative && !reversed) || (!this.isNegative && reversed), // #4056
  12819. y = axis.translate(axis.usePercentage ? 100 : this.total, 0, 0, 0, 1), // stack value translated mapped to chart coordinates
  12820. yZero = axis.translate(0), // stack origin
  12821. h = mathAbs(y - yZero), // stack height
  12822. x = chart.xAxis[0].translate(this.x) + xOffset, // stack x position
  12823. plotHeight = chart.plotHeight,
  12824. stackBox = { // this is the box for the complete stack
  12825. x: inverted ? (neg ? y : y - h) : x,
  12826. y: inverted ? plotHeight - x - xWidth : (neg ? (plotHeight - y - h) : plotHeight - y),
  12827. width: inverted ? h : xWidth,
  12828. height: inverted ? xWidth : h
  12829. },
  12830. label = this.label,
  12831. alignAttr;
  12832. if (label) {
  12833. label.align(this.alignOptions, null, stackBox); // align the label to the box
  12834. // Set visibility (#678)
  12835. alignAttr = label.alignAttr;
  12836. label[this.options.crop === false || chart.isInsidePlot(alignAttr.x, alignAttr.y) ? 'show' : 'hide'](true);
  12837. }
  12838. }
  12839. };
  12840. // Stacking methods defined on the Axis prototype
  12841. /**
  12842. * Build the stacks from top down
  12843. */
  12844. Axis.prototype.buildStacks = function () {
  12845. var series = this.series,
  12846. reversedStacks = pick(this.options.reversedStacks, true),
  12847. i = series.length;
  12848. if (!this.isXAxis) {
  12849. this.usePercentage = false;
  12850. while (i--) {
  12851. series[reversedStacks ? i : series.length - i - 1].setStackedPoints();
  12852. }
  12853. // Loop up again to compute percent stack
  12854. if (this.usePercentage) {
  12855. for (i = 0; i < series.length; i++) {
  12856. series[i].setPercentStacks();
  12857. }
  12858. }
  12859. }
  12860. };
  12861. Axis.prototype.renderStackTotals = function () {
  12862. var axis = this,
  12863. chart = axis.chart,
  12864. renderer = chart.renderer,
  12865. stacks = axis.stacks,
  12866. stackKey,
  12867. oneStack,
  12868. stackCategory,
  12869. stackTotalGroup = axis.stackTotalGroup;
  12870. // Create a separate group for the stack total labels
  12871. if (!stackTotalGroup) {
  12872. axis.stackTotalGroup = stackTotalGroup =
  12873. renderer.g('stack-labels')
  12874. .attr({
  12875. visibility: VISIBLE,
  12876. zIndex: 6
  12877. })
  12878. .add();
  12879. }
  12880. // plotLeft/Top will change when y axis gets wider so we need to translate the
  12881. // stackTotalGroup at every render call. See bug #506 and #516
  12882. stackTotalGroup.translate(chart.plotLeft, chart.plotTop);
  12883. // Render each stack total
  12884. for (stackKey in stacks) {
  12885. oneStack = stacks[stackKey];
  12886. for (stackCategory in oneStack) {
  12887. oneStack[stackCategory].render(stackTotalGroup);
  12888. }
  12889. }
  12890. };
  12891. // Stacking methods defnied for Series prototype
  12892. /**
  12893. * Adds series' points value to corresponding stack
  12894. */
  12895. Series.prototype.setStackedPoints = function () {
  12896. if (!this.options.stacking || (this.visible !== true && this.chart.options.chart.ignoreHiddenSeries !== false)) {
  12897. return;
  12898. }
  12899. var series = this,
  12900. xData = series.processedXData,
  12901. yData = series.processedYData,
  12902. stackedYData = [],
  12903. yDataLength = yData.length,
  12904. seriesOptions = series.options,
  12905. threshold = seriesOptions.threshold,
  12906. stackOption = seriesOptions.stack,
  12907. stacking = seriesOptions.stacking,
  12908. stackKey = series.stackKey,
  12909. negKey = '-' + stackKey,
  12910. negStacks = series.negStacks,
  12911. yAxis = series.yAxis,
  12912. stacks = yAxis.stacks,
  12913. oldStacks = yAxis.oldStacks,
  12914. isNegative,
  12915. stack,
  12916. other,
  12917. key,
  12918. pointKey,
  12919. i,
  12920. x,
  12921. y;
  12922. // loop over the non-null y values and read them into a local array
  12923. for (i = 0; i < yDataLength; i++) {
  12924. x = xData[i];
  12925. y = yData[i];
  12926. pointKey = series.index + ',' + i;
  12927. // Read stacked values into a stack based on the x value,
  12928. // the sign of y and the stack key. Stacking is also handled for null values (#739)
  12929. isNegative = negStacks && y < threshold;
  12930. key = isNegative ? negKey : stackKey;
  12931. // Create empty object for this stack if it doesn't exist yet
  12932. if (!stacks[key]) {
  12933. stacks[key] = {};
  12934. }
  12935. // Initialize StackItem for this x
  12936. if (!stacks[key][x]) {
  12937. if (oldStacks[key] && oldStacks[key][x]) {
  12938. stacks[key][x] = oldStacks[key][x];
  12939. stacks[key][x].total = null;
  12940. } else {
  12941. stacks[key][x] = new StackItem(yAxis, yAxis.options.stackLabels, isNegative, x, stackOption);
  12942. }
  12943. }
  12944. // If the StackItem doesn't exist, create it first
  12945. stack = stacks[key][x];
  12946. stack.points[pointKey] = [stack.cum || 0];
  12947. // Add value to the stack total
  12948. if (stacking === 'percent') {
  12949. // Percent stacked column, totals are the same for the positive and negative stacks
  12950. other = isNegative ? stackKey : negKey;
  12951. if (negStacks && stacks[other] && stacks[other][x]) {
  12952. other = stacks[other][x];
  12953. stack.total = other.total = mathMax(other.total, stack.total) + mathAbs(y) || 0;
  12954. // Percent stacked areas
  12955. } else {
  12956. stack.total = correctFloat(stack.total + (mathAbs(y) || 0));
  12957. }
  12958. } else {
  12959. stack.total = correctFloat(stack.total + (y || 0));
  12960. }
  12961. stack.cum = (stack.cum || 0) + (y || 0);
  12962. stack.points[pointKey].push(stack.cum);
  12963. stackedYData[i] = stack.cum;
  12964. }
  12965. if (stacking === 'percent') {
  12966. yAxis.usePercentage = true;
  12967. }
  12968. this.stackedYData = stackedYData; // To be used in getExtremes
  12969. // Reset old stacks
  12970. yAxis.oldStacks = {};
  12971. };
  12972. /**
  12973. * Iterate over all stacks and compute the absolute values to percent
  12974. */
  12975. Series.prototype.setPercentStacks = function () {
  12976. var series = this,
  12977. stackKey = series.stackKey,
  12978. stacks = series.yAxis.stacks,
  12979. processedXData = series.processedXData;
  12980. each([stackKey, '-' + stackKey], function (key) {
  12981. var i = processedXData.length,
  12982. x,
  12983. stack,
  12984. pointExtremes,
  12985. totalFactor;
  12986. while (i--) {
  12987. x = processedXData[i];
  12988. stack = stacks[key] && stacks[key][x];
  12989. pointExtremes = stack && stack.points[series.index + ',' + i];
  12990. if (pointExtremes) {
  12991. totalFactor = stack.total ? 100 / stack.total : 0;
  12992. pointExtremes[0] = correctFloat(pointExtremes[0] * totalFactor); // Y bottom value
  12993. pointExtremes[1] = correctFloat(pointExtremes[1] * totalFactor); // Y value
  12994. series.stackedYData[i] = pointExtremes[1];
  12995. }
  12996. }
  12997. });
  12998. };
  12999. // Extend the Chart prototype for dynamic methods
  13000. extend(Chart.prototype, {
  13001. /**
  13002. * Add a series dynamically after time
  13003. *
  13004. * @param {Object} options The config options
  13005. * @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true.
  13006. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  13007. * configuration
  13008. *
  13009. * @return {Object} series The newly created series object
  13010. */
  13011. addSeries: function (options, redraw, animation) {
  13012. var series,
  13013. chart = this;
  13014. if (options) {
  13015. redraw = pick(redraw, true); // defaults to true
  13016. fireEvent(chart, 'addSeries', { options: options }, function () {
  13017. series = chart.initSeries(options);
  13018. chart.isDirtyLegend = true; // the series array is out of sync with the display
  13019. chart.linkSeries();
  13020. if (redraw) {
  13021. chart.redraw(animation);
  13022. }
  13023. });
  13024. }
  13025. return series;
  13026. },
  13027. /**
  13028. * Add an axis to the chart
  13029. * @param {Object} options The axis option
  13030. * @param {Boolean} isX Whether it is an X axis or a value axis
  13031. */
  13032. addAxis: function (options, isX, redraw, animation) {
  13033. var key = isX ? 'xAxis' : 'yAxis',
  13034. chartOptions = this.options,
  13035. axis;
  13036. /*jslint unused: false*/
  13037. axis = new Axis(this, merge(options, {
  13038. index: this[key].length,
  13039. isX: isX
  13040. }));
  13041. /*jslint unused: true*/
  13042. // Push the new axis options to the chart options
  13043. chartOptions[key] = splat(chartOptions[key] || {});
  13044. chartOptions[key].push(options);
  13045. if (pick(redraw, true)) {
  13046. this.redraw(animation);
  13047. }
  13048. },
  13049. /**
  13050. * Dim the chart and show a loading text or symbol
  13051. * @param {String} str An optional text to show in the loading label instead of the default one
  13052. */
  13053. showLoading: function (str) {
  13054. var chart = this,
  13055. options = chart.options,
  13056. loadingDiv = chart.loadingDiv,
  13057. loadingOptions = options.loading,
  13058. setLoadingSize = function () {
  13059. if (loadingDiv) {
  13060. css(loadingDiv, {
  13061. left: chart.plotLeft + PX,
  13062. top: chart.plotTop + PX,
  13063. width: chart.plotWidth + PX,
  13064. height: chart.plotHeight + PX
  13065. });
  13066. }
  13067. };
  13068. // create the layer at the first call
  13069. if (!loadingDiv) {
  13070. chart.loadingDiv = loadingDiv = createElement(DIV, {
  13071. className: PREFIX + 'loading'
  13072. }, extend(loadingOptions.style, {
  13073. zIndex: 10,
  13074. display: NONE
  13075. }), chart.container);
  13076. chart.loadingSpan = createElement(
  13077. 'span',
  13078. null,
  13079. loadingOptions.labelStyle,
  13080. loadingDiv
  13081. );
  13082. addEvent(chart, 'redraw', setLoadingSize); // #1080
  13083. }
  13084. // update text
  13085. chart.loadingSpan.innerHTML = str || options.lang.loading;
  13086. // show it
  13087. if (!chart.loadingShown) {
  13088. css(loadingDiv, {
  13089. opacity: 0,
  13090. display: ''
  13091. });
  13092. animate(loadingDiv, {
  13093. opacity: loadingOptions.style.opacity
  13094. }, {
  13095. duration: loadingOptions.showDuration || 0
  13096. });
  13097. chart.loadingShown = true;
  13098. }
  13099. setLoadingSize();
  13100. },
  13101. /**
  13102. * Hide the loading layer
  13103. */
  13104. hideLoading: function () {
  13105. var options = this.options,
  13106. loadingDiv = this.loadingDiv;
  13107. if (loadingDiv) {
  13108. animate(loadingDiv, {
  13109. opacity: 0
  13110. }, {
  13111. duration: options.loading.hideDuration || 100,
  13112. complete: function () {
  13113. css(loadingDiv, { display: NONE });
  13114. }
  13115. });
  13116. }
  13117. this.loadingShown = false;
  13118. }
  13119. });
  13120. // extend the Point prototype for dynamic methods
  13121. extend(Point.prototype, {
  13122. /**
  13123. * Update the point with new options (typically x/y data) and optionally redraw the series.
  13124. *
  13125. * @param {Object} options Point options as defined in the series.data array
  13126. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  13127. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  13128. * configuration
  13129. *
  13130. */
  13131. update: function (options, redraw, animation, runEvent) {
  13132. var point = this,
  13133. series = point.series,
  13134. graphic = point.graphic,
  13135. i,
  13136. chart = series.chart,
  13137. seriesOptions = series.options,
  13138. names = series.xAxis && series.xAxis.names;
  13139. redraw = pick(redraw, true);
  13140. function update() {
  13141. point.applyOptions(options);
  13142. // Update visuals
  13143. if (isObject(options) && !isArray(options)) {
  13144. // Defer the actual redraw until getAttribs has been called (#3260)
  13145. point.redraw = function () {
  13146. if (graphic) {
  13147. if (options && options.marker && options.marker.symbol) {
  13148. point.graphic = graphic.destroy();
  13149. } else {
  13150. graphic.attr(point.pointAttr[point.state || '']);
  13151. }
  13152. }
  13153. if (options && options.dataLabels && point.dataLabel) { // #2468
  13154. point.dataLabel = point.dataLabel.destroy();
  13155. }
  13156. point.redraw = null;
  13157. };
  13158. }
  13159. // record changes in the parallel arrays
  13160. i = point.index;
  13161. series.updateParallelArrays(point, i);
  13162. if (names && point.name) {
  13163. names[point.x] = point.name;
  13164. }
  13165. seriesOptions.data[i] = point.options;
  13166. // redraw
  13167. series.isDirty = series.isDirtyData = true;
  13168. if (!series.fixedBox && series.hasCartesianSeries) { // #1906, #2320
  13169. chart.isDirtyBox = true;
  13170. }
  13171. if (chart.legend.display && seriesOptions.legendType === 'point') { // #1831, #1885, #3934
  13172. series.updateTotals();
  13173. chart.legend.clearItems();
  13174. }
  13175. if (redraw) {
  13176. chart.redraw(animation);
  13177. }
  13178. }
  13179. // Fire the event with a default handler of doing the update
  13180. if (runEvent === false) { // When called from setData
  13181. update();
  13182. } else {
  13183. point.firePointEvent('update', { options: options }, update);
  13184. }
  13185. },
  13186. /**
  13187. * Remove a point and optionally redraw the series and if necessary the axes
  13188. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  13189. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  13190. * configuration
  13191. */
  13192. remove: function (redraw, animation) {
  13193. this.series.removePoint(inArray(this, this.series.data), redraw, animation);
  13194. }
  13195. });
  13196. // Extend the series prototype for dynamic methods
  13197. extend(Series.prototype, {
  13198. /**
  13199. * Add a point dynamically after chart load time
  13200. * @param {Object} options Point options as given in series.data
  13201. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  13202. * @param {Boolean} shift If shift is true, a point is shifted off the start
  13203. * of the series as one is appended to the end.
  13204. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  13205. * configuration
  13206. */
  13207. addPoint: function (options, redraw, shift, animation) {
  13208. var series = this,
  13209. seriesOptions = series.options,
  13210. data = series.data,
  13211. graph = series.graph,
  13212. area = series.area,
  13213. chart = series.chart,
  13214. names = series.xAxis && series.xAxis.names,
  13215. currentShift = (graph && graph.shift) || 0,
  13216. shiftShapes = ['graph', 'area'],
  13217. dataOptions = seriesOptions.data,
  13218. point,
  13219. isInTheMiddle,
  13220. xData = series.xData,
  13221. i,
  13222. x;
  13223. setAnimation(animation, chart);
  13224. // Make graph animate sideways
  13225. if (shift) {
  13226. i = series.zones.length;
  13227. while (i--) {
  13228. shiftShapes.push('zoneGraph' + i, 'zoneArea' + i);
  13229. }
  13230. each(shiftShapes, function (shape) {
  13231. if (series[shape]) {
  13232. series[shape].shift = currentShift + 1;
  13233. }
  13234. });
  13235. }
  13236. if (area) {
  13237. area.isArea = true; // needed in animation, both with and without shift
  13238. }
  13239. // Optional redraw, defaults to true
  13240. redraw = pick(redraw, true);
  13241. // Get options and push the point to xData, yData and series.options. In series.generatePoints
  13242. // the Point instance will be created on demand and pushed to the series.data array.
  13243. point = { series: series };
  13244. series.pointClass.prototype.applyOptions.apply(point, [options]);
  13245. x = point.x;
  13246. // Get the insertion point
  13247. i = xData.length;
  13248. if (series.requireSorting && x < xData[i - 1]) {
  13249. isInTheMiddle = true;
  13250. while (i && xData[i - 1] > x) {
  13251. i--;
  13252. }
  13253. }
  13254. series.updateParallelArrays(point, 'splice', i, 0, 0); // insert undefined item
  13255. series.updateParallelArrays(point, i); // update it
  13256. if (names && point.name) {
  13257. names[x] = point.name;
  13258. }
  13259. dataOptions.splice(i, 0, options);
  13260. if (isInTheMiddle) {
  13261. series.data.splice(i, 0, null);
  13262. series.processData();
  13263. }
  13264. // Generate points to be added to the legend (#1329)
  13265. if (seriesOptions.legendType === 'point') {
  13266. series.generatePoints();
  13267. }
  13268. // Shift the first point off the parallel arrays
  13269. // todo: consider series.removePoint(i) method
  13270. if (shift) {
  13271. if (data[0] && data[0].remove) {
  13272. data[0].remove(false);
  13273. } else {
  13274. data.shift();
  13275. series.updateParallelArrays(point, 'shift');
  13276. dataOptions.shift();
  13277. }
  13278. }
  13279. // redraw
  13280. series.isDirty = true;
  13281. series.isDirtyData = true;
  13282. if (redraw) {
  13283. series.getAttribs(); // #1937
  13284. chart.redraw();
  13285. }
  13286. },
  13287. /**
  13288. * Remove a point (rendered or not), by index
  13289. */
  13290. removePoint: function (i, redraw, animation) {
  13291. var series = this,
  13292. data = series.data,
  13293. point = data[i],
  13294. points = series.points,
  13295. chart = series.chart,
  13296. remove = function () {
  13297. if (data.length === points.length) {
  13298. points.splice(i, 1);
  13299. }
  13300. data.splice(i, 1);
  13301. series.options.data.splice(i, 1);
  13302. series.updateParallelArrays(point || { series: series }, 'splice', i, 1);
  13303. if (point) {
  13304. point.destroy();
  13305. }
  13306. // redraw
  13307. series.isDirty = true;
  13308. series.isDirtyData = true;
  13309. if (redraw) {
  13310. chart.redraw();
  13311. }
  13312. };
  13313. setAnimation(animation, chart);
  13314. redraw = pick(redraw, true);
  13315. // Fire the event with a default handler of removing the point
  13316. if (point) {
  13317. point.firePointEvent('remove', null, remove);
  13318. } else {
  13319. remove();
  13320. }
  13321. },
  13322. /**
  13323. * Remove a series and optionally redraw the chart
  13324. *
  13325. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  13326. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  13327. * configuration
  13328. */
  13329. remove: function (redraw, animation) {
  13330. var series = this,
  13331. chart = series.chart;
  13332. redraw = pick(redraw, true);
  13333. if (!series.isRemoving) { /* prevent triggering native event in jQuery
  13334. (calling the remove function from the remove event) */
  13335. series.isRemoving = true;
  13336. // fire the event with a default handler of removing the point
  13337. fireEvent(series, 'remove', null, function () {
  13338. // destroy elements
  13339. series.destroy();
  13340. // redraw
  13341. chart.isDirtyLegend = chart.isDirtyBox = true;
  13342. chart.linkSeries();
  13343. if (redraw) {
  13344. chart.redraw(animation);
  13345. }
  13346. });
  13347. }
  13348. series.isRemoving = false;
  13349. },
  13350. /**
  13351. * Update the series with a new set of options
  13352. */
  13353. update: function (newOptions, redraw) {
  13354. var series = this,
  13355. chart = this.chart,
  13356. // must use user options when changing type because this.options is merged
  13357. // in with type specific plotOptions
  13358. oldOptions = this.userOptions,
  13359. oldType = this.type,
  13360. proto = seriesTypes[oldType].prototype,
  13361. preserve = ['group', 'markerGroup', 'dataLabelsGroup'],
  13362. n;
  13363. // If we're changing type or zIndex, create new groups (#3380, #3404)
  13364. if ((newOptions.type && newOptions.type !== oldType) || newOptions.zIndex !== undefined) {
  13365. preserve.length = 0;
  13366. }
  13367. // Make sure groups are not destroyed (#3094)
  13368. each(preserve, function (prop) {
  13369. preserve[prop] = series[prop];
  13370. delete series[prop];
  13371. });
  13372. // Do the merge, with some forced options
  13373. newOptions = merge(oldOptions, {
  13374. animation: false,
  13375. index: this.index,
  13376. pointStart: this.xData[0] // when updating after addPoint
  13377. }, { data: this.options.data }, newOptions);
  13378. // Destroy the series and delete all properties. Reinsert all methods
  13379. // and properties from the new type prototype (#2270, #3719)
  13380. this.remove(false);
  13381. for (n in proto) {
  13382. this[n] = UNDEFINED;
  13383. }
  13384. extend(this, seriesTypes[newOptions.type || oldType].prototype);
  13385. // Re-register groups (#3094)
  13386. each(preserve, function (prop) {
  13387. series[prop] = preserve[prop];
  13388. });
  13389. this.init(chart, newOptions);
  13390. chart.linkSeries(); // Links are lost in this.remove (#3028)
  13391. if (pick(redraw, true)) {
  13392. chart.redraw(false);
  13393. }
  13394. }
  13395. });
  13396. // Extend the Axis.prototype for dynamic methods
  13397. extend(Axis.prototype, {
  13398. /**
  13399. * Update the axis with a new options structure
  13400. */
  13401. update: function (newOptions, redraw) {
  13402. var chart = this.chart;
  13403. newOptions = chart.options[this.coll][this.options.index] = merge(this.userOptions, newOptions);
  13404. this.destroy(true);
  13405. this._addedPlotLB = UNDEFINED; // #1611, #2887
  13406. this.init(chart, extend(newOptions, { events: UNDEFINED }));
  13407. chart.isDirtyBox = true;
  13408. if (pick(redraw, true)) {
  13409. chart.redraw();
  13410. }
  13411. },
  13412. /**
  13413. * Remove the axis from the chart
  13414. */
  13415. remove: function (redraw) {
  13416. var chart = this.chart,
  13417. key = this.coll, // xAxis or yAxis
  13418. axisSeries = this.series,
  13419. i = axisSeries.length;
  13420. // Remove associated series (#2687)
  13421. while (i--) {
  13422. if (axisSeries[i]) {
  13423. axisSeries[i].remove(false);
  13424. }
  13425. }
  13426. // Remove the axis
  13427. erase(chart.axes, this);
  13428. erase(chart[key], this);
  13429. chart.options[key].splice(this.options.index, 1);
  13430. each(chart[key], function (axis, i) { // Re-index, #1706
  13431. axis.options.index = i;
  13432. });
  13433. this.destroy();
  13434. chart.isDirtyBox = true;
  13435. if (pick(redraw, true)) {
  13436. chart.redraw();
  13437. }
  13438. },
  13439. /**
  13440. * Update the axis title by options
  13441. */
  13442. setTitle: function (newTitleOptions, redraw) {
  13443. this.update({ title: newTitleOptions }, redraw);
  13444. },
  13445. /**
  13446. * Set new axis categories and optionally redraw
  13447. * @param {Array} categories
  13448. * @param {Boolean} redraw
  13449. */
  13450. setCategories: function (categories, redraw) {
  13451. this.update({ categories: categories }, redraw);
  13452. }
  13453. });
  13454. /**
  13455. * LineSeries object
  13456. */
  13457. var LineSeries = extendClass(Series);
  13458. seriesTypes.line = LineSeries;
  13459. /**
  13460. * Set the default options for area
  13461. */
  13462. defaultPlotOptions.area = merge(defaultSeriesOptions, {
  13463. threshold: 0
  13464. // trackByArea: false,
  13465. // lineColor: null, // overrides color, but lets fillColor be unaltered
  13466. // fillOpacity: 0.75,
  13467. // fillColor: null
  13468. });
  13469. /**
  13470. * AreaSeries object
  13471. */
  13472. var AreaSeries = extendClass(Series, {
  13473. type: 'area',
  13474. /**
  13475. * For stacks, don't split segments on null values. Instead, draw null values with
  13476. * no marker. Also insert dummy points for any X position that exists in other series
  13477. * in the stack.
  13478. */
  13479. getSegments: function () {
  13480. var series = this,
  13481. segments = [],
  13482. segment = [],
  13483. keys = [],
  13484. xAxis = this.xAxis,
  13485. yAxis = this.yAxis,
  13486. stack = yAxis.stacks[this.stackKey],
  13487. pointMap = {},
  13488. plotX,
  13489. plotY,
  13490. points = this.points,
  13491. connectNulls = this.options.connectNulls,
  13492. i,
  13493. x;
  13494. if (this.options.stacking && !this.cropped) { // cropped causes artefacts in Stock, and perf issue
  13495. // Create a map where we can quickly look up the points by their X value.
  13496. for (i = 0; i < points.length; i++) {
  13497. pointMap[points[i].x] = points[i];
  13498. }
  13499. // Sort the keys (#1651)
  13500. for (x in stack) {
  13501. if (stack[x].total !== null) { // nulled after switching between grouping and not (#1651, #2336)
  13502. keys.push(+x);
  13503. }
  13504. }
  13505. keys.sort(function (a, b) {
  13506. return a - b;
  13507. });
  13508. each(keys, function (x) {
  13509. var y = 0,
  13510. stackPoint;
  13511. if (connectNulls && (!pointMap[x] || pointMap[x].y === null)) { // #1836
  13512. return;
  13513. // The point exists, push it to the segment
  13514. } else if (pointMap[x]) {
  13515. segment.push(pointMap[x]);
  13516. // There is no point for this X value in this series, so we
  13517. // insert a dummy point in order for the areas to be drawn
  13518. // correctly.
  13519. } else {
  13520. // Loop down the stack to find the series below this one that has
  13521. // a value (#1991)
  13522. for (i = series.index; i <= yAxis.series.length; i++) {
  13523. stackPoint = stack[x].points[i + ',' + x];
  13524. if (stackPoint) {
  13525. y = stackPoint[1];
  13526. break;
  13527. }
  13528. }
  13529. plotX = xAxis.translate(x);
  13530. plotY = yAxis.toPixels(y, true);
  13531. segment.push({
  13532. y: null,
  13533. plotX: plotX,
  13534. clientX: plotX,
  13535. plotY: plotY,
  13536. yBottom: plotY,
  13537. onMouseOver: noop
  13538. });
  13539. }
  13540. });
  13541. if (segment.length) {
  13542. segments.push(segment);
  13543. }
  13544. } else {
  13545. Series.prototype.getSegments.call(this);
  13546. segments = this.segments;
  13547. }
  13548. this.segments = segments;
  13549. },
  13550. /**
  13551. * Extend the base Series getSegmentPath method by adding the path for the area.
  13552. * This path is pushed to the series.areaPath property.
  13553. */
  13554. getSegmentPath: function (segment) {
  13555. var segmentPath = Series.prototype.getSegmentPath.call(this, segment), // call base method
  13556. areaSegmentPath = [].concat(segmentPath), // work on a copy for the area path
  13557. i,
  13558. options = this.options,
  13559. segLength = segmentPath.length,
  13560. translatedThreshold = this.yAxis.getThreshold(options.threshold), // #2181
  13561. yBottom;
  13562. if (segLength === 3) { // for animation from 1 to two points
  13563. areaSegmentPath.push(L, segmentPath[1], segmentPath[2]);
  13564. }
  13565. if (options.stacking && !this.closedStacks) {
  13566. // Follow stack back. Todo: implement areaspline. A general solution could be to
  13567. // reverse the entire graphPath of the previous series, though may be hard with
  13568. // splines and with series with different extremes
  13569. for (i = segment.length - 1; i >= 0; i--) {
  13570. yBottom = pick(segment[i].yBottom, translatedThreshold);
  13571. // step line?
  13572. if (i < segment.length - 1 && options.step) {
  13573. areaSegmentPath.push(segment[i + 1].plotX, yBottom);
  13574. }
  13575. areaSegmentPath.push(segment[i].plotX, yBottom);
  13576. }
  13577. } else { // follow zero line back
  13578. this.closeSegment(areaSegmentPath, segment, translatedThreshold);
  13579. }
  13580. this.areaPath = this.areaPath.concat(areaSegmentPath);
  13581. return segmentPath;
  13582. },
  13583. /**
  13584. * Extendable method to close the segment path of an area. This is overridden in polar
  13585. * charts.
  13586. */
  13587. closeSegment: function (path, segment, translatedThreshold) {
  13588. path.push(
  13589. L,
  13590. segment[segment.length - 1].plotX,
  13591. translatedThreshold,
  13592. L,
  13593. segment[0].plotX,
  13594. translatedThreshold
  13595. );
  13596. },
  13597. /**
  13598. * Draw the graph and the underlying area. This method calls the Series base
  13599. * function and adds the area. The areaPath is calculated in the getSegmentPath
  13600. * method called from Series.prototype.drawGraph.
  13601. */
  13602. drawGraph: function () {
  13603. // Define or reset areaPath
  13604. this.areaPath = [];
  13605. // Call the base method
  13606. Series.prototype.drawGraph.apply(this);
  13607. // Define local variables
  13608. var series = this,
  13609. areaPath = this.areaPath,
  13610. options = this.options,
  13611. zones = this.zones,
  13612. props = [['area', this.color, options.fillColor]]; // area name, main color, fill color
  13613. each(zones, function (threshold, i) {
  13614. props.push(['zoneArea' + i, threshold.color || series.color, threshold.fillColor || options.fillColor]);
  13615. });
  13616. each(props, function (prop) {
  13617. var areaKey = prop[0],
  13618. area = series[areaKey];
  13619. // Create or update the area
  13620. if (area) { // update
  13621. area.animate({ d: areaPath });
  13622. } else { // create
  13623. series[areaKey] = series.chart.renderer.path(areaPath)
  13624. .attr({
  13625. fill: pick(
  13626. prop[2],
  13627. Color(prop[1]).setOpacity(pick(options.fillOpacity, 0.75)).get()
  13628. ),
  13629. zIndex: 0 // #1069
  13630. }).add(series.group);
  13631. }
  13632. });
  13633. },
  13634. drawLegendSymbol: LegendSymbolMixin.drawRectangle
  13635. });
  13636. seriesTypes.area = AreaSeries;
  13637. /**
  13638. * Set the default options for spline
  13639. */
  13640. defaultPlotOptions.spline = merge(defaultSeriesOptions);
  13641. /**
  13642. * SplineSeries object
  13643. */
  13644. var SplineSeries = extendClass(Series, {
  13645. type: 'spline',
  13646. /**
  13647. * Get the spline segment from a given point's previous neighbour to the given point
  13648. */
  13649. getPointSpline: function (segment, point, i) {
  13650. var smoothing = 1.5, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc
  13651. denom = smoothing + 1,
  13652. plotX = point.plotX,
  13653. plotY = point.plotY,
  13654. lastPoint = segment[i - 1],
  13655. nextPoint = segment[i + 1],
  13656. leftContX,
  13657. leftContY,
  13658. rightContX,
  13659. rightContY,
  13660. ret;
  13661. // find control points
  13662. if (lastPoint && nextPoint) {
  13663. var lastX = lastPoint.plotX,
  13664. lastY = lastPoint.plotY,
  13665. nextX = nextPoint.plotX,
  13666. nextY = nextPoint.plotY,
  13667. correction;
  13668. leftContX = (smoothing * plotX + lastX) / denom;
  13669. leftContY = (smoothing * plotY + lastY) / denom;
  13670. rightContX = (smoothing * plotX + nextX) / denom;
  13671. rightContY = (smoothing * plotY + nextY) / denom;
  13672. // have the two control points make a straight line through main point
  13673. correction = ((rightContY - leftContY) * (rightContX - plotX)) /
  13674. (rightContX - leftContX) + plotY - rightContY;
  13675. leftContY += correction;
  13676. rightContY += correction;
  13677. // to prevent false extremes, check that control points are between
  13678. // neighbouring points' y values
  13679. if (leftContY > lastY && leftContY > plotY) {
  13680. leftContY = mathMax(lastY, plotY);
  13681. rightContY = 2 * plotY - leftContY; // mirror of left control point
  13682. } else if (leftContY < lastY && leftContY < plotY) {
  13683. leftContY = mathMin(lastY, plotY);
  13684. rightContY = 2 * plotY - leftContY;
  13685. }
  13686. if (rightContY > nextY && rightContY > plotY) {
  13687. rightContY = mathMax(nextY, plotY);
  13688. leftContY = 2 * plotY - rightContY;
  13689. } else if (rightContY < nextY && rightContY < plotY) {
  13690. rightContY = mathMin(nextY, plotY);
  13691. leftContY = 2 * plotY - rightContY;
  13692. }
  13693. // record for drawing in next point
  13694. point.rightContX = rightContX;
  13695. point.rightContY = rightContY;
  13696. }
  13697. // Visualize control points for debugging
  13698. /*
  13699. if (leftContX) {
  13700. this.chart.renderer.circle(leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 2)
  13701. .attr({
  13702. stroke: 'red',
  13703. 'stroke-width': 1,
  13704. fill: 'none'
  13705. })
  13706. .add();
  13707. this.chart.renderer.path(['M', leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop,
  13708. 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
  13709. .attr({
  13710. stroke: 'red',
  13711. 'stroke-width': 1
  13712. })
  13713. .add();
  13714. this.chart.renderer.circle(rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 2)
  13715. .attr({
  13716. stroke: 'green',
  13717. 'stroke-width': 1,
  13718. fill: 'none'
  13719. })
  13720. .add();
  13721. this.chart.renderer.path(['M', rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop,
  13722. 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
  13723. .attr({
  13724. stroke: 'green',
  13725. 'stroke-width': 1
  13726. })
  13727. .add();
  13728. }
  13729. */
  13730. // moveTo or lineTo
  13731. if (!i) {
  13732. ret = [M, plotX, plotY];
  13733. } else { // curve from last point to this
  13734. ret = [
  13735. 'C',
  13736. lastPoint.rightContX || lastPoint.plotX,
  13737. lastPoint.rightContY || lastPoint.plotY,
  13738. leftContX || plotX,
  13739. leftContY || plotY,
  13740. plotX,
  13741. plotY
  13742. ];
  13743. lastPoint.rightContX = lastPoint.rightContY = null; // reset for updating series later
  13744. }
  13745. return ret;
  13746. }
  13747. });
  13748. seriesTypes.spline = SplineSeries;
  13749. /**
  13750. * Set the default options for areaspline
  13751. */
  13752. defaultPlotOptions.areaspline = merge(defaultPlotOptions.area);
  13753. /**
  13754. * AreaSplineSeries object
  13755. */
  13756. var areaProto = AreaSeries.prototype,
  13757. AreaSplineSeries = extendClass(SplineSeries, {
  13758. type: 'areaspline',
  13759. closedStacks: true, // instead of following the previous graph back, follow the threshold back
  13760. // Mix in methods from the area series
  13761. getSegmentPath: areaProto.getSegmentPath,
  13762. closeSegment: areaProto.closeSegment,
  13763. drawGraph: areaProto.drawGraph,
  13764. drawLegendSymbol: LegendSymbolMixin.drawRectangle
  13765. });
  13766. seriesTypes.areaspline = AreaSplineSeries;
  13767. /**
  13768. * Set the default options for column
  13769. */
  13770. defaultPlotOptions.column = merge(defaultSeriesOptions, {
  13771. borderColor: '#FFFFFF',
  13772. //borderWidth: 1,
  13773. borderRadius: 0,
  13774. //colorByPoint: undefined,
  13775. groupPadding: 0.2,
  13776. //grouping: true,
  13777. marker: null, // point options are specified in the base options
  13778. pointPadding: 0.1,
  13779. //pointWidth: null,
  13780. minPointLength: 0,
  13781. cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes
  13782. pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories
  13783. states: {
  13784. hover: {
  13785. brightness: 0.1,
  13786. shadow: false,
  13787. halo: false
  13788. },
  13789. select: {
  13790. color: '#C0C0C0',
  13791. borderColor: '#000000',
  13792. shadow: false
  13793. }
  13794. },
  13795. dataLabels: {
  13796. align: null, // auto
  13797. verticalAlign: null, // auto
  13798. y: null
  13799. },
  13800. stickyTracking: false,
  13801. tooltip: {
  13802. distance: 6
  13803. },
  13804. threshold: 0
  13805. });
  13806. /**
  13807. * ColumnSeries object
  13808. */
  13809. var ColumnSeries = extendClass(Series, {
  13810. type: 'column',
  13811. pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
  13812. stroke: 'borderColor',
  13813. fill: 'color',
  13814. r: 'borderRadius'
  13815. },
  13816. cropShoulder: 0,
  13817. directTouch: true, // When tooltip is not shared, this series (and derivatives) requires direct touch/hover. KD-tree does not apply.
  13818. trackerGroups: ['group', 'dataLabelsGroup'],
  13819. negStacks: true, // use separate negative stacks, unlike area stacks where a negative
  13820. // point is substracted from previous (#1910)
  13821. /**
  13822. * Initialize the series
  13823. */
  13824. init: function () {
  13825. Series.prototype.init.apply(this, arguments);
  13826. var series = this,
  13827. chart = series.chart;
  13828. // if the series is added dynamically, force redraw of other
  13829. // series affected by a new column
  13830. if (chart.hasRendered) {
  13831. each(chart.series, function (otherSeries) {
  13832. if (otherSeries.type === series.type) {
  13833. otherSeries.isDirty = true;
  13834. }
  13835. });
  13836. }
  13837. },
  13838. /**
  13839. * Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding,
  13840. * pointWidth etc.
  13841. */
  13842. getColumnMetrics: function () {
  13843. var series = this,
  13844. options = series.options,
  13845. xAxis = series.xAxis,
  13846. yAxis = series.yAxis,
  13847. reversedXAxis = xAxis.reversed,
  13848. stackKey,
  13849. stackGroups = {},
  13850. columnIndex,
  13851. columnCount = 0;
  13852. // Get the total number of column type series.
  13853. // This is called on every series. Consider moving this logic to a
  13854. // chart.orderStacks() function and call it on init, addSeries and removeSeries
  13855. if (options.grouping === false) {
  13856. columnCount = 1;
  13857. } else {
  13858. each(series.chart.series, function (otherSeries) {
  13859. var otherOptions = otherSeries.options,
  13860. otherYAxis = otherSeries.yAxis;
  13861. if (otherSeries.type === series.type && otherSeries.visible &&
  13862. yAxis.len === otherYAxis.len && yAxis.pos === otherYAxis.pos) { // #642, #2086
  13863. if (otherOptions.stacking) {
  13864. stackKey = otherSeries.stackKey;
  13865. if (stackGroups[stackKey] === UNDEFINED) {
  13866. stackGroups[stackKey] = columnCount++;
  13867. }
  13868. columnIndex = stackGroups[stackKey];
  13869. } else if (otherOptions.grouping !== false) { // #1162
  13870. columnIndex = columnCount++;
  13871. }
  13872. otherSeries.columnIndex = columnIndex;
  13873. }
  13874. });
  13875. }
  13876. var categoryWidth = mathMin(
  13877. mathAbs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || xAxis.tickInterval || 1), // #2610
  13878. xAxis.len // #1535
  13879. ),
  13880. groupPadding = categoryWidth * options.groupPadding,
  13881. groupWidth = categoryWidth - 2 * groupPadding,
  13882. pointOffsetWidth = groupWidth / columnCount,
  13883. optionPointWidth = options.pointWidth,
  13884. pointPadding = defined(optionPointWidth) ? (pointOffsetWidth - optionPointWidth) / 2 :
  13885. pointOffsetWidth * options.pointPadding,
  13886. pointWidth = pick(optionPointWidth, pointOffsetWidth - 2 * pointPadding), // exact point width, used in polar charts
  13887. colIndex = (reversedXAxis ?
  13888. columnCount - (series.columnIndex || 0) : // #1251
  13889. series.columnIndex) || 0,
  13890. pointXOffset = pointPadding + (groupPadding + colIndex *
  13891. pointOffsetWidth - (categoryWidth / 2)) *
  13892. (reversedXAxis ? -1 : 1);
  13893. // Save it for reading in linked series (Error bars particularly)
  13894. return (series.columnMetrics = {
  13895. width: pointWidth,
  13896. offset: pointXOffset
  13897. });
  13898. },
  13899. /**
  13900. * Translate each point to the plot area coordinate system and find shape positions
  13901. */
  13902. translate: function () {
  13903. var series = this,
  13904. chart = series.chart,
  13905. options = series.options,
  13906. borderWidth = series.borderWidth = pick(
  13907. options.borderWidth,
  13908. series.closestPointRange * series.xAxis.transA < 2 ? 0 : 1 // #3635
  13909. ),
  13910. yAxis = series.yAxis,
  13911. threshold = options.threshold,
  13912. translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold),
  13913. minPointLength = pick(options.minPointLength, 5),
  13914. metrics = series.getColumnMetrics(),
  13915. pointWidth = metrics.width,
  13916. seriesBarW = series.barW = mathMax(pointWidth, 1 + 2 * borderWidth), // postprocessed for border width
  13917. pointXOffset = series.pointXOffset = metrics.offset,
  13918. xCrisp = -(borderWidth % 2 ? 0.5 : 0),
  13919. yCrisp = borderWidth % 2 ? 0.5 : 1;
  13920. if (chart.inverted) {
  13921. translatedThreshold -= 0.5; // #3355
  13922. if (chart.renderer.isVML) {
  13923. yCrisp += 1;
  13924. }
  13925. }
  13926. // When the pointPadding is 0, we want the columns to be packed tightly, so we allow individual
  13927. // columns to have individual sizes. When pointPadding is greater, we strive for equal-width
  13928. // columns (#2694).
  13929. if (options.pointPadding) {
  13930. seriesBarW = mathCeil(seriesBarW);
  13931. }
  13932. Series.prototype.translate.apply(series);
  13933. // Record the new values
  13934. each(series.points, function (point) {
  13935. var yBottom = pick(point.yBottom, translatedThreshold),
  13936. plotY = mathMin(mathMax(-999 - yBottom, point.plotY), yAxis.len + 999 + yBottom), // Don't draw too far outside plot area (#1303, #2241)
  13937. barX = point.plotX + pointXOffset,
  13938. barW = seriesBarW,
  13939. barY = mathMin(plotY, yBottom),
  13940. right,
  13941. bottom,
  13942. fromTop,
  13943. up,
  13944. barH = mathMax(plotY, yBottom) - barY;
  13945. // Handle options.minPointLength
  13946. if (mathAbs(barH) < minPointLength) {
  13947. if (minPointLength) {
  13948. barH = minPointLength;
  13949. up = (!yAxis.reversed && !point.negative) || (yAxis.reversed && point.negative);
  13950. barY =
  13951. mathRound(mathAbs(barY - translatedThreshold) > minPointLength ? // stacked
  13952. yBottom - minPointLength : // keep position
  13953. translatedThreshold - (up ? minPointLength : 0)); // #1485, #4051
  13954. }
  13955. }
  13956. // Cache for access in polar
  13957. point.barX = barX;
  13958. point.pointWidth = pointWidth;
  13959. // Fix the tooltip on center of grouped columns (#1216, #424, #3648)
  13960. point.tooltipPos = chart.inverted ?
  13961. [yAxis.len + yAxis.pos - chart.plotLeft - plotY, series.xAxis.len - barX - barW / 2] :
  13962. [barX + barW / 2, plotY + yAxis.pos - chart.plotTop];
  13963. // Round off to obtain crisp edges and avoid overlapping with neighbours (#2694)
  13964. right = mathRound(barX + barW) + xCrisp;
  13965. barX = mathRound(barX) + xCrisp;
  13966. barW = right - barX;
  13967. fromTop = mathAbs(barY) < 0.5;
  13968. bottom = mathMin(mathRound(barY + barH) + yCrisp, 9e4); // #3575
  13969. barY = mathRound(barY) + yCrisp;
  13970. barH = bottom - barY;
  13971. // Top edges are exceptions
  13972. if (fromTop) {
  13973. barY -= 1;
  13974. barH += 1;
  13975. }
  13976. // Register shape type and arguments to be used in drawPoints
  13977. point.shapeType = 'rect';
  13978. point.shapeArgs = {
  13979. x: barX,
  13980. y: barY,
  13981. width: barW,
  13982. height: barH
  13983. };
  13984. });
  13985. },
  13986. getSymbol: noop,
  13987. /**
  13988. * Use a solid rectangle like the area series types
  13989. */
  13990. drawLegendSymbol: LegendSymbolMixin.drawRectangle,
  13991. /**
  13992. * Columns have no graph
  13993. */
  13994. drawGraph: noop,
  13995. /**
  13996. * Draw the columns. For bars, the series.group is rotated, so the same coordinates
  13997. * apply for columns and bars. This method is inherited by scatter series.
  13998. *
  13999. */
  14000. drawPoints: function () {
  14001. var series = this,
  14002. chart = this.chart,
  14003. options = series.options,
  14004. renderer = chart.renderer,
  14005. animationLimit = options.animationLimit || 250,
  14006. shapeArgs,
  14007. pointAttr;
  14008. // draw the columns
  14009. each(series.points, function (point) {
  14010. var plotY = point.plotY,
  14011. graphic = point.graphic,
  14012. borderAttr;
  14013. if (plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) {
  14014. shapeArgs = point.shapeArgs;
  14015. borderAttr = defined(series.borderWidth) ? {
  14016. 'stroke-width': series.borderWidth
  14017. } : {};
  14018. pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || series.pointAttr[NORMAL_STATE];
  14019. if (graphic) { // update
  14020. stop(graphic);
  14021. graphic.attr(borderAttr)[chart.pointCount < animationLimit ? 'animate' : 'attr'](merge(shapeArgs));
  14022. } else {
  14023. point.graphic = graphic = renderer[point.shapeType](shapeArgs)
  14024. .attr(borderAttr)
  14025. .attr(pointAttr)
  14026. .add(series.group)
  14027. .shadow(options.shadow, null, options.stacking && !options.borderRadius);
  14028. }
  14029. } else if (graphic) {
  14030. point.graphic = graphic.destroy(); // #1269
  14031. }
  14032. });
  14033. },
  14034. /**
  14035. * Animate the column heights one by one from zero
  14036. * @param {Boolean} init Whether to initialize the animation or run it
  14037. */
  14038. animate: function (init) {
  14039. var series = this,
  14040. yAxis = this.yAxis,
  14041. options = series.options,
  14042. inverted = this.chart.inverted,
  14043. attr = {},
  14044. translatedThreshold;
  14045. if (hasSVG) { // VML is too slow anyway
  14046. if (init) {
  14047. attr.scaleY = 0.001;
  14048. translatedThreshold = mathMin(yAxis.pos + yAxis.len, mathMax(yAxis.pos, yAxis.toPixels(options.threshold)));
  14049. if (inverted) {
  14050. attr.translateX = translatedThreshold - yAxis.len;
  14051. } else {
  14052. attr.translateY = translatedThreshold;
  14053. }
  14054. series.group.attr(attr);
  14055. } else { // run the animation
  14056. attr.scaleY = 1;
  14057. attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos;
  14058. series.group.animate(attr, series.options.animation);
  14059. // delete this function to allow it only once
  14060. series.animate = null;
  14061. }
  14062. }
  14063. },
  14064. /**
  14065. * Remove this series from the chart
  14066. */
  14067. remove: function () {
  14068. var series = this,
  14069. chart = series.chart;
  14070. // column and bar series affects other series of the same type
  14071. // as they are either stacked or grouped
  14072. if (chart.hasRendered) {
  14073. each(chart.series, function (otherSeries) {
  14074. if (otherSeries.type === series.type) {
  14075. otherSeries.isDirty = true;
  14076. }
  14077. });
  14078. }
  14079. Series.prototype.remove.apply(series, arguments);
  14080. }
  14081. });
  14082. seriesTypes.column = ColumnSeries;
  14083. /**
  14084. * Set the default options for bar
  14085. */
  14086. defaultPlotOptions.bar = merge(defaultPlotOptions.column);
  14087. /**
  14088. * The Bar series class
  14089. */
  14090. var BarSeries = extendClass(ColumnSeries, {
  14091. type: 'bar',
  14092. inverted: true
  14093. });
  14094. seriesTypes.bar = BarSeries;
  14095. /**
  14096. * Set the default options for scatter
  14097. */
  14098. defaultPlotOptions.scatter = merge(defaultSeriesOptions, {
  14099. lineWidth: 0,
  14100. marker: {
  14101. enabled: true // Overrides auto-enabling in line series (#3647)
  14102. },
  14103. tooltip: {
  14104. headerFormat: '<span style="color:{series.color}">\u25CF</span> <span style="font-size: 10px;"> {series.name}</span><br/>',
  14105. pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>'
  14106. }
  14107. });
  14108. /**
  14109. * The scatter series class
  14110. */
  14111. var ScatterSeries = extendClass(Series, {
  14112. type: 'scatter',
  14113. sorted: false,
  14114. requireSorting: false,
  14115. noSharedTooltip: true,
  14116. trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'],
  14117. takeOrdinalPosition: false, // #2342
  14118. kdDimensions: 2,
  14119. kdComparer: 'distR',
  14120. drawGraph: function () {
  14121. if (this.options.lineWidth) {
  14122. Series.prototype.drawGraph.call(this);
  14123. }
  14124. }
  14125. });
  14126. seriesTypes.scatter = ScatterSeries;
  14127. /**
  14128. * Set the default options for pie
  14129. */
  14130. defaultPlotOptions.pie = merge(defaultSeriesOptions, {
  14131. borderColor: '#FFFFFF',
  14132. borderWidth: 1,
  14133. center: [null, null],
  14134. clip: false,
  14135. colorByPoint: true, // always true for pies
  14136. dataLabels: {
  14137. // align: null,
  14138. // connectorWidth: 1,
  14139. // connectorColor: point.color,
  14140. // connectorPadding: 5,
  14141. distance: 30,
  14142. enabled: true,
  14143. formatter: function () { // #2945
  14144. return this.point.name;
  14145. },
  14146. // softConnector: true,
  14147. x: 0
  14148. // y: 0
  14149. },
  14150. ignoreHiddenPoint: true,
  14151. //innerSize: 0,
  14152. legendType: 'point',
  14153. marker: null, // point options are specified in the base options
  14154. size: null,
  14155. showInLegend: false,
  14156. slicedOffset: 10,
  14157. states: {
  14158. hover: {
  14159. brightness: 0.1,
  14160. shadow: false
  14161. }
  14162. },
  14163. stickyTracking: false,
  14164. tooltip: {
  14165. followPointer: true
  14166. }
  14167. });
  14168. /**
  14169. * Extended point object for pies
  14170. */
  14171. var PiePoint = extendClass(Point, {
  14172. /**
  14173. * Initiate the pie slice
  14174. */
  14175. init: function () {
  14176. Point.prototype.init.apply(this, arguments);
  14177. var point = this,
  14178. toggleSlice;
  14179. extend(point, {
  14180. visible: point.visible !== false,
  14181. name: pick(point.name, 'Slice')
  14182. });
  14183. // add event listener for select
  14184. toggleSlice = function (e) {
  14185. point.slice(e.type === 'select');
  14186. };
  14187. addEvent(point, 'select', toggleSlice);
  14188. addEvent(point, 'unselect', toggleSlice);
  14189. return point;
  14190. },
  14191. /**
  14192. * Toggle the visibility of the pie slice
  14193. * @param {Boolean} vis Whether to show the slice or not. If undefined, the
  14194. * visibility is toggled
  14195. */
  14196. setVisible: function (vis, force) {
  14197. var point = this,
  14198. series = point.series,
  14199. chart = series.chart,
  14200. doRedraw = !series.isDirty && series.options.ignoreHiddenPoint;
  14201. // Only if the value has changed
  14202. if (vis !== point.visible || force) {
  14203. // If called without an argument, toggle visibility
  14204. point.visible = point.options.visible = vis = vis === UNDEFINED ? !point.visible : vis;
  14205. series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data
  14206. // Show and hide associated elements
  14207. each(['graphic', 'dataLabel', 'connector', 'shadowGroup'], function (key) {
  14208. if (point[key]) {
  14209. point[key][vis ? 'show' : 'hide'](true);
  14210. }
  14211. });
  14212. if (point.legendItem) {
  14213. if (chart.hasRendered) {
  14214. series.updateTotals();
  14215. chart.legend.clearItems();
  14216. if (!doRedraw) {
  14217. chart.legend.render();
  14218. }
  14219. }
  14220. chart.legend.colorizeItem(point, vis);
  14221. }
  14222. // Handle ignore hidden slices
  14223. if (doRedraw) {
  14224. series.isDirty = true;
  14225. chart.redraw();
  14226. }
  14227. }
  14228. },
  14229. /**
  14230. * Set or toggle whether the slice is cut out from the pie
  14231. * @param {Boolean} sliced When undefined, the slice state is toggled
  14232. * @param {Boolean} redraw Whether to redraw the chart. True by default.
  14233. */
  14234. slice: function (sliced, redraw, animation) {
  14235. var point = this,
  14236. series = point.series,
  14237. chart = series.chart,
  14238. translation;
  14239. setAnimation(animation, chart);
  14240. // redraw is true by default
  14241. redraw = pick(redraw, true);
  14242. // if called without an argument, toggle
  14243. point.sliced = point.options.sliced = sliced = defined(sliced) ? sliced : !point.sliced;
  14244. series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data
  14245. translation = sliced ? point.slicedTranslation : {
  14246. translateX: 0,
  14247. translateY: 0
  14248. };
  14249. point.graphic.animate(translation);
  14250. if (point.shadowGroup) {
  14251. point.shadowGroup.animate(translation);
  14252. }
  14253. },
  14254. haloPath: function (size) {
  14255. var shapeArgs = this.shapeArgs,
  14256. chart = this.series.chart;
  14257. return this.sliced || !this.visible ? [] : this.series.chart.renderer.symbols.arc(chart.plotLeft + shapeArgs.x, chart.plotTop + shapeArgs.y, shapeArgs.r + size, shapeArgs.r + size, {
  14258. innerR: this.shapeArgs.r,
  14259. start: shapeArgs.start,
  14260. end: shapeArgs.end
  14261. });
  14262. }
  14263. });
  14264. /**
  14265. * The Pie series class
  14266. */
  14267. var PieSeries = {
  14268. type: 'pie',
  14269. isCartesian: false,
  14270. pointClass: PiePoint,
  14271. requireSorting: false,
  14272. noSharedTooltip: true,
  14273. trackerGroups: ['group', 'dataLabelsGroup'],
  14274. axisTypes: [],
  14275. pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
  14276. stroke: 'borderColor',
  14277. 'stroke-width': 'borderWidth',
  14278. fill: 'color'
  14279. },
  14280. /**
  14281. * Pies have one color each point
  14282. */
  14283. getColor: noop,
  14284. /**
  14285. * Animate the pies in
  14286. */
  14287. animate: function (init) {
  14288. var series = this,
  14289. points = series.points,
  14290. startAngleRad = series.startAngleRad;
  14291. if (!init) {
  14292. each(points, function (point) {
  14293. var graphic = point.graphic,
  14294. args = point.shapeArgs;
  14295. if (graphic) {
  14296. // start values
  14297. graphic.attr({
  14298. r: point.startR || (series.center[3] / 2), // animate from inner radius (#779)
  14299. start: startAngleRad,
  14300. end: startAngleRad
  14301. });
  14302. // animate
  14303. graphic.animate({
  14304. r: args.r,
  14305. start: args.start,
  14306. end: args.end
  14307. }, series.options.animation);
  14308. }
  14309. });
  14310. // delete this function to allow it only once
  14311. series.animate = null;
  14312. }
  14313. },
  14314. /**
  14315. * Extend the basic setData method by running processData and generatePoints immediately,
  14316. * in order to access the points from the legend.
  14317. */
  14318. setData: function (data, redraw, animation, updatePoints) {
  14319. Series.prototype.setData.call(this, data, false, animation, updatePoints);
  14320. this.processData();
  14321. this.generatePoints();
  14322. if (pick(redraw, true)) {
  14323. this.chart.redraw(animation);
  14324. }
  14325. },
  14326. /**
  14327. * Recompute total chart sum and update percentages of points.
  14328. */
  14329. updateTotals: function () {
  14330. var i,
  14331. total = 0,
  14332. points,
  14333. len,
  14334. point,
  14335. ignoreHiddenPoint = this.options.ignoreHiddenPoint;
  14336. // Populate local vars
  14337. points = this.points;
  14338. len = points.length;
  14339. // Get the total sum
  14340. for (i = 0; i < len; i++) {
  14341. point = points[i];
  14342. // Disallow negative values (#1530, #3623)
  14343. if (point.y < 0) {
  14344. point.y = null;
  14345. }
  14346. total += (ignoreHiddenPoint && !point.visible) ? 0 : point.y;
  14347. }
  14348. this.total = total;
  14349. // Set each point's properties
  14350. for (i = 0; i < len; i++) {
  14351. point = points[i];
  14352. //point.percentage = (total <= 0 || ignoreHiddenPoint && !point.visible) ? 0 : point.y / total * 100;
  14353. point.percentage = (total > 0 && (point.visible || !ignoreHiddenPoint)) ? point.y / total * 100 : 0;
  14354. point.total = total;
  14355. }
  14356. },
  14357. /**
  14358. * Extend the generatePoints method by adding total and percentage properties to each point
  14359. */
  14360. generatePoints: function () {
  14361. Series.prototype.generatePoints.call(this);
  14362. this.updateTotals();
  14363. },
  14364. /**
  14365. * Do translation for pie slices
  14366. */
  14367. translate: function (positions) {
  14368. this.generatePoints();
  14369. var series = this,
  14370. cumulative = 0,
  14371. precision = 1000, // issue #172
  14372. options = series.options,
  14373. slicedOffset = options.slicedOffset,
  14374. connectorOffset = slicedOffset + options.borderWidth,
  14375. start,
  14376. end,
  14377. angle,
  14378. startAngle = options.startAngle || 0,
  14379. startAngleRad = series.startAngleRad = mathPI / 180 * (startAngle - 90),
  14380. endAngleRad = series.endAngleRad = mathPI / 180 * ((pick(options.endAngle, startAngle + 360)) - 90),
  14381. circ = endAngleRad - startAngleRad, //2 * mathPI,
  14382. points = series.points,
  14383. radiusX, // the x component of the radius vector for a given point
  14384. radiusY,
  14385. labelDistance = options.dataLabels.distance,
  14386. ignoreHiddenPoint = options.ignoreHiddenPoint,
  14387. i,
  14388. len = points.length,
  14389. point;
  14390. // Get positions - either an integer or a percentage string must be given.
  14391. // If positions are passed as a parameter, we're in a recursive loop for adjusting
  14392. // space for data labels.
  14393. if (!positions) {
  14394. series.center = positions = series.getCenter();
  14395. }
  14396. // utility for getting the x value from a given y, used for anticollision logic in data labels
  14397. series.getX = function (y, left) {
  14398. angle = math.asin(mathMin((y - positions[1]) / (positions[2] / 2 + labelDistance), 1));
  14399. return positions[0] +
  14400. (left ? -1 : 1) *
  14401. (mathCos(angle) * (positions[2] / 2 + labelDistance));
  14402. };
  14403. // Calculate the geometry for each point
  14404. for (i = 0; i < len; i++) {
  14405. point = points[i];
  14406. // set start and end angle
  14407. start = startAngleRad + (cumulative * circ);
  14408. if (!ignoreHiddenPoint || point.visible) {
  14409. cumulative += point.percentage / 100;
  14410. }
  14411. end = startAngleRad + (cumulative * circ);
  14412. // set the shape
  14413. point.shapeType = 'arc';
  14414. point.shapeArgs = {
  14415. x: positions[0],
  14416. y: positions[1],
  14417. r: positions[2] / 2,
  14418. innerR: positions[3] / 2,
  14419. start: mathRound(start * precision) / precision,
  14420. end: mathRound(end * precision) / precision
  14421. };
  14422. // The angle must stay within -90 and 270 (#2645)
  14423. angle = (end + start) / 2;
  14424. if (angle > 1.5 * mathPI) {
  14425. angle -= 2 * mathPI;
  14426. } else if (angle < -mathPI / 2) {
  14427. angle += 2 * mathPI;
  14428. }
  14429. // Center for the sliced out slice
  14430. point.slicedTranslation = {
  14431. translateX: mathRound(mathCos(angle) * slicedOffset),
  14432. translateY: mathRound(mathSin(angle) * slicedOffset)
  14433. };
  14434. // set the anchor point for tooltips
  14435. radiusX = mathCos(angle) * positions[2] / 2;
  14436. radiusY = mathSin(angle) * positions[2] / 2;
  14437. point.tooltipPos = [
  14438. positions[0] + radiusX * 0.7,
  14439. positions[1] + radiusY * 0.7
  14440. ];
  14441. point.half = angle < -mathPI / 2 || angle > mathPI / 2 ? 1 : 0;
  14442. point.angle = angle;
  14443. // set the anchor point for data labels
  14444. connectorOffset = mathMin(connectorOffset, labelDistance / 2); // #1678
  14445. point.labelPos = [
  14446. positions[0] + radiusX + mathCos(angle) * labelDistance, // first break of connector
  14447. positions[1] + radiusY + mathSin(angle) * labelDistance, // a/a
  14448. positions[0] + radiusX + mathCos(angle) * connectorOffset, // second break, right outside pie
  14449. positions[1] + radiusY + mathSin(angle) * connectorOffset, // a/a
  14450. positions[0] + radiusX, // landing point for connector
  14451. positions[1] + radiusY, // a/a
  14452. labelDistance < 0 ? // alignment
  14453. 'center' :
  14454. point.half ? 'right' : 'left', // alignment
  14455. angle // center angle
  14456. ];
  14457. }
  14458. },
  14459. drawGraph: null,
  14460. /**
  14461. * Draw the data points
  14462. */
  14463. drawPoints: function () {
  14464. var series = this,
  14465. chart = series.chart,
  14466. renderer = chart.renderer,
  14467. groupTranslation,
  14468. //center,
  14469. graphic,
  14470. //group,
  14471. shadow = series.options.shadow,
  14472. shadowGroup,
  14473. shapeArgs;
  14474. if (shadow && !series.shadowGroup) {
  14475. series.shadowGroup = renderer.g('shadow')
  14476. .add(series.group);
  14477. }
  14478. // draw the slices
  14479. each(series.points, function (point) {
  14480. var visible = point.options.visible;
  14481. graphic = point.graphic;
  14482. shapeArgs = point.shapeArgs;
  14483. shadowGroup = point.shadowGroup;
  14484. // put the shadow behind all points
  14485. if (shadow && !shadowGroup) {
  14486. shadowGroup = point.shadowGroup = renderer.g('shadow')
  14487. .add(series.shadowGroup);
  14488. }
  14489. // if the point is sliced, use special translation, else use plot area traslation
  14490. groupTranslation = point.sliced ? point.slicedTranslation : {
  14491. translateX: 0,
  14492. translateY: 0
  14493. };
  14494. //group.translate(groupTranslation[0], groupTranslation[1]);
  14495. if (shadowGroup) {
  14496. shadowGroup.attr(groupTranslation);
  14497. }
  14498. // draw the slice
  14499. if (graphic) {
  14500. graphic.animate(extend(shapeArgs, groupTranslation));
  14501. } else {
  14502. point.graphic = graphic = renderer[point.shapeType](shapeArgs)
  14503. .setRadialReference(series.center)
  14504. .attr(
  14505. point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE]
  14506. )
  14507. .attr({
  14508. 'stroke-linejoin': 'round'
  14509. //zIndex: 1 // #2722 (reversed)
  14510. })
  14511. .attr(groupTranslation)
  14512. .add(series.group)
  14513. .shadow(shadow, shadowGroup);
  14514. }
  14515. // Detect point specific visibility (#2430)
  14516. if (visible !== undefined) {
  14517. point.setVisible(visible, true);
  14518. }
  14519. });
  14520. },
  14521. searchPoint: noop,
  14522. /**
  14523. * Utility for sorting data labels
  14524. */
  14525. sortByAngle: function (points, sign) {
  14526. points.sort(function (a, b) {
  14527. return a.angle !== undefined && (b.angle - a.angle) * sign;
  14528. });
  14529. },
  14530. /**
  14531. * Use a simple symbol from LegendSymbolMixin
  14532. */
  14533. drawLegendSymbol: LegendSymbolMixin.drawRectangle,
  14534. /**
  14535. * Use the getCenter method from drawLegendSymbol
  14536. */
  14537. getCenter: CenteredSeriesMixin.getCenter,
  14538. /**
  14539. * Pies don't have point marker symbols
  14540. */
  14541. getSymbol: noop
  14542. };
  14543. PieSeries = extendClass(Series, PieSeries);
  14544. seriesTypes.pie = PieSeries;
  14545. /**
  14546. * Draw the data labels
  14547. */
  14548. Series.prototype.drawDataLabels = function () {
  14549. var series = this,
  14550. seriesOptions = series.options,
  14551. cursor = seriesOptions.cursor,
  14552. options = seriesOptions.dataLabels,
  14553. points = series.points,
  14554. pointOptions,
  14555. generalOptions,
  14556. hasRendered = series.hasRendered || 0,
  14557. str,
  14558. dataLabelsGroup,
  14559. renderer = series.chart.renderer;
  14560. if (options.enabled || series._hasPointLabels) {
  14561. // Process default alignment of data labels for columns
  14562. if (series.dlProcessOptions) {
  14563. series.dlProcessOptions(options);
  14564. }
  14565. // Create a separate group for the data labels to avoid rotation
  14566. dataLabelsGroup = series.plotGroup(
  14567. 'dataLabelsGroup',
  14568. 'data-labels',
  14569. options.defer ? HIDDEN : VISIBLE,
  14570. options.zIndex || 6
  14571. );
  14572. if (pick(options.defer, true)) {
  14573. dataLabelsGroup.attr({ opacity: +hasRendered }); // #3300
  14574. if (!hasRendered) {
  14575. addEvent(series, 'afterAnimate', function () {
  14576. if (series.visible) { // #3023, #3024
  14577. dataLabelsGroup.show();
  14578. }
  14579. dataLabelsGroup[seriesOptions.animation ? 'animate' : 'attr']({ opacity: 1 }, { duration: 200 });
  14580. });
  14581. }
  14582. }
  14583. // Make the labels for each point
  14584. generalOptions = options;
  14585. each(points, function (point) {
  14586. var enabled,
  14587. dataLabel = point.dataLabel,
  14588. labelConfig,
  14589. attr,
  14590. name,
  14591. rotation,
  14592. connector = point.connector,
  14593. isNew = true,
  14594. style,
  14595. moreStyle = {};
  14596. // Determine if each data label is enabled
  14597. pointOptions = point.dlOptions || (point.options && point.options.dataLabels); // dlOptions is used in treemaps
  14598. enabled = pick(pointOptions && pointOptions.enabled, generalOptions.enabled); // #2282
  14599. // If the point is outside the plot area, destroy it. #678, #820
  14600. if (dataLabel && !enabled) {
  14601. point.dataLabel = dataLabel.destroy();
  14602. // Individual labels are disabled if the are explicitly disabled
  14603. // in the point options, or if they fall outside the plot area.
  14604. } else if (enabled) {
  14605. // Create individual options structure that can be extended without
  14606. // affecting others
  14607. options = merge(generalOptions, pointOptions);
  14608. style = options.style;
  14609. rotation = options.rotation;
  14610. // Get the string
  14611. labelConfig = point.getLabelConfig();
  14612. str = options.format ?
  14613. format(options.format, labelConfig) :
  14614. options.formatter.call(labelConfig, options);
  14615. // Determine the color
  14616. style.color = pick(options.color, style.color, series.color, 'black');
  14617. // update existing label
  14618. if (dataLabel) {
  14619. if (defined(str)) {
  14620. dataLabel
  14621. .attr({
  14622. text: str
  14623. });
  14624. isNew = false;
  14625. } else { // #1437 - the label is shown conditionally
  14626. point.dataLabel = dataLabel = dataLabel.destroy();
  14627. if (connector) {
  14628. point.connector = connector.destroy();
  14629. }
  14630. }
  14631. // create new label
  14632. } else if (defined(str)) {
  14633. attr = {
  14634. //align: align,
  14635. fill: options.backgroundColor,
  14636. stroke: options.borderColor,
  14637. 'stroke-width': options.borderWidth,
  14638. r: options.borderRadius || 0,
  14639. rotation: rotation,
  14640. padding: options.padding,
  14641. zIndex: 1
  14642. };
  14643. // Get automated contrast color
  14644. if (style.color === 'contrast') {
  14645. moreStyle.color = options.inside || options.distance < 0 || !!seriesOptions.stacking ?
  14646. renderer.getContrast(point.color || series.color) :
  14647. '#000000';
  14648. }
  14649. if (cursor) {
  14650. moreStyle.cursor = cursor;
  14651. }
  14652. // Remove unused attributes (#947)
  14653. for (name in attr) {
  14654. if (attr[name] === UNDEFINED) {
  14655. delete attr[name];
  14656. }
  14657. }
  14658. dataLabel = point.dataLabel = renderer[rotation ? 'text' : 'label']( // labels don't support rotation
  14659. str,
  14660. 0,
  14661. -999,
  14662. options.shape,
  14663. null,
  14664. null,
  14665. options.useHTML
  14666. )
  14667. .attr(attr)
  14668. .css(extend(style, moreStyle))
  14669. .add(dataLabelsGroup)
  14670. .shadow(options.shadow);
  14671. }
  14672. if (dataLabel) {
  14673. // Now the data label is created and placed at 0,0, so we need to align it
  14674. series.alignDataLabel(point, dataLabel, options, null, isNew);
  14675. }
  14676. }
  14677. });
  14678. }
  14679. };
  14680. /**
  14681. * Align each individual data label
  14682. */
  14683. Series.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) {
  14684. var chart = this.chart,
  14685. inverted = chart.inverted,
  14686. plotX = pick(point.plotX, -999),
  14687. plotY = pick(point.plotY, -999),
  14688. bBox = dataLabel.getBBox(),
  14689. baseline = chart.renderer.fontMetrics(options.style.fontSize).b,
  14690. rotCorr, // rotation correction
  14691. // Math.round for rounding errors (#2683), alignTo to allow column labels (#2700)
  14692. visible = this.visible && (point.series.forceDL || chart.isInsidePlot(plotX, mathRound(plotY), inverted) ||
  14693. (alignTo && chart.isInsidePlot(plotX, inverted ? alignTo.x + 1 : alignTo.y + alignTo.height - 1, inverted))),
  14694. alignAttr; // the final position;
  14695. if (visible) {
  14696. // The alignment box is a singular point
  14697. alignTo = extend({
  14698. x: inverted ? chart.plotWidth - plotY : plotX,
  14699. y: mathRound(inverted ? chart.plotHeight - plotX : plotY),
  14700. width: 0,
  14701. height: 0
  14702. }, alignTo);
  14703. // Add the text size for alignment calculation
  14704. extend(options, {
  14705. width: bBox.width,
  14706. height: bBox.height
  14707. });
  14708. // Allow a hook for changing alignment in the last moment, then do the alignment
  14709. if (options.rotation) { // Fancy box alignment isn't supported for rotated text
  14710. rotCorr = chart.renderer.rotCorr(baseline, options.rotation); // #3723
  14711. dataLabel[isNew ? 'attr' : 'animate']({
  14712. x: alignTo.x + options.x + alignTo.width / 2 + rotCorr.x,
  14713. y: alignTo.y + options.y + alignTo.height / 2
  14714. })
  14715. .attr({ // #3003
  14716. align: options.align
  14717. });
  14718. } else {
  14719. dataLabel.align(options, null, alignTo);
  14720. alignAttr = dataLabel.alignAttr;
  14721. // Handle justify or crop
  14722. if (pick(options.overflow, 'justify') === 'justify') {
  14723. this.justifyDataLabel(dataLabel, options, alignAttr, bBox, alignTo, isNew);
  14724. } else if (pick(options.crop, true)) {
  14725. // Now check that the data label is within the plot area
  14726. visible = chart.isInsidePlot(alignAttr.x, alignAttr.y) && chart.isInsidePlot(alignAttr.x + bBox.width, alignAttr.y + bBox.height);
  14727. }
  14728. // When we're using a shape, make it possible with a connector or an arrow pointing to thie point
  14729. if (options.shape) {
  14730. dataLabel.attr({
  14731. anchorX: point.plotX,
  14732. anchorY: point.plotY
  14733. });
  14734. }
  14735. }
  14736. }
  14737. // Show or hide based on the final aligned position
  14738. if (!visible) {
  14739. dataLabel.attr({ y: -999 });
  14740. dataLabel.placed = false; // don't animate back in
  14741. }
  14742. };
  14743. /**
  14744. * If data labels fall partly outside the plot area, align them back in, in a way that
  14745. * doesn't hide the point.
  14746. */
  14747. Series.prototype.justifyDataLabel = function (dataLabel, options, alignAttr, bBox, alignTo, isNew) {
  14748. var chart = this.chart,
  14749. align = options.align,
  14750. verticalAlign = options.verticalAlign,
  14751. off,
  14752. justified,
  14753. padding = dataLabel.box ? 0 : (dataLabel.padding || 0);
  14754. // Off left
  14755. off = alignAttr.x + padding;
  14756. if (off < 0) {
  14757. if (align === 'right') {
  14758. options.align = 'left';
  14759. } else {
  14760. options.x = -off;
  14761. }
  14762. justified = true;
  14763. }
  14764. // Off right
  14765. off = alignAttr.x + bBox.width - padding;
  14766. if (off > chart.plotWidth) {
  14767. if (align === 'left') {
  14768. options.align = 'right';
  14769. } else {
  14770. options.x = chart.plotWidth - off;
  14771. }
  14772. justified = true;
  14773. }
  14774. // Off top
  14775. off = alignAttr.y + padding;
  14776. if (off < 0) {
  14777. if (verticalAlign === 'bottom') {
  14778. options.verticalAlign = 'top';
  14779. } else {
  14780. options.y = -off;
  14781. }
  14782. justified = true;
  14783. }
  14784. // Off bottom
  14785. off = alignAttr.y + bBox.height - padding;
  14786. if (off > chart.plotHeight) {
  14787. if (verticalAlign === 'top') {
  14788. options.verticalAlign = 'bottom';
  14789. } else {
  14790. options.y = chart.plotHeight - off;
  14791. }
  14792. justified = true;
  14793. }
  14794. if (justified) {
  14795. dataLabel.placed = !isNew;
  14796. dataLabel.align(options, null, alignTo);
  14797. }
  14798. };
  14799. /**
  14800. * Override the base drawDataLabels method by pie specific functionality
  14801. */
  14802. if (seriesTypes.pie) {
  14803. seriesTypes.pie.prototype.drawDataLabels = function () {
  14804. var series = this,
  14805. data = series.data,
  14806. point,
  14807. chart = series.chart,
  14808. options = series.options.dataLabels,
  14809. connectorPadding = pick(options.connectorPadding, 10),
  14810. connectorWidth = pick(options.connectorWidth, 1),
  14811. plotWidth = chart.plotWidth,
  14812. plotHeight = chart.plotHeight,
  14813. connector,
  14814. connectorPath,
  14815. softConnector = pick(options.softConnector, true),
  14816. distanceOption = options.distance,
  14817. seriesCenter = series.center,
  14818. radius = seriesCenter[2] / 2,
  14819. centerY = seriesCenter[1],
  14820. outside = distanceOption > 0,
  14821. dataLabel,
  14822. dataLabelWidth,
  14823. labelPos,
  14824. labelHeight,
  14825. halves = [// divide the points into right and left halves for anti collision
  14826. [], // right
  14827. [] // left
  14828. ],
  14829. x,
  14830. y,
  14831. visibility,
  14832. rankArr,
  14833. i,
  14834. j,
  14835. overflow = [0, 0, 0, 0], // top, right, bottom, left
  14836. sort = function (a, b) {
  14837. return b.y - a.y;
  14838. };
  14839. // get out if not enabled
  14840. if (!series.visible || (!options.enabled && !series._hasPointLabels)) {
  14841. return;
  14842. }
  14843. // run parent method
  14844. Series.prototype.drawDataLabels.apply(series);
  14845. // arrange points for detection collision
  14846. each(data, function (point) {
  14847. if (point.dataLabel && point.visible) { // #407, #2510
  14848. halves[point.half].push(point);
  14849. }
  14850. });
  14851. /* Loop over the points in each half, starting from the top and bottom
  14852. * of the pie to detect overlapping labels.
  14853. */
  14854. i = 2;
  14855. while (i--) {
  14856. var slots = [],
  14857. slotsLength,
  14858. usedSlots = [],
  14859. points = halves[i],
  14860. pos,
  14861. bottom,
  14862. length = points.length,
  14863. slotIndex;
  14864. if (!length) {
  14865. continue;
  14866. }
  14867. // Sort by angle
  14868. series.sortByAngle(points, i - 0.5);
  14869. // Assume equal label heights on either hemisphere (#2630)
  14870. j = labelHeight = 0;
  14871. while (!labelHeight && points[j]) { // #1569
  14872. labelHeight = points[j] && points[j].dataLabel && (points[j].dataLabel.getBBox().height || 21); // 21 is for #968
  14873. j++;
  14874. }
  14875. // Only do anti-collision when we are outside the pie and have connectors (#856)
  14876. if (distanceOption > 0) {
  14877. // Build the slots
  14878. bottom = mathMin(centerY + radius + distanceOption, chart.plotHeight);
  14879. for (pos = mathMax(0, centerY - radius - distanceOption); pos <= bottom; pos += labelHeight) {
  14880. slots.push(pos);
  14881. }
  14882. slotsLength = slots.length;
  14883. /* Visualize the slots
  14884. if (!series.slotElements) {
  14885. series.slotElements = [];
  14886. }
  14887. if (i === 1) {
  14888. series.slotElements.forEach(function (elem) {
  14889. elem.destroy();
  14890. });
  14891. series.slotElements.length = 0;
  14892. }
  14893. slots.forEach(function (pos, no) {
  14894. var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0),
  14895. slotY = pos + chart.plotTop;
  14896. if (!isNaN(slotX)) {
  14897. series.slotElements.push(chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1)
  14898. .attr({
  14899. 'stroke-width': 1,
  14900. stroke: 'silver',
  14901. fill: 'rgba(0,0,255,0.1)'
  14902. })
  14903. .add());
  14904. series.slotElements.push(chart.renderer.text('Slot '+ no, slotX, slotY + 4)
  14905. .attr({
  14906. fill: 'silver'
  14907. }).add());
  14908. }
  14909. });
  14910. // */
  14911. // if there are more values than available slots, remove lowest values
  14912. if (length > slotsLength) {
  14913. // create an array for sorting and ranking the points within each quarter
  14914. rankArr = [].concat(points);
  14915. rankArr.sort(sort);
  14916. j = length;
  14917. while (j--) {
  14918. rankArr[j].rank = j;
  14919. }
  14920. j = length;
  14921. while (j--) {
  14922. if (points[j].rank >= slotsLength) {
  14923. points.splice(j, 1);
  14924. }
  14925. }
  14926. length = points.length;
  14927. }
  14928. // The label goes to the nearest open slot, but not closer to the edge than
  14929. // the label's index.
  14930. for (j = 0; j < length; j++) {
  14931. point = points[j];
  14932. labelPos = point.labelPos;
  14933. var closest = 9999,
  14934. distance,
  14935. slotI;
  14936. // find the closest slot index
  14937. for (slotI = 0; slotI < slotsLength; slotI++) {
  14938. distance = mathAbs(slots[slotI] - labelPos[1]);
  14939. if (distance < closest) {
  14940. closest = distance;
  14941. slotIndex = slotI;
  14942. }
  14943. }
  14944. // if that slot index is closer to the edges of the slots, move it
  14945. // to the closest appropriate slot
  14946. if (slotIndex < j && slots[j] !== null) { // cluster at the top
  14947. slotIndex = j;
  14948. } else if (slotsLength < length - j + slotIndex && slots[j] !== null) { // cluster at the bottom
  14949. slotIndex = slotsLength - length + j;
  14950. while (slots[slotIndex] === null) { // make sure it is not taken
  14951. slotIndex++;
  14952. }
  14953. } else {
  14954. // Slot is taken, find next free slot below. In the next run, the next slice will find the
  14955. // slot above these, because it is the closest one
  14956. while (slots[slotIndex] === null) { // make sure it is not taken
  14957. slotIndex++;
  14958. }
  14959. }
  14960. usedSlots.push({ i: slotIndex, y: slots[slotIndex] });
  14961. slots[slotIndex] = null; // mark as taken
  14962. }
  14963. // sort them in order to fill in from the top
  14964. usedSlots.sort(sort);
  14965. }
  14966. // now the used slots are sorted, fill them up sequentially
  14967. for (j = 0; j < length; j++) {
  14968. var slot, naturalY;
  14969. point = points[j];
  14970. labelPos = point.labelPos;
  14971. dataLabel = point.dataLabel;
  14972. visibility = point.visible === false ? HIDDEN : 'inherit';
  14973. naturalY = labelPos[1];
  14974. if (distanceOption > 0) {
  14975. slot = usedSlots.pop();
  14976. slotIndex = slot.i;
  14977. // if the slot next to currrent slot is free, the y value is allowed
  14978. // to fall back to the natural position
  14979. y = slot.y;
  14980. if ((naturalY > y && slots[slotIndex + 1] !== null) ||
  14981. (naturalY < y && slots[slotIndex - 1] !== null)) {
  14982. y = mathMin(mathMax(0, naturalY), chart.plotHeight);
  14983. }
  14984. } else {
  14985. y = naturalY;
  14986. }
  14987. // get the x - use the natural x position for first and last slot, to prevent the top
  14988. // and botton slice connectors from touching each other on either side
  14989. // Problem: Should check that it makes sense - http://jsfiddle.net/highcharts/n1y6ngxz/
  14990. x = options.justify ?
  14991. seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption) :
  14992. series.getX(y === centerY - radius - distanceOption || y === centerY + radius + distanceOption ? naturalY : y, i);
  14993. // Record the placement and visibility
  14994. dataLabel._attr = {
  14995. visibility: visibility,
  14996. align: labelPos[6]
  14997. };
  14998. dataLabel._pos = {
  14999. x: x + options.x +
  15000. ({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0),
  15001. y: y + options.y - 10 // 10 is for the baseline (label vs text)
  15002. };
  15003. dataLabel.connX = x;
  15004. dataLabel.connY = y;
  15005. // Detect overflowing data labels
  15006. if (this.options.size === null) {
  15007. dataLabelWidth = dataLabel.width;
  15008. // Overflow left
  15009. if (x - dataLabelWidth < connectorPadding) {
  15010. overflow[3] = mathMax(mathRound(dataLabelWidth - x + connectorPadding), overflow[3]);
  15011. // Overflow right
  15012. } else if (x + dataLabelWidth > plotWidth - connectorPadding) {
  15013. overflow[1] = mathMax(mathRound(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]);
  15014. }
  15015. // Overflow top
  15016. if (y - labelHeight / 2 < 0) {
  15017. overflow[0] = mathMax(mathRound(-y + labelHeight / 2), overflow[0]);
  15018. // Overflow left
  15019. } else if (y + labelHeight / 2 > plotHeight) {
  15020. overflow[2] = mathMax(mathRound(y + labelHeight / 2 - plotHeight), overflow[2]);
  15021. }
  15022. }
  15023. } // for each point
  15024. } // for each half
  15025. // Do not apply the final placement and draw the connectors until we have verified
  15026. // that labels are not spilling over.
  15027. if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) {
  15028. // Place the labels in the final position
  15029. this.placeDataLabels();
  15030. // Draw the connectors
  15031. if (outside && connectorWidth) {
  15032. each(this.points, function (point) {
  15033. connector = point.connector;
  15034. labelPos = point.labelPos;
  15035. dataLabel = point.dataLabel;
  15036. if (dataLabel && dataLabel._pos) {
  15037. visibility = dataLabel._attr.visibility;
  15038. x = dataLabel.connX;
  15039. y = dataLabel.connY;
  15040. connectorPath = softConnector ? [
  15041. M,
  15042. x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
  15043. 'C',
  15044. x, y, // first break, next to the label
  15045. 2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5],
  15046. labelPos[2], labelPos[3], // second break
  15047. L,
  15048. labelPos[4], labelPos[5] // base
  15049. ] : [
  15050. M,
  15051. x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
  15052. L,
  15053. labelPos[2], labelPos[3], // second break
  15054. L,
  15055. labelPos[4], labelPos[5] // base
  15056. ];
  15057. if (connector) {
  15058. connector.animate({ d: connectorPath });
  15059. connector.attr('visibility', visibility);
  15060. } else {
  15061. point.connector = connector = series.chart.renderer.path(connectorPath).attr({
  15062. 'stroke-width': connectorWidth,
  15063. stroke: options.connectorColor || point.color || '#606060',
  15064. visibility: visibility
  15065. //zIndex: 0 // #2722 (reversed)
  15066. })
  15067. .add(series.dataLabelsGroup);
  15068. }
  15069. } else if (connector) {
  15070. point.connector = connector.destroy();
  15071. }
  15072. });
  15073. }
  15074. }
  15075. };
  15076. /**
  15077. * Perform the final placement of the data labels after we have verified that they
  15078. * fall within the plot area.
  15079. */
  15080. seriesTypes.pie.prototype.placeDataLabels = function () {
  15081. each(this.points, function (point) {
  15082. var dataLabel = point.dataLabel,
  15083. _pos;
  15084. if (dataLabel) {
  15085. _pos = dataLabel._pos;
  15086. if (_pos) {
  15087. dataLabel.attr(dataLabel._attr);
  15088. dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos);
  15089. dataLabel.moved = true;
  15090. } else if (dataLabel) {
  15091. dataLabel.attr({ y: -999 });
  15092. }
  15093. }
  15094. });
  15095. };
  15096. seriesTypes.pie.prototype.alignDataLabel = noop;
  15097. /**
  15098. * Verify whether the data labels are allowed to draw, or we should run more translation and data
  15099. * label positioning to keep them inside the plot area. Returns true when data labels are ready
  15100. * to draw.
  15101. */
  15102. seriesTypes.pie.prototype.verifyDataLabelOverflow = function (overflow) {
  15103. var center = this.center,
  15104. options = this.options,
  15105. centerOption = options.center,
  15106. minSize = options.minSize || 80,
  15107. newSize = minSize,
  15108. ret;
  15109. // Handle horizontal size and center
  15110. if (centerOption[0] !== null) { // Fixed center
  15111. newSize = mathMax(center[2] - mathMax(overflow[1], overflow[3]), minSize);
  15112. } else { // Auto center
  15113. newSize = mathMax(
  15114. center[2] - overflow[1] - overflow[3], // horizontal overflow
  15115. minSize
  15116. );
  15117. center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center
  15118. }
  15119. // Handle vertical size and center
  15120. if (centerOption[1] !== null) { // Fixed center
  15121. newSize = mathMax(mathMin(newSize, center[2] - mathMax(overflow[0], overflow[2])), minSize);
  15122. } else { // Auto center
  15123. newSize = mathMax(
  15124. mathMin(
  15125. newSize,
  15126. center[2] - overflow[0] - overflow[2] // vertical overflow
  15127. ),
  15128. minSize
  15129. );
  15130. center[1] += (overflow[0] - overflow[2]) / 2; // vertical center
  15131. }
  15132. // If the size must be decreased, we need to run translate and drawDataLabels again
  15133. if (newSize < center[2]) {
  15134. center[2] = newSize;
  15135. this.translate(center);
  15136. each(this.points, function (point) {
  15137. if (point.dataLabel) {
  15138. point.dataLabel._pos = null; // reset
  15139. }
  15140. });
  15141. if (this.drawDataLabels) {
  15142. this.drawDataLabels();
  15143. }
  15144. // Else, return true to indicate that the pie and its labels is within the plot area
  15145. } else {
  15146. ret = true;
  15147. }
  15148. return ret;
  15149. };
  15150. }
  15151. if (seriesTypes.column) {
  15152. /**
  15153. * Override the basic data label alignment by adjusting for the position of the column
  15154. */
  15155. seriesTypes.column.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) {
  15156. var inverted = this.chart.inverted,
  15157. series = point.series,
  15158. dlBox = point.dlBox || point.shapeArgs, // data label box for alignment
  15159. below = point.below || (point.plotY > pick(this.translatedThreshold, series.yAxis.len)),
  15160. inside = pick(options.inside, !!this.options.stacking); // draw it inside the box?
  15161. // Align to the column itself, or the top of it
  15162. if (dlBox) { // Area range uses this method but not alignTo
  15163. alignTo = merge(dlBox);
  15164. if (inverted) {
  15165. alignTo = {
  15166. x: series.yAxis.len - alignTo.y - alignTo.height,
  15167. y: series.xAxis.len - alignTo.x - alignTo.width,
  15168. width: alignTo.height,
  15169. height: alignTo.width
  15170. };
  15171. }
  15172. // Compute the alignment box
  15173. if (!inside) {
  15174. if (inverted) {
  15175. alignTo.x += below ? 0 : alignTo.width;
  15176. alignTo.width = 0;
  15177. } else {
  15178. alignTo.y += below ? alignTo.height : 0;
  15179. alignTo.height = 0;
  15180. }
  15181. }
  15182. }
  15183. // When alignment is undefined (typically columns and bars), display the individual
  15184. // point below or above the point depending on the threshold
  15185. options.align = pick(
  15186. options.align,
  15187. !inverted || inside ? 'center' : below ? 'right' : 'left'
  15188. );
  15189. options.verticalAlign = pick(
  15190. options.verticalAlign,
  15191. inverted || inside ? 'middle' : below ? 'top' : 'bottom'
  15192. );
  15193. // Call the parent method
  15194. Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew);
  15195. };
  15196. }
  15197. /**
  15198. * Highcharts JS v4.1.5 (2015-04-13)
  15199. * Highcharts module to hide overlapping data labels. This module is included by default in Highmaps.
  15200. *
  15201. * (c) 2010-2014 Torstein Honsi
  15202. *
  15203. * License: www.highcharts.com/license
  15204. */
  15205. /*global Highcharts, HighchartsAdapter */
  15206. (function (H) {
  15207. var Chart = H.Chart,
  15208. each = H.each,
  15209. addEvent = HighchartsAdapter.addEvent;
  15210. // Collect potensial overlapping data labels. Stack labels probably don't need to be
  15211. // considered because they are usually accompanied by data labels that lie inside the columns.
  15212. Chart.prototype.callbacks.push(function (chart) {
  15213. function collectAndHide() {
  15214. var labels = [];
  15215. each(chart.series, function (series) {
  15216. var dlOptions = series.options.dataLabels;
  15217. if ((dlOptions.enabled || series._hasPointLabels) && !dlOptions.allowOverlap && series.visible) { // #3866
  15218. each(series.points, function (point) {
  15219. if (point.dataLabel) {
  15220. point.dataLabel.labelrank = point.labelrank;
  15221. labels.push(point.dataLabel);
  15222. }
  15223. });
  15224. }
  15225. });
  15226. chart.hideOverlappingLabels(labels);
  15227. }
  15228. // Do it now ...
  15229. collectAndHide();
  15230. // ... and after each chart redraw
  15231. addEvent(chart, 'redraw', collectAndHide);
  15232. });
  15233. /**
  15234. * Hide overlapping labels. Labels are moved and faded in and out on zoom to provide a smooth
  15235. * visual imression.
  15236. */
  15237. Chart.prototype.hideOverlappingLabels = function (labels) {
  15238. var len = labels.length,
  15239. label,
  15240. i,
  15241. j,
  15242. label1,
  15243. label2,
  15244. intersectRect = function (pos1, pos2, size1, size2) {
  15245. return !(
  15246. pos2.x > pos1.x + size1.width ||
  15247. pos2.x + size2.width < pos1.x ||
  15248. pos2.y > pos1.y + size1.height ||
  15249. pos2.y + size2.height < pos1.y
  15250. );
  15251. };
  15252. // Mark with initial opacity
  15253. for (i = 0; i < len; i++) {
  15254. label = labels[i];
  15255. if (label) {
  15256. label.oldOpacity = label.opacity;
  15257. label.newOpacity = 1;
  15258. }
  15259. }
  15260. // Detect overlapping labels
  15261. for (i = 0; i < len; i++) {
  15262. label1 = labels[i];
  15263. for (j = i + 1; j < len; ++j) {
  15264. label2 = labels[j];
  15265. if (label1 && label2 && label1.placed && label2.placed && label1.newOpacity !== 0 && label2.newOpacity !== 0 &&
  15266. intersectRect(label1.alignAttr, label2.alignAttr, label1, label2)) {
  15267. (label1.labelrank < label2.labelrank ? label1 : label2).newOpacity = 0;
  15268. }
  15269. }
  15270. }
  15271. // Hide or show
  15272. for (i = 0; i < len; i++) {
  15273. label = labels[i];
  15274. if (label) {
  15275. if (label.oldOpacity !== label.newOpacity && label.placed) {
  15276. label.alignAttr.opacity = label.newOpacity;
  15277. label[label.isOld && label.newOpacity ? 'animate' : 'attr'](label.alignAttr);
  15278. }
  15279. label.isOld = true;
  15280. }
  15281. }
  15282. };
  15283. }(Highcharts));/**
  15284. * TrackerMixin for points and graphs
  15285. */
  15286. var TrackerMixin = Highcharts.TrackerMixin = {
  15287. drawTrackerPoint: function () {
  15288. var series = this,
  15289. chart = series.chart,
  15290. pointer = chart.pointer,
  15291. cursor = series.options.cursor,
  15292. css = cursor && { cursor: cursor },
  15293. onMouseOver = function (e) {
  15294. var target = e.target,
  15295. point;
  15296. while (target && !point) {
  15297. point = target.point;
  15298. target = target.parentNode;
  15299. }
  15300. if (point !== UNDEFINED && point !== chart.hoverPoint) { // undefined on graph in scatterchart
  15301. point.onMouseOver(e);
  15302. }
  15303. };
  15304. // Add reference to the point
  15305. each(series.points, function (point) {
  15306. if (point.graphic) {
  15307. point.graphic.element.point = point;
  15308. }
  15309. if (point.dataLabel) {
  15310. point.dataLabel.element.point = point;
  15311. }
  15312. });
  15313. // Add the event listeners, we need to do this only once
  15314. if (!series._hasTracking) {
  15315. each(series.trackerGroups, function (key) {
  15316. if (series[key]) { // we don't always have dataLabelsGroup
  15317. series[key]
  15318. .addClass(PREFIX + 'tracker')
  15319. .on('mouseover', onMouseOver)
  15320. .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); })
  15321. .css(css);
  15322. if (hasTouch) {
  15323. series[key].on('touchstart', onMouseOver);
  15324. }
  15325. }
  15326. });
  15327. series._hasTracking = true;
  15328. }
  15329. },
  15330. /**
  15331. * Draw the tracker object that sits above all data labels and markers to
  15332. * track mouse events on the graph or points. For the line type charts
  15333. * the tracker uses the same graphPath, but with a greater stroke width
  15334. * for better control.
  15335. */
  15336. drawTrackerGraph: function () {
  15337. var series = this,
  15338. options = series.options,
  15339. trackByArea = options.trackByArea,
  15340. trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath),
  15341. trackerPathLength = trackerPath.length,
  15342. chart = series.chart,
  15343. pointer = chart.pointer,
  15344. renderer = chart.renderer,
  15345. snap = chart.options.tooltip.snap,
  15346. tracker = series.tracker,
  15347. cursor = options.cursor,
  15348. css = cursor && { cursor: cursor },
  15349. singlePoints = series.singlePoints,
  15350. singlePoint,
  15351. i,
  15352. onMouseOver = function () {
  15353. if (chart.hoverSeries !== series) {
  15354. series.onMouseOver();
  15355. }
  15356. },
  15357. /*
  15358. * Empirical lowest possible opacities for TRACKER_FILL for an element to stay invisible but clickable
  15359. * IE6: 0.002
  15360. * IE7: 0.002
  15361. * IE8: 0.002
  15362. * IE9: 0.00000000001 (unlimited)
  15363. * IE10: 0.0001 (exporting only)
  15364. * FF: 0.00000000001 (unlimited)
  15365. * Chrome: 0.000001
  15366. * Safari: 0.000001
  15367. * Opera: 0.00000000001 (unlimited)
  15368. */
  15369. TRACKER_FILL = 'rgba(192,192,192,' + (hasSVG ? 0.0001 : 0.002) + ')';
  15370. // Extend end points. A better way would be to use round linecaps,
  15371. // but those are not clickable in VML.
  15372. if (trackerPathLength && !trackByArea) {
  15373. i = trackerPathLength + 1;
  15374. while (i--) {
  15375. if (trackerPath[i] === M) { // extend left side
  15376. trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L);
  15377. }
  15378. if ((i && trackerPath[i] === M) || i === trackerPathLength) { // extend right side
  15379. trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]);
  15380. }
  15381. }
  15382. }
  15383. // handle single points
  15384. for (i = 0; i < singlePoints.length; i++) {
  15385. singlePoint = singlePoints[i];
  15386. trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY,
  15387. L, singlePoint.plotX + snap, singlePoint.plotY);
  15388. }
  15389. // draw the tracker
  15390. if (tracker) {
  15391. tracker.attr({ d: trackerPath });
  15392. } else { // create
  15393. series.tracker = renderer.path(trackerPath)
  15394. .attr({
  15395. 'stroke-linejoin': 'round', // #1225
  15396. visibility: series.visible ? VISIBLE : HIDDEN,
  15397. stroke: TRACKER_FILL,
  15398. fill: trackByArea ? TRACKER_FILL : NONE,
  15399. 'stroke-width' : options.lineWidth + (trackByArea ? 0 : 2 * snap),
  15400. zIndex: 2
  15401. })
  15402. .add(series.group);
  15403. // The tracker is added to the series group, which is clipped, but is covered
  15404. // by the marker group. So the marker group also needs to capture events.
  15405. each([series.tracker, series.markerGroup], function (tracker) {
  15406. tracker.addClass(PREFIX + 'tracker')
  15407. .on('mouseover', onMouseOver)
  15408. .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); })
  15409. .css(css);
  15410. if (hasTouch) {
  15411. tracker.on('touchstart', onMouseOver);
  15412. }
  15413. });
  15414. }
  15415. }
  15416. };
  15417. /* End TrackerMixin */
  15418. /**
  15419. * Add tracking event listener to the series group, so the point graphics
  15420. * themselves act as trackers
  15421. */
  15422. if (seriesTypes.column) {
  15423. ColumnSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
  15424. }
  15425. if (seriesTypes.pie) {
  15426. seriesTypes.pie.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
  15427. }
  15428. if (seriesTypes.scatter) {
  15429. ScatterSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
  15430. }
  15431. /*
  15432. * Extend Legend for item events
  15433. */
  15434. extend(Legend.prototype, {
  15435. setItemEvents: function (item, legendItem, useHTML, itemStyle, itemHiddenStyle) {
  15436. var legend = this;
  15437. // Set the events on the item group, or in case of useHTML, the item itself (#1249)
  15438. (useHTML ? legendItem : item.legendGroup).on('mouseover', function () {
  15439. item.setState(HOVER_STATE);
  15440. legendItem.css(legend.options.itemHoverStyle);
  15441. })
  15442. .on('mouseout', function () {
  15443. legendItem.css(item.visible ? itemStyle : itemHiddenStyle);
  15444. item.setState();
  15445. })
  15446. .on('click', function (event) {
  15447. var strLegendItemClick = 'legendItemClick',
  15448. fnLegendItemClick = function () {
  15449. item.setVisible();
  15450. };
  15451. // Pass over the click/touch event. #4.
  15452. event = {
  15453. browserEvent: event
  15454. };
  15455. // click the name or symbol
  15456. if (item.firePointEvent) { // point
  15457. item.firePointEvent(strLegendItemClick, event, fnLegendItemClick);
  15458. } else {
  15459. fireEvent(item, strLegendItemClick, event, fnLegendItemClick);
  15460. }
  15461. });
  15462. },
  15463. createCheckboxForItem: function (item) {
  15464. var legend = this;
  15465. item.checkbox = createElement('input', {
  15466. type: 'checkbox',
  15467. checked: item.selected,
  15468. defaultChecked: item.selected // required by IE7
  15469. }, legend.options.itemCheckboxStyle, legend.chart.container);
  15470. addEvent(item.checkbox, 'click', function (event) {
  15471. var target = event.target;
  15472. fireEvent(item.series || item, 'checkboxClick', { // #3712
  15473. checked: target.checked,
  15474. item: item
  15475. },
  15476. function () {
  15477. item.select();
  15478. }
  15479. );
  15480. });
  15481. }
  15482. });
  15483. /*
  15484. * Add pointer cursor to legend itemstyle in defaultOptions
  15485. */
  15486. defaultOptions.legend.itemStyle.cursor = 'pointer';
  15487. /*
  15488. * Extend the Chart object with interaction
  15489. */
  15490. extend(Chart.prototype, {
  15491. /**
  15492. * Display the zoom button
  15493. */
  15494. showResetZoom: function () {
  15495. var chart = this,
  15496. lang = defaultOptions.lang,
  15497. btnOptions = chart.options.chart.resetZoomButton,
  15498. theme = btnOptions.theme,
  15499. states = theme.states,
  15500. alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox';
  15501. this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, function () { chart.zoomOut(); }, theme, states && states.hover)
  15502. .attr({
  15503. align: btnOptions.position.align,
  15504. title: lang.resetZoomTitle
  15505. })
  15506. .add()
  15507. .align(btnOptions.position, false, alignTo);
  15508. },
  15509. /**
  15510. * Zoom out to 1:1
  15511. */
  15512. zoomOut: function () {
  15513. var chart = this;
  15514. fireEvent(chart, 'selection', { resetSelection: true }, function () {
  15515. chart.zoom();
  15516. });
  15517. },
  15518. /**
  15519. * Zoom into a given portion of the chart given by axis coordinates
  15520. * @param {Object} event
  15521. */
  15522. zoom: function (event) {
  15523. var chart = this,
  15524. hasZoomed,
  15525. pointer = chart.pointer,
  15526. displayButton = false,
  15527. resetZoomButton;
  15528. // If zoom is called with no arguments, reset the axes
  15529. if (!event || event.resetSelection) {
  15530. each(chart.axes, function (axis) {
  15531. hasZoomed = axis.zoom();
  15532. });
  15533. } else { // else, zoom in on all axes
  15534. each(event.xAxis.concat(event.yAxis), function (axisData) {
  15535. var axis = axisData.axis,
  15536. isXAxis = axis.isXAxis;
  15537. // don't zoom more than minRange
  15538. if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) {
  15539. hasZoomed = axis.zoom(axisData.min, axisData.max);
  15540. if (axis.displayBtn) {
  15541. displayButton = true;
  15542. }
  15543. }
  15544. });
  15545. }
  15546. // Show or hide the Reset zoom button
  15547. resetZoomButton = chart.resetZoomButton;
  15548. if (displayButton && !resetZoomButton) {
  15549. chart.showResetZoom();
  15550. } else if (!displayButton && isObject(resetZoomButton)) {
  15551. chart.resetZoomButton = resetZoomButton.destroy();
  15552. }
  15553. // Redraw
  15554. if (hasZoomed) {
  15555. chart.redraw(
  15556. pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation
  15557. );
  15558. }
  15559. },
  15560. /**
  15561. * Pan the chart by dragging the mouse across the pane. This function is called
  15562. * on mouse move, and the distance to pan is computed from chartX compared to
  15563. * the first chartX position in the dragging operation.
  15564. */
  15565. pan: function (e, panning) {
  15566. var chart = this,
  15567. hoverPoints = chart.hoverPoints,
  15568. doRedraw;
  15569. // remove active points for shared tooltip
  15570. if (hoverPoints) {
  15571. each(hoverPoints, function (point) {
  15572. point.setState();
  15573. });
  15574. }
  15575. each(panning === 'xy' ? [1, 0] : [1], function (isX) { // xy is used in maps
  15576. var mousePos = e[isX ? 'chartX' : 'chartY'],
  15577. axis = chart[isX ? 'xAxis' : 'yAxis'][0],
  15578. startPos = chart[isX ? 'mouseDownX' : 'mouseDownY'],
  15579. halfPointRange = (axis.pointRange || 0) / 2,
  15580. extremes = axis.getExtremes(),
  15581. newMin = axis.toValue(startPos - mousePos, true) + halfPointRange,
  15582. newMax = axis.toValue(startPos + chart[isX ? 'plotWidth' : 'plotHeight'] - mousePos, true) - halfPointRange,
  15583. goingLeft = startPos > mousePos; // #3613
  15584. if (axis.series.length &&
  15585. (goingLeft || newMin > mathMin(extremes.dataMin, extremes.min)) &&
  15586. (!goingLeft || newMax < mathMax(extremes.dataMax, extremes.max))) {
  15587. axis.setExtremes(newMin, newMax, false, false, { trigger: 'pan' });
  15588. doRedraw = true;
  15589. }
  15590. chart[isX ? 'mouseDownX' : 'mouseDownY'] = mousePos; // set new reference for next run
  15591. });
  15592. if (doRedraw) {
  15593. chart.redraw(false);
  15594. }
  15595. css(chart.container, { cursor: 'move' });
  15596. }
  15597. });
  15598. /*
  15599. * Extend the Point object with interaction
  15600. */
  15601. extend(Point.prototype, {
  15602. /**
  15603. * Toggle the selection status of a point
  15604. * @param {Boolean} selected Whether to select or unselect the point.
  15605. * @param {Boolean} accumulate Whether to add to the previous selection. By default,
  15606. * this happens if the control key (Cmd on Mac) was pressed during clicking.
  15607. */
  15608. select: function (selected, accumulate) {
  15609. var point = this,
  15610. series = point.series,
  15611. chart = series.chart;
  15612. selected = pick(selected, !point.selected);
  15613. // fire the event with the defalut handler
  15614. point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () {
  15615. point.selected = point.options.selected = selected;
  15616. series.options.data[inArray(point, series.data)] = point.options;
  15617. point.setState(selected && SELECT_STATE);
  15618. // unselect all other points unless Ctrl or Cmd + click
  15619. if (!accumulate) {
  15620. each(chart.getSelectedPoints(), function (loopPoint) {
  15621. if (loopPoint.selected && loopPoint !== point) {
  15622. loopPoint.selected = loopPoint.options.selected = false;
  15623. series.options.data[inArray(loopPoint, series.data)] = loopPoint.options;
  15624. loopPoint.setState(NORMAL_STATE);
  15625. loopPoint.firePointEvent('unselect');
  15626. }
  15627. });
  15628. }
  15629. });
  15630. },
  15631. /**
  15632. * Runs on mouse over the point
  15633. */
  15634. onMouseOver: function (e) {
  15635. var point = this,
  15636. series = point.series,
  15637. chart = series.chart,
  15638. tooltip = chart.tooltip,
  15639. hoverPoint = chart.hoverPoint;
  15640. if (chart.hoverSeries !== series) {
  15641. series.onMouseOver();
  15642. }
  15643. // set normal state to previous series
  15644. if (hoverPoint && hoverPoint !== point) {
  15645. hoverPoint.onMouseOut();
  15646. }
  15647. // trigger the event
  15648. point.firePointEvent('mouseOver');
  15649. // update the tooltip
  15650. if (tooltip && (!tooltip.shared || series.noSharedTooltip)) {
  15651. tooltip.refresh(point, e);
  15652. }
  15653. // hover this
  15654. point.setState(HOVER_STATE);
  15655. chart.hoverPoint = point;
  15656. },
  15657. /**
  15658. * Runs on mouse out from the point
  15659. */
  15660. onMouseOut: function () {
  15661. var chart = this.series.chart,
  15662. hoverPoints = chart.hoverPoints;
  15663. this.firePointEvent('mouseOut');
  15664. if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887, #2240
  15665. this.setState();
  15666. chart.hoverPoint = null;
  15667. }
  15668. },
  15669. /**
  15670. * Import events from the series' and point's options. Only do it on
  15671. * demand, to save processing time on hovering.
  15672. */
  15673. importEvents: function () {
  15674. if (!this.hasImportedEvents) {
  15675. var point = this,
  15676. options = merge(point.series.options.point, point.options),
  15677. events = options.events,
  15678. eventType;
  15679. point.events = events;
  15680. for (eventType in events) {
  15681. addEvent(point, eventType, events[eventType]);
  15682. }
  15683. this.hasImportedEvents = true;
  15684. }
  15685. },
  15686. /**
  15687. * Set the point's state
  15688. * @param {String} state
  15689. */
  15690. setState: function (state, move) {
  15691. var point = this,
  15692. plotX = point.plotX,
  15693. plotY = point.plotY,
  15694. series = point.series,
  15695. stateOptions = series.options.states,
  15696. markerOptions = defaultPlotOptions[series.type].marker && series.options.marker,
  15697. normalDisabled = markerOptions && !markerOptions.enabled,
  15698. markerStateOptions = markerOptions && markerOptions.states[state],
  15699. stateDisabled = markerStateOptions && markerStateOptions.enabled === false,
  15700. stateMarkerGraphic = series.stateMarkerGraphic,
  15701. pointMarker = point.marker || {},
  15702. chart = series.chart,
  15703. radius,
  15704. halo = series.halo,
  15705. haloOptions,
  15706. newSymbol,
  15707. pointAttr;
  15708. state = state || NORMAL_STATE; // empty string
  15709. pointAttr = point.pointAttr[state] || series.pointAttr[state];
  15710. if (
  15711. // already has this state
  15712. (state === point.state && !move) ||
  15713. // selected points don't respond to hover
  15714. (point.selected && state !== SELECT_STATE) ||
  15715. // series' state options is disabled
  15716. (stateOptions[state] && stateOptions[state].enabled === false) ||
  15717. // general point marker's state options is disabled
  15718. (state && (stateDisabled || (normalDisabled && markerStateOptions.enabled === false))) ||
  15719. // individual point marker's state options is disabled
  15720. (state && pointMarker.states && pointMarker.states[state] && pointMarker.states[state].enabled === false) // #1610
  15721. ) {
  15722. return;
  15723. }
  15724. // apply hover styles to the existing point
  15725. if (point.graphic) {
  15726. radius = markerOptions && point.graphic.symbolName && pointAttr.r;
  15727. point.graphic.attr(merge(
  15728. pointAttr,
  15729. radius ? { // new symbol attributes (#507, #612)
  15730. x: plotX - radius,
  15731. y: plotY - radius,
  15732. width: 2 * radius,
  15733. height: 2 * radius
  15734. } : {}
  15735. ));
  15736. // Zooming in from a range with no markers to a range with markers
  15737. if (stateMarkerGraphic) {
  15738. stateMarkerGraphic.hide();
  15739. }
  15740. } else {
  15741. // if a graphic is not applied to each point in the normal state, create a shared
  15742. // graphic for the hover state
  15743. if (state && markerStateOptions) {
  15744. radius = markerStateOptions.radius;
  15745. newSymbol = pointMarker.symbol || series.symbol;
  15746. // If the point has another symbol than the previous one, throw away the
  15747. // state marker graphic and force a new one (#1459)
  15748. if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) {
  15749. stateMarkerGraphic = stateMarkerGraphic.destroy();
  15750. }
  15751. // Add a new state marker graphic
  15752. if (!stateMarkerGraphic) {
  15753. if (newSymbol) {
  15754. series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol(
  15755. newSymbol,
  15756. plotX - radius,
  15757. plotY - radius,
  15758. 2 * radius,
  15759. 2 * radius
  15760. )
  15761. .attr(pointAttr)
  15762. .add(series.markerGroup);
  15763. stateMarkerGraphic.currentSymbol = newSymbol;
  15764. }
  15765. // Move the existing graphic
  15766. } else {
  15767. stateMarkerGraphic[move ? 'animate' : 'attr']({ // #1054
  15768. x: plotX - radius,
  15769. y: plotY - radius
  15770. });
  15771. }
  15772. }
  15773. if (stateMarkerGraphic) {
  15774. stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY, chart.inverted) ? 'show' : 'hide'](); // #2450
  15775. }
  15776. }
  15777. // Show me your halo
  15778. haloOptions = stateOptions[state] && stateOptions[state].halo;
  15779. if (haloOptions && haloOptions.size) {
  15780. if (!halo) {
  15781. series.halo = halo = chart.renderer.path()
  15782. .add(chart.seriesGroup);
  15783. }
  15784. halo.attr(extend({
  15785. fill: Color(point.color || series.color).setOpacity(haloOptions.opacity).get()
  15786. }, haloOptions.attributes))[move ? 'animate' : 'attr']({
  15787. d: point.haloPath(haloOptions.size)
  15788. });
  15789. } else if (halo) {
  15790. halo.attr({ d: [] });
  15791. }
  15792. point.state = state;
  15793. },
  15794. haloPath: function (size) {
  15795. var series = this.series,
  15796. chart = series.chart,
  15797. plotBox = series.getPlotBox(),
  15798. inverted = chart.inverted;
  15799. return chart.renderer.symbols.circle(
  15800. plotBox.translateX + (inverted ? series.yAxis.len - this.plotY : this.plotX) - size,
  15801. plotBox.translateY + (inverted ? series.xAxis.len - this.plotX : this.plotY) - size,
  15802. size * 2,
  15803. size * 2
  15804. );
  15805. }
  15806. });
  15807. /*
  15808. * Extend the Series object with interaction
  15809. */
  15810. extend(Series.prototype, {
  15811. /**
  15812. * Series mouse over handler
  15813. */
  15814. onMouseOver: function () {
  15815. var series = this,
  15816. chart = series.chart,
  15817. hoverSeries = chart.hoverSeries;
  15818. // set normal state to previous series
  15819. if (hoverSeries && hoverSeries !== series) {
  15820. hoverSeries.onMouseOut();
  15821. }
  15822. // trigger the event, but to save processing time,
  15823. // only if defined
  15824. if (series.options.events.mouseOver) {
  15825. fireEvent(series, 'mouseOver');
  15826. }
  15827. // hover this
  15828. series.setState(HOVER_STATE);
  15829. chart.hoverSeries = series;
  15830. },
  15831. /**
  15832. * Series mouse out handler
  15833. */
  15834. onMouseOut: function () {
  15835. // trigger the event only if listeners exist
  15836. var series = this,
  15837. options = series.options,
  15838. chart = series.chart,
  15839. tooltip = chart.tooltip,
  15840. hoverPoint = chart.hoverPoint;
  15841. // trigger mouse out on the point, which must be in this series
  15842. if (hoverPoint) {
  15843. hoverPoint.onMouseOut();
  15844. }
  15845. // fire the mouse out event
  15846. if (series && options.events.mouseOut) {
  15847. fireEvent(series, 'mouseOut');
  15848. }
  15849. // hide the tooltip
  15850. if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) {
  15851. tooltip.hide();
  15852. }
  15853. // set normal state
  15854. series.setState();
  15855. chart.hoverSeries = null;
  15856. },
  15857. /**
  15858. * Set the state of the graph
  15859. */
  15860. setState: function (state) {
  15861. var series = this,
  15862. options = series.options,
  15863. graph = series.graph,
  15864. stateOptions = options.states,
  15865. lineWidth = options.lineWidth,
  15866. attribs,
  15867. i = 0;
  15868. state = state || NORMAL_STATE;
  15869. if (series.state !== state) {
  15870. series.state = state;
  15871. if (stateOptions[state] && stateOptions[state].enabled === false) {
  15872. return;
  15873. }
  15874. if (state) {
  15875. lineWidth = stateOptions[state].lineWidth || lineWidth + (stateOptions[state].lineWidthPlus || 0); // #4035
  15876. }
  15877. if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML
  15878. attribs = {
  15879. 'stroke-width': lineWidth
  15880. };
  15881. // use attr because animate will cause any other animation on the graph to stop
  15882. graph.attr(attribs);
  15883. while (series['zoneGraph' + i]) {
  15884. series['zoneGraph' + i].attr(attribs);
  15885. i = i + 1;
  15886. }
  15887. }
  15888. }
  15889. },
  15890. /**
  15891. * Set the visibility of the graph
  15892. *
  15893. * @param vis {Boolean} True to show the series, false to hide. If UNDEFINED,
  15894. * the visibility is toggled.
  15895. */
  15896. setVisible: function (vis, redraw) {
  15897. var series = this,
  15898. chart = series.chart,
  15899. legendItem = series.legendItem,
  15900. showOrHide,
  15901. ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries,
  15902. oldVisibility = series.visible;
  15903. // if called without an argument, toggle visibility
  15904. series.visible = vis = series.userOptions.visible = vis === UNDEFINED ? !oldVisibility : vis;
  15905. showOrHide = vis ? 'show' : 'hide';
  15906. // show or hide elements
  15907. each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) {
  15908. if (series[key]) {
  15909. series[key][showOrHide]();
  15910. }
  15911. });
  15912. // hide tooltip (#1361)
  15913. if (chart.hoverSeries === series || (chart.hoverPoint && chart.hoverPoint.series) === series) {
  15914. series.onMouseOut();
  15915. }
  15916. if (legendItem) {
  15917. chart.legend.colorizeItem(series, vis);
  15918. }
  15919. // rescale or adapt to resized chart
  15920. series.isDirty = true;
  15921. // in a stack, all other series are affected
  15922. if (series.options.stacking) {
  15923. each(chart.series, function (otherSeries) {
  15924. if (otherSeries.options.stacking && otherSeries.visible) {
  15925. otherSeries.isDirty = true;
  15926. }
  15927. });
  15928. }
  15929. // show or hide linked series
  15930. each(series.linkedSeries, function (otherSeries) {
  15931. otherSeries.setVisible(vis, false);
  15932. });
  15933. if (ignoreHiddenSeries) {
  15934. chart.isDirtyBox = true;
  15935. }
  15936. if (redraw !== false) {
  15937. chart.redraw();
  15938. }
  15939. fireEvent(series, showOrHide);
  15940. },
  15941. /**
  15942. * Show the graph
  15943. */
  15944. show: function () {
  15945. this.setVisible(true);
  15946. },
  15947. /**
  15948. * Hide the graph
  15949. */
  15950. hide: function () {
  15951. this.setVisible(false);
  15952. },
  15953. /**
  15954. * Set the selected state of the graph
  15955. *
  15956. * @param selected {Boolean} True to select the series, false to unselect. If
  15957. * UNDEFINED, the selection state is toggled.
  15958. */
  15959. select: function (selected) {
  15960. var series = this;
  15961. // if called without an argument, toggle
  15962. series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected;
  15963. if (series.checkbox) {
  15964. series.checkbox.checked = selected;
  15965. }
  15966. fireEvent(series, selected ? 'select' : 'unselect');
  15967. },
  15968. drawTracker: TrackerMixin.drawTrackerGraph
  15969. });
  15970. // global variables
  15971. extend(Highcharts, {
  15972. // Constructors
  15973. Color: Color,
  15974. Point: Point,
  15975. Tick: Tick,
  15976. Renderer: Renderer,
  15977. SVGElement: SVGElement,
  15978. SVGRenderer: SVGRenderer,
  15979. // Various
  15980. arrayMin: arrayMin,
  15981. arrayMax: arrayMax,
  15982. charts: charts,
  15983. dateFormat: dateFormat,
  15984. error: error,
  15985. format: format,
  15986. pathAnim: pathAnim,
  15987. getOptions: getOptions,
  15988. hasBidiBug: hasBidiBug,
  15989. isTouchDevice: isTouchDevice,
  15990. setOptions: setOptions,
  15991. addEvent: addEvent,
  15992. removeEvent: removeEvent,
  15993. createElement: createElement,
  15994. discardElement: discardElement,
  15995. css: css,
  15996. each: each,
  15997. map: map,
  15998. merge: merge,
  15999. splat: splat,
  16000. extendClass: extendClass,
  16001. pInt: pInt,
  16002. svg: hasSVG,
  16003. canvas: useCanVG,
  16004. vml: !hasSVG && !useCanVG,
  16005. product: PRODUCT,
  16006. version: VERSION
  16007. });
  16008. }());