highcharts.src.js 499 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906
  1. // ==ClosureCompiler==
  2. // @compilation_level SIMPLE_OPTIMIZATIONS
  3. /**
  4. * @license Highcharts JS v4.1.9 (2015-10-07)
  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. isMS = /(msie|trident|edge)/i.test(userAgent) && !isOpera,
  33. docMode8 = doc.documentMode === 8,
  34. isWebKit = !isMS && /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 && !isMS && !!doc.createElement('canvas').getContext,
  41. Renderer,
  42. hasTouch,
  43. symbolSizes = {},
  44. idCounter = 0,
  45. garbageBin,
  46. defaultOptions,
  47. dateFormat, // function
  48. pathAnim,
  49. timeUnits,
  50. noop = function () { return UNDEFINED; },
  51. charts = [],
  52. chartCount = 0,
  53. PRODUCT = 'Highcharts',
  54. VERSION = '4.1.9',
  55. // some constants for frequently used strings
  56. DIV = 'div',
  57. ABSOLUTE = 'absolute',
  58. RELATIVE = 'relative',
  59. HIDDEN = 'hidden',
  60. PREFIX = 'highcharts-',
  61. VISIBLE = 'visible',
  62. PX = 'px',
  63. NONE = 'none',
  64. M = 'M',
  65. L = 'L',
  66. numRegex = /^[0-9]+$/,
  67. NORMAL_STATE = '',
  68. HOVER_STATE = 'hover',
  69. SELECT_STATE = 'select',
  70. marginNames = ['plotTop', 'marginRight', 'marginBottom', 'plotLeft'],
  71. // Object for extending Axis
  72. AxisPlotLineOrBandExtension,
  73. // constants for attributes
  74. STROKE_WIDTH = 'stroke-width',
  75. // time methods, changed based on whether or not UTC is used
  76. Date, // Allow using a different Date class
  77. makeTime,
  78. timezoneOffset,
  79. getTimezoneOffset,
  80. getMinutes,
  81. getHours,
  82. getDay,
  83. getDate,
  84. getMonth,
  85. getFullYear,
  86. setMilliseconds,
  87. setSeconds,
  88. setMinutes,
  89. setHours,
  90. setDate,
  91. setMonth,
  92. setFullYear,
  93. // lookup over the types and the associated classes
  94. seriesTypes = {},
  95. Highcharts;
  96. // The Highcharts namespace
  97. Highcharts = win.Highcharts = win.Highcharts ? error(16, true) : {};
  98. Highcharts.seriesTypes = seriesTypes;
  99. /**
  100. * Extend an object with the members of another
  101. * @param {Object} a The object to be extended
  102. * @param {Object} b The object to add to the first one
  103. */
  104. var extend = Highcharts.extend = function (a, b) {
  105. var n;
  106. if (!a) {
  107. a = {};
  108. }
  109. for (n in b) {
  110. a[n] = b[n];
  111. }
  112. return a;
  113. };
  114. /**
  115. * Deep merge two or more objects and return a third object. If the first argument is
  116. * true, the contents of the second object is copied into the first object.
  117. * Previously this function redirected to jQuery.extend(true), but this had two limitations.
  118. * First, it deep merged arrays, which lead to workarounds in Highcharts. Second,
  119. * it copied properties from extended prototypes.
  120. */
  121. function merge() {
  122. var i,
  123. args = arguments,
  124. len,
  125. ret = {},
  126. doCopy = function (copy, original) {
  127. var value, key;
  128. // An object is replacing a primitive
  129. if (typeof copy !== 'object') {
  130. copy = {};
  131. }
  132. for (key in original) {
  133. if (original.hasOwnProperty(key)) {
  134. value = original[key];
  135. // Copy the contents of objects, but not arrays or DOM nodes
  136. if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]' &&
  137. key !== 'renderTo' && typeof value.nodeType !== 'number') {
  138. copy[key] = doCopy(copy[key] || {}, value);
  139. // Primitives and arrays are copied over directly
  140. } else {
  141. copy[key] = original[key];
  142. }
  143. }
  144. }
  145. return copy;
  146. };
  147. // If first argument is true, copy into the existing object. Used in setOptions.
  148. if (args[0] === true) {
  149. ret = args[1];
  150. args = Array.prototype.slice.call(args, 2);
  151. }
  152. // For each argument, extend the return
  153. len = args.length;
  154. for (i = 0; i < len; i++) {
  155. ret = doCopy(ret, args[i]);
  156. }
  157. return ret;
  158. }
  159. /**
  160. * Shortcut for parseInt
  161. * @param {Object} s
  162. * @param {Number} mag Magnitude
  163. */
  164. function pInt(s, mag) {
  165. return parseInt(s, mag || 10);
  166. }
  167. /**
  168. * Check for string
  169. * @param {Object} s
  170. */
  171. function isString(s) {
  172. return typeof s === 'string';
  173. }
  174. /**
  175. * Check for object
  176. * @param {Object} obj
  177. */
  178. function isObject(obj) {
  179. return obj && typeof obj === 'object';
  180. }
  181. /**
  182. * Check for array
  183. * @param {Object} obj
  184. */
  185. function isArray(obj) {
  186. return Object.prototype.toString.call(obj) === '[object Array]';
  187. }
  188. /**
  189. * Check for number
  190. * @param {Object} n
  191. */
  192. function isNumber(n) {
  193. return typeof n === 'number';
  194. }
  195. function log2lin(num) {
  196. return math.log(num) / math.LN10;
  197. }
  198. function lin2log(num) {
  199. return math.pow(10, num);
  200. }
  201. /**
  202. * Remove last occurence of an item from an array
  203. * @param {Array} arr
  204. * @param {Mixed} item
  205. */
  206. function erase(arr, item) {
  207. var i = arr.length;
  208. while (i--) {
  209. if (arr[i] === item) {
  210. arr.splice(i, 1);
  211. break;
  212. }
  213. }
  214. //return arr;
  215. }
  216. /**
  217. * Returns true if the object is not null or undefined. Like MooTools' $.defined.
  218. * @param {Object} obj
  219. */
  220. function defined(obj) {
  221. return obj !== UNDEFINED && obj !== null;
  222. }
  223. /**
  224. * Set or get an attribute or an object of attributes. Can't use jQuery attr because
  225. * it attempts to set expando properties on the SVG element, which is not allowed.
  226. *
  227. * @param {Object} elem The DOM element to receive the attribute(s)
  228. * @param {String|Object} prop The property or an abject of key-value pairs
  229. * @param {String} value The value if a single property is set
  230. */
  231. function attr(elem, prop, value) {
  232. var key,
  233. ret;
  234. // if the prop is a string
  235. if (isString(prop)) {
  236. // set the value
  237. if (defined(value)) {
  238. elem.setAttribute(prop, value);
  239. // get the value
  240. } else if (elem && elem.getAttribute) { // elem not defined when printing pie demo...
  241. ret = elem.getAttribute(prop);
  242. }
  243. // else if prop is defined, it is a hash of key/value pairs
  244. } else if (defined(prop) && isObject(prop)) {
  245. for (key in prop) {
  246. elem.setAttribute(key, prop[key]);
  247. }
  248. }
  249. return ret;
  250. }
  251. /**
  252. * Check if an element is an array, and if not, make it into an array. Like
  253. * MooTools' $.splat.
  254. */
  255. function splat(obj) {
  256. return isArray(obj) ? obj : [obj];
  257. }
  258. /**
  259. * Return the first value that is defined. Like MooTools' $.pick.
  260. */
  261. var pick = Highcharts.pick = function () {
  262. var args = arguments,
  263. i,
  264. arg,
  265. length = args.length;
  266. for (i = 0; i < length; i++) {
  267. arg = args[i];
  268. if (arg !== UNDEFINED && arg !== null) {
  269. return arg;
  270. }
  271. }
  272. };
  273. /**
  274. * Set CSS on a given element
  275. * @param {Object} el
  276. * @param {Object} styles Style object with camel case property names
  277. */
  278. function css(el, styles) {
  279. if (isMS && !hasSVG) { // #2686
  280. if (styles && styles.opacity !== UNDEFINED) {
  281. styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')';
  282. }
  283. }
  284. extend(el.style, styles);
  285. }
  286. /**
  287. * Utility function to create element with attributes and styles
  288. * @param {Object} tag
  289. * @param {Object} attribs
  290. * @param {Object} styles
  291. * @param {Object} parent
  292. * @param {Object} nopad
  293. */
  294. function createElement(tag, attribs, styles, parent, nopad) {
  295. var el = doc.createElement(tag);
  296. if (attribs) {
  297. extend(el, attribs);
  298. }
  299. if (nopad) {
  300. css(el, {padding: 0, border: NONE, margin: 0});
  301. }
  302. if (styles) {
  303. css(el, styles);
  304. }
  305. if (parent) {
  306. parent.appendChild(el);
  307. }
  308. return el;
  309. }
  310. /**
  311. * Extend a prototyped class by new members
  312. * @param {Object} parent
  313. * @param {Object} members
  314. */
  315. function extendClass(parent, members) {
  316. var object = function () { return UNDEFINED; };
  317. object.prototype = new parent();
  318. extend(object.prototype, members);
  319. return object;
  320. }
  321. /**
  322. * Pad a string to a given length by adding 0 to the beginning
  323. * @param {Number} number
  324. * @param {Number} length
  325. */
  326. function pad(number, length) {
  327. // Create an array of the remaining length +1 and join it with 0's
  328. return new Array((length || 2) + 1 - String(number).length).join(0) + number;
  329. }
  330. /**
  331. * Return a length based on either the integer value, or a percentage of a base.
  332. */
  333. function relativeLength (value, base) {
  334. return (/%$/).test(value) ? base * parseFloat(value) / 100 : parseFloat(value);
  335. }
  336. /**
  337. * Wrap a method with extended functionality, preserving the original function
  338. * @param {Object} obj The context object that the method belongs to
  339. * @param {String} method The name of the method to extend
  340. * @param {Function} func A wrapper function callback. This function is called with the same arguments
  341. * as the original function, except that the original function is unshifted and passed as the first
  342. * argument.
  343. */
  344. var wrap = Highcharts.wrap = function (obj, method, func) {
  345. var proceed = obj[method];
  346. obj[method] = function () {
  347. var args = Array.prototype.slice.call(arguments);
  348. args.unshift(proceed);
  349. return func.apply(this, args);
  350. };
  351. };
  352. function getTZOffset(timestamp) {
  353. return ((getTimezoneOffset && getTimezoneOffset(timestamp)) || timezoneOffset || 0) * 60000;
  354. }
  355. /**
  356. * Based on http://www.php.net/manual/en/function.strftime.php
  357. * @param {String} format
  358. * @param {Number} timestamp
  359. * @param {Boolean} capitalize
  360. */
  361. dateFormat = function (format, timestamp, capitalize) {
  362. if (!defined(timestamp) || isNaN(timestamp)) {
  363. return defaultOptions.lang.invalidDate || '';
  364. }
  365. format = pick(format, '%Y-%m-%d %H:%M:%S');
  366. var date = new Date(timestamp - getTZOffset(timestamp)),
  367. key, // used in for constuct below
  368. // get the basic time values
  369. hours = date[getHours](),
  370. day = date[getDay](),
  371. dayOfMonth = date[getDate](),
  372. month = date[getMonth](),
  373. fullYear = date[getFullYear](),
  374. lang = defaultOptions.lang,
  375. langWeekdays = lang.weekdays,
  376. // List all format keys. Custom formats can be added from the outside.
  377. replacements = extend({
  378. // Day
  379. 'a': langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon'
  380. 'A': langWeekdays[day], // Long weekday, like 'Monday'
  381. 'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31
  382. 'e': dayOfMonth, // Day of the month, 1 through 31
  383. 'w': day,
  384. // Week (none implemented)
  385. //'W': weekNumber(),
  386. // Month
  387. 'b': lang.shortMonths[month], // Short month, like 'Jan'
  388. 'B': lang.months[month], // Long month, like 'January'
  389. 'm': pad(month + 1), // Two digit month number, 01 through 12
  390. // Year
  391. 'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009
  392. 'Y': fullYear, // Four digits year, like 2009
  393. // Time
  394. 'H': pad(hours), // Two digits hours in 24h format, 00 through 23
  395. 'k': hours, // Hours in 24h format, 0 through 23
  396. 'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11
  397. 'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12
  398. 'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59
  399. 'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM
  400. 'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM
  401. 'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59
  402. 'L': pad(mathRound(timestamp % 1000), 3) // Milliseconds (naming from Ruby)
  403. }, Highcharts.dateFormats);
  404. // do the replaces
  405. for (key in replacements) {
  406. while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster
  407. format = format.replace('%' + key, typeof replacements[key] === 'function' ? replacements[key](timestamp) : replacements[key]);
  408. }
  409. }
  410. // Optionally capitalize the string and return
  411. return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format;
  412. };
  413. /**
  414. * Format a single variable. Similar to sprintf, without the % prefix.
  415. */
  416. function formatSingle(format, val) {
  417. var floatRegex = /f$/,
  418. decRegex = /\.([0-9])/,
  419. lang = defaultOptions.lang,
  420. decimals;
  421. if (floatRegex.test(format)) { // float
  422. decimals = format.match(decRegex);
  423. decimals = decimals ? decimals[1] : -1;
  424. if (val !== null) {
  425. val = Highcharts.numberFormat(
  426. val,
  427. decimals,
  428. lang.decimalPoint,
  429. format.indexOf(',') > -1 ? lang.thousandsSep : ''
  430. );
  431. }
  432. } else {
  433. val = dateFormat(format, val);
  434. }
  435. return val;
  436. }
  437. /**
  438. * Format a string according to a subset of the rules of Python's String.format method.
  439. */
  440. function format(str, ctx) {
  441. var splitter = '{',
  442. isInside = false,
  443. segment,
  444. valueAndFormat,
  445. path,
  446. i,
  447. len,
  448. ret = [],
  449. val,
  450. index;
  451. while ((index = str.indexOf(splitter)) !== -1) {
  452. segment = str.slice(0, index);
  453. if (isInside) { // we're on the closing bracket looking back
  454. valueAndFormat = segment.split(':');
  455. path = valueAndFormat.shift().split('.'); // get first and leave format
  456. len = path.length;
  457. val = ctx;
  458. // Assign deeper paths
  459. for (i = 0; i < len; i++) {
  460. val = val[path[i]];
  461. }
  462. // Format the replacement
  463. if (valueAndFormat.length) {
  464. val = formatSingle(valueAndFormat.join(':'), val);
  465. }
  466. // Push the result and advance the cursor
  467. ret.push(val);
  468. } else {
  469. ret.push(segment);
  470. }
  471. str = str.slice(index + 1); // the rest
  472. isInside = !isInside; // toggle
  473. splitter = isInside ? '}' : '{'; // now look for next matching bracket
  474. }
  475. ret.push(str);
  476. return ret.join('');
  477. }
  478. /**
  479. * Get the magnitude of a number
  480. */
  481. function getMagnitude(num) {
  482. return math.pow(10, mathFloor(math.log(num) / math.LN10));
  483. }
  484. /**
  485. * Take an interval and normalize it to multiples of 1, 2, 2.5 and 5
  486. * @param {Number} interval
  487. * @param {Array} multiples
  488. * @param {Number} magnitude
  489. * @param {Object} options
  490. */
  491. function normalizeTickInterval(interval, multiples, magnitude, allowDecimals, preventExceed) {
  492. var normalized,
  493. i,
  494. retInterval = interval;
  495. // round to a tenfold of 1, 2, 2.5 or 5
  496. magnitude = pick(magnitude, 1);
  497. normalized = interval / magnitude;
  498. // multiples for a linear scale
  499. if (!multiples) {
  500. multiples = [1, 2, 2.5, 5, 10];
  501. // the allowDecimals option
  502. if (allowDecimals === false) {
  503. if (magnitude === 1) {
  504. multiples = [1, 2, 5, 10];
  505. } else if (magnitude <= 0.1) {
  506. multiples = [1 / magnitude];
  507. }
  508. }
  509. }
  510. // normalize the interval to the nearest multiple
  511. for (i = 0; i < multiples.length; i++) {
  512. retInterval = multiples[i];
  513. if ((preventExceed && retInterval * magnitude >= interval) || // only allow tick amounts smaller than natural
  514. (!preventExceed && (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2))) {
  515. break;
  516. }
  517. }
  518. // multiply back to the correct magnitude
  519. retInterval *= magnitude;
  520. return retInterval;
  521. }
  522. /**
  523. * Utility method that sorts an object array and keeping the order of equal items.
  524. * ECMA script standard does not specify the behaviour when items are equal.
  525. */
  526. function stableSort(arr, sortFunction) {
  527. var length = arr.length,
  528. sortValue,
  529. i;
  530. // Add index to each item
  531. for (i = 0; i < length; i++) {
  532. arr[i].ss_i = i; // stable sort index
  533. }
  534. arr.sort(function (a, b) {
  535. sortValue = sortFunction(a, b);
  536. return sortValue === 0 ? a.ss_i - b.ss_i : sortValue;
  537. });
  538. // Remove index from items
  539. for (i = 0; i < length; i++) {
  540. delete arr[i].ss_i; // stable sort index
  541. }
  542. }
  543. /**
  544. * Non-recursive method to find the lowest member of an array. Math.min raises a maximum
  545. * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
  546. * method is slightly slower, but safe.
  547. */
  548. function arrayMin(data) {
  549. var i = data.length,
  550. min = data[0];
  551. while (i--) {
  552. if (data[i] < min) {
  553. min = data[i];
  554. }
  555. }
  556. return min;
  557. }
  558. /**
  559. * Non-recursive method to find the lowest member of an array. Math.min raises a maximum
  560. * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
  561. * method is slightly slower, but safe.
  562. */
  563. function arrayMax(data) {
  564. var i = data.length,
  565. max = data[0];
  566. while (i--) {
  567. if (data[i] > max) {
  568. max = data[i];
  569. }
  570. }
  571. return max;
  572. }
  573. /**
  574. * Utility method that destroys any SVGElement or VMLElement that are properties on the given object.
  575. * It loops all properties and invokes destroy if there is a destroy method. The property is
  576. * then delete'ed.
  577. * @param {Object} The object to destroy properties on
  578. * @param {Object} Exception, do not destroy this property, only delete it.
  579. */
  580. function destroyObjectProperties(obj, except) {
  581. var n;
  582. for (n in obj) {
  583. // If the object is non-null and destroy is defined
  584. if (obj[n] && obj[n] !== except && obj[n].destroy) {
  585. // Invoke the destroy
  586. obj[n].destroy();
  587. }
  588. // Delete the property from the object.
  589. delete obj[n];
  590. }
  591. }
  592. /**
  593. * Discard an element by moving it to the bin and delete
  594. * @param {Object} The HTML node to discard
  595. */
  596. function discardElement(element) {
  597. // create a garbage bin element, not part of the DOM
  598. if (!garbageBin) {
  599. garbageBin = createElement(DIV);
  600. }
  601. // move the node and empty bin
  602. if (element) {
  603. garbageBin.appendChild(element);
  604. }
  605. garbageBin.innerHTML = '';
  606. }
  607. /**
  608. * Provide error messages for debugging, with links to online explanation
  609. */
  610. function error (code, stop) {
  611. var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code;
  612. if (stop) {
  613. throw msg;
  614. }
  615. // else ...
  616. if (win.console) {
  617. console.log(msg);
  618. }
  619. }
  620. /**
  621. * Fix JS round off float errors
  622. * @param {Number} num
  623. */
  624. function correctFloat(num, prec) {
  625. return parseFloat(
  626. num.toPrecision(prec || 14)
  627. );
  628. }
  629. /**
  630. * Set the global animation to either a given value, or fall back to the
  631. * given chart's animation option
  632. * @param {Object} animation
  633. * @param {Object} chart
  634. */
  635. function setAnimation(animation, chart) {
  636. chart.renderer.globalAnimation = pick(animation, chart.animation);
  637. }
  638. /**
  639. * The time unit lookup
  640. */
  641. timeUnits = {
  642. millisecond: 1,
  643. second: 1000,
  644. minute: 60000,
  645. hour: 3600000,
  646. day: 24 * 3600000,
  647. week: 7 * 24 * 3600000,
  648. month: 28 * 24 * 3600000,
  649. year: 364 * 24 * 3600000
  650. };
  651. /**
  652. * Format a number and return a string based on input settings
  653. * @param {Number} number The input number to format
  654. * @param {Number} decimals The amount of decimals
  655. * @param {String} decPoint The decimal point, defaults to the one given in the lang options
  656. * @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options
  657. */
  658. Highcharts.numberFormat = function (number, decimals, decPoint, thousandsSep) {
  659. var lang = defaultOptions.lang,
  660. // http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/
  661. n = +number || 0,
  662. c = decimals === -1 ?
  663. mathMin((n.toString().split('.')[1] || '').length, 20) : // Preserve decimals. Not huge numbers (#3793).
  664. (isNaN(decimals = mathAbs(decimals)) ? 2 : decimals),
  665. d = decPoint === undefined ? lang.decimalPoint : decPoint,
  666. t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep,
  667. s = n < 0 ? "-" : "",
  668. i = String(pInt(n = mathAbs(n).toFixed(c))),
  669. j = i.length > 3 ? i.length % 3 : 0;
  670. return (s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) +
  671. (c ? d + mathAbs(n - i).toFixed(c).slice(2) : ""));
  672. };
  673. /**
  674. * Path interpolation algorithm used across adapters
  675. */
  676. pathAnim = {
  677. /**
  678. * Prepare start and end values so that the path can be animated one to one
  679. */
  680. init: function (elem, fromD, toD) {
  681. fromD = fromD || '';
  682. var shift = elem.shift,
  683. bezier = fromD.indexOf('C') > -1,
  684. numParams = bezier ? 7 : 3,
  685. endLength,
  686. slice,
  687. i,
  688. start = fromD.split(' '),
  689. end = [].concat(toD), // copy
  690. startBaseLine,
  691. endBaseLine,
  692. sixify = function (arr) { // in splines make move points have six parameters like bezier curves
  693. i = arr.length;
  694. while (i--) {
  695. if (arr[i] === M) {
  696. arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]);
  697. }
  698. }
  699. };
  700. if (bezier) {
  701. sixify(start);
  702. sixify(end);
  703. }
  704. // pull out the base lines before padding
  705. if (elem.isArea) {
  706. startBaseLine = start.splice(start.length - 6, 6);
  707. endBaseLine = end.splice(end.length - 6, 6);
  708. }
  709. // if shifting points, prepend a dummy point to the end path
  710. if (shift <= end.length / numParams && start.length === end.length) {
  711. while (shift--) {
  712. end = [].concat(end).splice(0, numParams).concat(end);
  713. }
  714. }
  715. elem.shift = 0; // reset for following animations
  716. // copy and append last point until the length matches the end length
  717. if (start.length) {
  718. endLength = end.length;
  719. while (start.length < endLength) {
  720. //bezier && sixify(start);
  721. slice = [].concat(start).splice(start.length - numParams, numParams);
  722. if (bezier) { // disable first control point
  723. slice[numParams - 6] = slice[numParams - 2];
  724. slice[numParams - 5] = slice[numParams - 1];
  725. }
  726. start = start.concat(slice);
  727. }
  728. }
  729. if (startBaseLine) { // append the base lines for areas
  730. start = start.concat(startBaseLine);
  731. end = end.concat(endBaseLine);
  732. }
  733. return [start, end];
  734. },
  735. /**
  736. * Interpolate each value of the path and return the array
  737. */
  738. step: function (start, end, pos, complete) {
  739. var ret = [],
  740. i = start.length,
  741. startVal;
  742. if (pos === 1) { // land on the final path without adjustment points appended in the ends
  743. ret = complete;
  744. } else if (i === end.length && pos < 1) {
  745. while (i--) {
  746. startVal = parseFloat(start[i]);
  747. ret[i] =
  748. isNaN(startVal) ? // a letter instruction like M or L
  749. start[i] :
  750. pos * (parseFloat(end[i] - startVal)) + startVal;
  751. }
  752. } else { // if animation is finished or length not matching, land on right value
  753. ret = end;
  754. }
  755. return ret;
  756. }
  757. };
  758. (function ($) {
  759. /**
  760. * The default HighchartsAdapter for jQuery
  761. */
  762. win.HighchartsAdapter = win.HighchartsAdapter || ($ && {
  763. /**
  764. * Initialize the adapter by applying some extensions to jQuery
  765. */
  766. init: function (pathAnim) {
  767. // extend the animate function to allow SVG animations
  768. var Fx = $.fx;
  769. /*jslint unparam: true*//* allow unused param x in this function */
  770. $.extend($.easing, {
  771. easeOutQuad: function (x, t, b, c, d) {
  772. return -c * (t /= d) * (t - 2) + b;
  773. }
  774. });
  775. /*jslint unparam: false*/
  776. // extend some methods to check for elem.attr, which means it is a Highcharts SVG object
  777. $.each(['cur', '_default', 'width', 'height', 'opacity'], function (i, fn) {
  778. var obj = Fx.step,
  779. base;
  780. // Handle different parent objects
  781. if (fn === 'cur') {
  782. obj = Fx.prototype; // 'cur', the getter, relates to Fx.prototype
  783. } else if (fn === '_default' && $.Tween) { // jQuery 1.8 model
  784. obj = $.Tween.propHooks[fn];
  785. fn = 'set';
  786. }
  787. // Overwrite the method
  788. base = obj[fn];
  789. if (base) { // step.width and step.height don't exist in jQuery < 1.7
  790. // create the extended function replacement
  791. obj[fn] = function (fx) {
  792. var elem;
  793. // Fx.prototype.cur does not use fx argument
  794. fx = i ? fx : this;
  795. // Don't run animations on textual properties like align (#1821)
  796. if (fx.prop === 'align') {
  797. return;
  798. }
  799. // shortcut
  800. elem = fx.elem;
  801. // Fx.prototype.cur returns the current value. The other ones are setters
  802. // and returning a value has no effect.
  803. return elem.attr ? // is SVG element wrapper
  804. elem.attr(fx.prop, fn === 'cur' ? UNDEFINED : fx.now) : // apply the SVG wrapper's method
  805. base.apply(this, arguments); // use jQuery's built-in method
  806. };
  807. }
  808. });
  809. // Extend the opacity getter, needed for fading opacity with IE9 and jQuery 1.10+
  810. wrap($.cssHooks.opacity, 'get', function (proceed, elem, computed) {
  811. return elem.attr ? (elem.opacity || 0) : proceed.call(this, elem, computed);
  812. });
  813. // Define the setter function for d (path definitions)
  814. this.addAnimSetter('d', function (fx) {
  815. var elem = fx.elem,
  816. ends;
  817. // Normally start and end should be set in state == 0, but sometimes,
  818. // for reasons unknown, this doesn't happen. Perhaps state == 0 is skipped
  819. // in these cases
  820. if (!fx.started) {
  821. ends = pathAnim.init(elem, elem.d, elem.toD);
  822. fx.start = ends[0];
  823. fx.end = ends[1];
  824. fx.started = true;
  825. }
  826. // Interpolate each value of the path
  827. elem.attr('d', pathAnim.step(fx.start, fx.end, fx.pos, elem.toD));
  828. });
  829. /**
  830. * Utility for iterating over an array. Parameters are reversed compared to jQuery.
  831. * @param {Array} arr
  832. * @param {Function} fn
  833. */
  834. this.each = Array.prototype.forEach ?
  835. function (arr, fn) { // modern browsers
  836. return Array.prototype.forEach.call(arr, fn);
  837. } :
  838. function (arr, fn) { // legacy
  839. var i,
  840. len = arr.length;
  841. for (i = 0; i < len; i++) {
  842. if (fn.call(arr[i], arr[i], i, arr) === false) {
  843. return i;
  844. }
  845. }
  846. };
  847. /**
  848. * Register Highcharts as a plugin in the respective framework
  849. */
  850. $.fn.highcharts = function () {
  851. var constr = 'Chart', // default constructor
  852. args = arguments,
  853. options,
  854. ret,
  855. chart;
  856. if (this[0]) {
  857. if (isString(args[0])) {
  858. constr = args[0];
  859. args = Array.prototype.slice.call(args, 1);
  860. }
  861. options = args[0];
  862. // Create the chart
  863. if (options !== UNDEFINED) {
  864. /*jslint unused:false*/
  865. options.chart = options.chart || {};
  866. options.chart.renderTo = this[0];
  867. chart = new Highcharts[constr](options, args[1]);
  868. ret = this;
  869. /*jslint unused:true*/
  870. }
  871. // When called without parameters or with the return argument, get a predefined chart
  872. if (options === UNDEFINED) {
  873. ret = charts[attr(this[0], 'data-highcharts-chart')];
  874. }
  875. }
  876. return ret;
  877. };
  878. },
  879. /**
  880. * Add an animation setter for a specific property
  881. */
  882. addAnimSetter: function (prop, setter) {
  883. // jQuery 1.8 style
  884. if ($.Tween) {
  885. $.Tween.propHooks[prop] = {
  886. set: setter
  887. };
  888. // pre 1.8
  889. } else {
  890. $.fx.step[prop] = setter;
  891. }
  892. },
  893. /**
  894. * Downloads a script and executes a callback when done.
  895. * @param {String} scriptLocation
  896. * @param {Function} callback
  897. */
  898. getScript: $.getScript,
  899. /**
  900. * Return the index of an item in an array, or -1 if not found
  901. */
  902. inArray: $.inArray,
  903. /**
  904. * A direct link to jQuery methods. MooTools and Prototype adapters must be implemented for each case of method.
  905. * @param {Object} elem The HTML element
  906. * @param {String} method Which method to run on the wrapped element
  907. */
  908. adapterRun: function (elem, method) {
  909. return $(elem)[method]();
  910. },
  911. /**
  912. * Filter an array
  913. */
  914. grep: $.grep,
  915. /**
  916. * Map an array
  917. * @param {Array} arr
  918. * @param {Function} fn
  919. */
  920. map: function (arr, fn) {
  921. //return jQuery.map(arr, fn);
  922. var results = [],
  923. i = 0,
  924. len = arr.length;
  925. for (; i < len; i++) {
  926. results[i] = fn.call(arr[i], arr[i], i, arr);
  927. }
  928. return results;
  929. },
  930. /**
  931. * Get the position of an element relative to the top left of the page
  932. */
  933. offset: function (el) {
  934. return $(el).offset();
  935. },
  936. /**
  937. * Add an event listener
  938. * @param {Object} el A HTML element or custom object
  939. * @param {String} event The event type
  940. * @param {Function} fn The event handler
  941. */
  942. addEvent: function (el, event, fn) {
  943. $(el).bind(event, fn);
  944. },
  945. /**
  946. * Remove event added with addEvent
  947. * @param {Object} el The object
  948. * @param {String} eventType The event type. Leave blank to remove all events.
  949. * @param {Function} handler The function to remove
  950. */
  951. removeEvent: function (el, eventType, handler) {
  952. // workaround for jQuery issue with unbinding custom events:
  953. // http://forum.jQuery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jQuery-1-4-2
  954. var func = doc.removeEventListener ? 'removeEventListener' : 'detachEvent';
  955. if (doc[func] && el && !el[func]) {
  956. el[func] = function () {};
  957. }
  958. $(el).unbind(eventType, handler);
  959. },
  960. /**
  961. * Fire an event on a custom object
  962. * @param {Object} el
  963. * @param {String} type
  964. * @param {Object} eventArguments
  965. * @param {Function} defaultFunction
  966. */
  967. fireEvent: function (el, type, eventArguments, defaultFunction) {
  968. var event = $.Event(type),
  969. detachedType = 'detached' + type,
  970. defaultPrevented;
  971. // Remove warnings in Chrome when accessing returnValue (#2790), layerX and layerY. Although Highcharts
  972. // never uses these properties, Chrome includes them in the default click event and
  973. // raises the warning when they are copied over in the extend statement below.
  974. //
  975. // To avoid problems in IE (see #1010) where we cannot delete the properties and avoid
  976. // testing if they are there (warning in chrome) the only option is to test if running IE.
  977. if (!isMS && eventArguments) {
  978. delete eventArguments.layerX;
  979. delete eventArguments.layerY;
  980. delete eventArguments.returnValue;
  981. }
  982. extend(event, eventArguments);
  983. // Prevent jQuery from triggering the object method that is named the
  984. // same as the event. For example, if the event is 'select', jQuery
  985. // attempts calling el.select and it goes into a loop.
  986. if (el[type]) {
  987. el[detachedType] = el[type];
  988. el[type] = null;
  989. }
  990. // Wrap preventDefault and stopPropagation in try/catch blocks in
  991. // order to prevent JS errors when cancelling events on non-DOM
  992. // objects. #615.
  993. /*jslint unparam: true*/
  994. $.each(['preventDefault', 'stopPropagation'], function (i, fn) {
  995. var base = event[fn];
  996. event[fn] = function () {
  997. try {
  998. base.call(event);
  999. } catch (e) {
  1000. if (fn === 'preventDefault') {
  1001. defaultPrevented = true;
  1002. }
  1003. }
  1004. };
  1005. });
  1006. /*jslint unparam: false*/
  1007. // trigger it
  1008. $(el).trigger(event);
  1009. // attach the method
  1010. if (el[detachedType]) {
  1011. el[type] = el[detachedType];
  1012. el[detachedType] = null;
  1013. }
  1014. if (defaultFunction && !event.isDefaultPrevented() && !defaultPrevented) {
  1015. defaultFunction(event);
  1016. }
  1017. },
  1018. /**
  1019. * Extension method needed for MooTools
  1020. */
  1021. washMouseEvent: function (e) {
  1022. var ret = e.originalEvent || e;
  1023. // computed by jQuery, needed by IE8
  1024. if (ret.pageX === UNDEFINED) { // #1236
  1025. ret.pageX = e.pageX;
  1026. ret.pageY = e.pageY;
  1027. }
  1028. return ret;
  1029. },
  1030. /**
  1031. * Animate a HTML element or SVG element wrapper
  1032. * @param {Object} el
  1033. * @param {Object} params
  1034. * @param {Object} options jQuery-like animation options: duration, easing, callback
  1035. */
  1036. animate: function (el, params, options) {
  1037. var $el = $(el);
  1038. if (!el.style) {
  1039. el.style = {}; // #1881
  1040. }
  1041. if (params.d) {
  1042. el.toD = params.d; // keep the array form for paths, used in $.fx.step.d
  1043. params.d = 1; // because in jQuery, animating to an array has a different meaning
  1044. }
  1045. $el.stop();
  1046. if (params.opacity !== UNDEFINED && el.attr) {
  1047. params.opacity += 'px'; // force jQuery to use same logic as width and height (#2161)
  1048. }
  1049. el.hasAnim = 1; // #3342
  1050. $el.animate(params, options);
  1051. },
  1052. /**
  1053. * Stop running animation
  1054. */
  1055. stop: function (el) {
  1056. if (el.hasAnim) { // #3342, memory leak on calling $(el) from destroy
  1057. $(el).stop();
  1058. }
  1059. }
  1060. });
  1061. }(win.jQuery));
  1062. // check for a custom HighchartsAdapter defined prior to this file
  1063. var globalAdapter = win.HighchartsAdapter,
  1064. adapter = globalAdapter || {};
  1065. // Initialize the adapter
  1066. if (globalAdapter) {
  1067. globalAdapter.init.call(globalAdapter, pathAnim);
  1068. }
  1069. // Utility functions. If the HighchartsAdapter is not defined, adapter is an empty object
  1070. // and all the utility functions will be null. In that case they are populated by the
  1071. // default adapters below.
  1072. var adapterRun = adapter.adapterRun,
  1073. getScript = adapter.getScript,
  1074. inArray = adapter.inArray,
  1075. each = Highcharts.each = adapter.each,
  1076. grep = adapter.grep,
  1077. offset = adapter.offset,
  1078. map = adapter.map,
  1079. addEvent = adapter.addEvent,
  1080. removeEvent = adapter.removeEvent,
  1081. fireEvent = adapter.fireEvent,
  1082. washMouseEvent = adapter.washMouseEvent,
  1083. animate = adapter.animate,
  1084. stop = adapter.stop;
  1085. /* ****************************************************************************
  1086. * Handle the options *
  1087. *****************************************************************************/
  1088. defaultOptions = {
  1089. colors: ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c',
  1090. '#8085e9', '#f15c80', '#e4d354', '#2b908f', '#f45b5b', '#91e8e1'],
  1091. symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'],
  1092. lang: {
  1093. loading: 'Loading...',
  1094. months: ['January', 'February', 'March', 'April', 'May', 'June', 'July',
  1095. 'August', 'September', 'October', 'November', 'December'],
  1096. shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  1097. weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  1098. // invalidDate: '',
  1099. decimalPoint: '.',
  1100. numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels
  1101. resetZoom: 'Reset zoom',
  1102. resetZoomTitle: 'Reset zoom level 1:1',
  1103. thousandsSep: ' '
  1104. },
  1105. global: {
  1106. useUTC: true,
  1107. //timezoneOffset: 0,
  1108. canvasToolsURL: 'http://code.highcharts.com/4.1.9/modules/canvas-tools.js',
  1109. VMLRadialGradientURL: 'http://code.highcharts.com/4.1.9/gfx/vml-radial-gradient.png'
  1110. },
  1111. chart: {
  1112. //animation: true,
  1113. //alignTicks: false,
  1114. //reflow: true,
  1115. //className: null,
  1116. //events: { load, selection },
  1117. //margin: [null],
  1118. //marginTop: null,
  1119. //marginRight: null,
  1120. //marginBottom: null,
  1121. //marginLeft: null,
  1122. borderColor: '#4572A7',
  1123. //borderWidth: 0,
  1124. borderRadius: 0,
  1125. defaultSeriesType: 'line',
  1126. ignoreHiddenSeries: true,
  1127. //inverted: false,
  1128. //shadow: false,
  1129. spacing: [10, 10, 15, 10],
  1130. //spacingTop: 10,
  1131. //spacingRight: 10,
  1132. //spacingBottom: 15,
  1133. //spacingLeft: 10,
  1134. //style: {
  1135. // fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font
  1136. // fontSize: '12px'
  1137. //},
  1138. backgroundColor: '#FFFFFF',
  1139. //plotBackgroundColor: null,
  1140. plotBorderColor: '#C0C0C0',
  1141. //plotBorderWidth: 0,
  1142. //plotShadow: false,
  1143. //zoomType: ''
  1144. resetZoomButton: {
  1145. theme: {
  1146. zIndex: 20
  1147. },
  1148. position: {
  1149. align: 'right',
  1150. x: -10,
  1151. //verticalAlign: 'top',
  1152. y: 10
  1153. }
  1154. // relativeTo: 'plot'
  1155. }
  1156. },
  1157. title: {
  1158. text: 'Chart title',
  1159. align: 'center',
  1160. // floating: false,
  1161. margin: 15,
  1162. // x: 0,
  1163. // verticalAlign: 'top',
  1164. // y: null,
  1165. style: {
  1166. color: '#333333',
  1167. fontSize: '18px'
  1168. }
  1169. },
  1170. subtitle: {
  1171. text: '',
  1172. align: 'center',
  1173. // floating: false
  1174. // x: 0,
  1175. // verticalAlign: 'top',
  1176. // y: null,
  1177. style: {
  1178. color: '#555555'
  1179. }
  1180. },
  1181. plotOptions: {
  1182. line: { // base series options
  1183. allowPointSelect: false,
  1184. showCheckbox: false,
  1185. animation: {
  1186. duration: 1000
  1187. },
  1188. //connectNulls: false,
  1189. //cursor: 'default',
  1190. //clip: true,
  1191. //dashStyle: null,
  1192. //enableMouseTracking: true,
  1193. events: {},
  1194. //legendIndex: 0,
  1195. //linecap: 'round',
  1196. lineWidth: 2,
  1197. //shadow: false,
  1198. // stacking: null,
  1199. marker: {
  1200. //enabled: true,
  1201. //symbol: null,
  1202. lineWidth: 0,
  1203. radius: 4,
  1204. lineColor: '#FFFFFF',
  1205. //fillColor: null,
  1206. states: { // states for a single point
  1207. hover: {
  1208. enabled: true,
  1209. lineWidthPlus: 1,
  1210. radiusPlus: 2
  1211. },
  1212. select: {
  1213. fillColor: '#FFFFFF',
  1214. lineColor: '#000000',
  1215. lineWidth: 2
  1216. }
  1217. }
  1218. },
  1219. point: {
  1220. events: {}
  1221. },
  1222. dataLabels: {
  1223. align: 'center',
  1224. // defer: true,
  1225. // enabled: false,
  1226. formatter: function () {
  1227. return this.y === null ? '' : Highcharts.numberFormat(this.y, -1);
  1228. },
  1229. style: {
  1230. color: 'contrast',
  1231. fontSize: '11px',
  1232. fontWeight: 'bold',
  1233. textShadow: '0 0 6px contrast, 0 0 3px contrast'
  1234. },
  1235. verticalAlign: 'bottom', // above singular point
  1236. x: 0,
  1237. y: 0,
  1238. // backgroundColor: undefined,
  1239. // borderColor: undefined,
  1240. // borderRadius: undefined,
  1241. // borderWidth: undefined,
  1242. padding: 5
  1243. // shadow: false
  1244. },
  1245. cropThreshold: 300, // draw points outside the plot area when the number of points is less than this
  1246. pointRange: 0,
  1247. //pointStart: 0,
  1248. //pointInterval: 1,
  1249. //showInLegend: null, // auto: true for standalone series, false for linked series
  1250. softThreshold: true,
  1251. states: { // states for the entire series
  1252. hover: {
  1253. //enabled: false,
  1254. lineWidthPlus: 1,
  1255. marker: {
  1256. // lineWidth: base + 1,
  1257. // radius: base + 1
  1258. },
  1259. halo: {
  1260. size: 10,
  1261. opacity: 0.25
  1262. }
  1263. },
  1264. select: {
  1265. marker: {}
  1266. }
  1267. },
  1268. stickyTracking: true,
  1269. //tooltip: {
  1270. //pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b>'
  1271. //valueDecimals: null,
  1272. //xDateFormat: '%A, %b %e, %Y',
  1273. //valuePrefix: '',
  1274. //ySuffix: ''
  1275. //}
  1276. turboThreshold: 1000
  1277. // zIndex: null
  1278. }
  1279. },
  1280. labels: {
  1281. //items: [],
  1282. style: {
  1283. //font: defaultFont,
  1284. position: ABSOLUTE,
  1285. color: '#3E576F'
  1286. }
  1287. },
  1288. legend: {
  1289. enabled: true,
  1290. align: 'center',
  1291. //floating: false,
  1292. layout: 'horizontal',
  1293. labelFormatter: function () {
  1294. return this.name;
  1295. },
  1296. //borderWidth: 0,
  1297. borderColor: '#909090',
  1298. borderRadius: 0,
  1299. navigation: {
  1300. // animation: true,
  1301. activeColor: '#274b6d',
  1302. // arrowSize: 12
  1303. inactiveColor: '#CCC'
  1304. // style: {} // text styles
  1305. },
  1306. // margin: 20,
  1307. // reversed: false,
  1308. shadow: false,
  1309. // backgroundColor: null,
  1310. /*style: {
  1311. padding: '5px'
  1312. },*/
  1313. itemStyle: {
  1314. color: '#333333',
  1315. fontSize: '12px',
  1316. fontWeight: 'bold'
  1317. },
  1318. itemHoverStyle: {
  1319. //cursor: 'pointer', removed as of #601
  1320. color: '#000'
  1321. },
  1322. itemHiddenStyle: {
  1323. color: '#CCC'
  1324. },
  1325. itemCheckboxStyle: {
  1326. position: ABSOLUTE,
  1327. width: '13px', // for IE precision
  1328. height: '13px'
  1329. },
  1330. // itemWidth: undefined,
  1331. // symbolRadius: 0,
  1332. // symbolWidth: 16,
  1333. symbolPadding: 5,
  1334. verticalAlign: 'bottom',
  1335. // width: undefined,
  1336. x: 0,
  1337. y: 0,
  1338. title: {
  1339. //text: null,
  1340. style: {
  1341. fontWeight: 'bold'
  1342. }
  1343. }
  1344. },
  1345. loading: {
  1346. // hideDuration: 100,
  1347. labelStyle: {
  1348. fontWeight: 'bold',
  1349. position: RELATIVE,
  1350. top: '45%'
  1351. },
  1352. // showDuration: 0,
  1353. style: {
  1354. position: ABSOLUTE,
  1355. backgroundColor: 'white',
  1356. opacity: 0.5,
  1357. textAlign: 'center'
  1358. }
  1359. },
  1360. tooltip: {
  1361. enabled: true,
  1362. animation: hasSVG,
  1363. //crosshairs: null,
  1364. backgroundColor: 'rgba(249, 249, 249, .85)',
  1365. borderWidth: 1,
  1366. borderRadius: 3,
  1367. dateTimeLabelFormats: {
  1368. millisecond: '%A, %b %e, %H:%M:%S.%L',
  1369. second: '%A, %b %e, %H:%M:%S',
  1370. minute: '%A, %b %e, %H:%M',
  1371. hour: '%A, %b %e, %H:%M',
  1372. day: '%A, %b %e, %Y',
  1373. week: 'Week from %A, %b %e, %Y',
  1374. month: '%B %Y',
  1375. year: '%Y'
  1376. },
  1377. footerFormat: '',
  1378. //formatter: defaultFormatter,
  1379. headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>',
  1380. pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b><br/>',
  1381. shadow: true,
  1382. //shape: 'callout',
  1383. //shared: false,
  1384. snap: isTouchDevice ? 25 : 10,
  1385. style: {
  1386. color: '#333333',
  1387. cursor: 'default',
  1388. fontSize: '12px',
  1389. padding: '8px',
  1390. pointerEvents: 'none', // #1686 http://caniuse.com/#feat=pointer-events
  1391. whiteSpace: 'nowrap'
  1392. }
  1393. //xDateFormat: '%A, %b %e, %Y',
  1394. //valueDecimals: null,
  1395. //valuePrefix: '',
  1396. //valueSuffix: ''
  1397. },
  1398. credits: {
  1399. enabled: true,
  1400. text: 'Highcharts.com',
  1401. href: 'http://www.highcharts.com',
  1402. position: {
  1403. align: 'right',
  1404. x: -10,
  1405. verticalAlign: 'bottom',
  1406. y: -5
  1407. },
  1408. style: {
  1409. cursor: 'pointer',
  1410. color: '#909090',
  1411. fontSize: '9px'
  1412. }
  1413. }
  1414. };
  1415. // Series defaults
  1416. var defaultPlotOptions = defaultOptions.plotOptions,
  1417. defaultSeriesOptions = defaultPlotOptions.line;
  1418. // set the default time methods
  1419. setTimeMethods();
  1420. /**
  1421. * Set the time methods globally based on the useUTC option. Time method can be either
  1422. * local time or UTC (default).
  1423. */
  1424. function setTimeMethods() {
  1425. var globalOptions = defaultOptions.global,
  1426. useUTC = globalOptions.useUTC,
  1427. GET = useUTC ? 'getUTC' : 'get',
  1428. SET = useUTC ? 'setUTC' : 'set';
  1429. Date = globalOptions.Date || window.Date;
  1430. timezoneOffset = useUTC && globalOptions.timezoneOffset;
  1431. getTimezoneOffset = useUTC && globalOptions.getTimezoneOffset;
  1432. makeTime = function (year, month, date, hours, minutes, seconds) {
  1433. var d;
  1434. if (useUTC) {
  1435. d = Date.UTC.apply(0, arguments);
  1436. d += getTZOffset(d);
  1437. } else {
  1438. d = new Date(
  1439. year,
  1440. month,
  1441. pick(date, 1),
  1442. pick(hours, 0),
  1443. pick(minutes, 0),
  1444. pick(seconds, 0)
  1445. ).getTime();
  1446. }
  1447. return d;
  1448. };
  1449. getMinutes = GET + 'Minutes';
  1450. getHours = GET + 'Hours';
  1451. getDay = GET + 'Day';
  1452. getDate = GET + 'Date';
  1453. getMonth = GET + 'Month';
  1454. getFullYear = GET + 'FullYear';
  1455. setMilliseconds = SET + 'Milliseconds';
  1456. setSeconds = SET + 'Seconds';
  1457. setMinutes = SET + 'Minutes';
  1458. setHours = SET + 'Hours';
  1459. setDate = SET + 'Date';
  1460. setMonth = SET + 'Month';
  1461. setFullYear = SET + 'FullYear';
  1462. }
  1463. /**
  1464. * Merge the default options with custom options and return the new options structure
  1465. * @param {Object} options The new custom options
  1466. */
  1467. function setOptions(options) {
  1468. // Copy in the default options
  1469. defaultOptions = merge(true, defaultOptions, options);
  1470. // Apply UTC
  1471. setTimeMethods();
  1472. return defaultOptions;
  1473. }
  1474. /**
  1475. * Get the updated default options. Until 3.0.7, merely exposing defaultOptions for outside modules
  1476. * wasn't enough because the setOptions method created a new object.
  1477. */
  1478. function getOptions() {
  1479. return defaultOptions;
  1480. }
  1481. /**
  1482. * Handle color operations. The object methods are chainable.
  1483. * @param {String} input The input color in either rbga or hex format
  1484. */
  1485. 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*\)/,
  1486. hexRegEx = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/,
  1487. rgbRegEx = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/;
  1488. var Color = function (input) {
  1489. // declare variables
  1490. var rgba = [], result, stops;
  1491. /**
  1492. * Parse the input color to rgba array
  1493. * @param {String} input
  1494. */
  1495. function init(input) {
  1496. // Gradients
  1497. if (input && input.stops) {
  1498. stops = map(input.stops, function (stop) {
  1499. return Color(stop[1]);
  1500. });
  1501. // Solid colors
  1502. } else {
  1503. // rgba
  1504. result = rgbaRegEx.exec(input);
  1505. if (result) {
  1506. rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)];
  1507. } else {
  1508. // hex
  1509. result = hexRegEx.exec(input);
  1510. if (result) {
  1511. rgba = [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1];
  1512. } else {
  1513. // rgb
  1514. result = rgbRegEx.exec(input);
  1515. if (result) {
  1516. rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1];
  1517. }
  1518. }
  1519. }
  1520. }
  1521. }
  1522. /**
  1523. * Return the color a specified format
  1524. * @param {String} format
  1525. */
  1526. function get(format) {
  1527. var ret;
  1528. if (stops) {
  1529. ret = merge(input);
  1530. ret.stops = [].concat(ret.stops);
  1531. each(stops, function (stop, i) {
  1532. ret.stops[i] = [ret.stops[i][0], stop.get(format)];
  1533. });
  1534. // it's NaN if gradient colors on a column chart
  1535. } else if (rgba && !isNaN(rgba[0])) {
  1536. if (format === 'rgb') {
  1537. ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')';
  1538. } else if (format === 'a') {
  1539. ret = rgba[3];
  1540. } else {
  1541. ret = 'rgba(' + rgba.join(',') + ')';
  1542. }
  1543. } else {
  1544. ret = input;
  1545. }
  1546. return ret;
  1547. }
  1548. /**
  1549. * Brighten the color
  1550. * @param {Number} alpha
  1551. */
  1552. function brighten(alpha) {
  1553. if (stops) {
  1554. each(stops, function (stop) {
  1555. stop.brighten(alpha);
  1556. });
  1557. } else if (isNumber(alpha) && alpha !== 0) {
  1558. var i;
  1559. for (i = 0; i < 3; i++) {
  1560. rgba[i] += pInt(alpha * 255);
  1561. if (rgba[i] < 0) {
  1562. rgba[i] = 0;
  1563. }
  1564. if (rgba[i] > 255) {
  1565. rgba[i] = 255;
  1566. }
  1567. }
  1568. }
  1569. return this;
  1570. }
  1571. /**
  1572. * Set the color's opacity to a given alpha value
  1573. * @param {Number} alpha
  1574. */
  1575. function setOpacity(alpha) {
  1576. rgba[3] = alpha;
  1577. return this;
  1578. }
  1579. // initialize: parse the input
  1580. init(input);
  1581. // public methods
  1582. return {
  1583. get: get,
  1584. brighten: brighten,
  1585. rgba: rgba,
  1586. setOpacity: setOpacity,
  1587. raw: input
  1588. };
  1589. };
  1590. /**
  1591. * A wrapper object for SVG elements
  1592. */
  1593. function SVGElement() {}
  1594. SVGElement.prototype = {
  1595. // Default base for animation
  1596. opacity: 1,
  1597. // For labels, these CSS properties are applied to the <text> node directly
  1598. textProps: ['fontSize', 'fontWeight', 'fontFamily', 'fontStyle', 'color',
  1599. 'lineHeight', 'width', 'textDecoration', 'textOverflow', 'textShadow'],
  1600. /**
  1601. * Initialize the SVG renderer
  1602. * @param {Object} renderer
  1603. * @param {String} nodeName
  1604. */
  1605. init: function (renderer, nodeName) {
  1606. var wrapper = this;
  1607. wrapper.element = nodeName === 'span' ?
  1608. createElement(nodeName) :
  1609. doc.createElementNS(SVG_NS, nodeName);
  1610. wrapper.renderer = renderer;
  1611. },
  1612. /**
  1613. * Animate a given attribute
  1614. * @param {Object} params
  1615. * @param {Number} options The same options as in jQuery animation
  1616. * @param {Function} complete Function to perform at the end of animation
  1617. */
  1618. animate: function (params, options, complete) {
  1619. var animOptions = pick(options, this.renderer.globalAnimation, true);
  1620. stop(this); // stop regardless of animation actually running, or reverting to .attr (#607)
  1621. if (animOptions) {
  1622. animOptions = merge(animOptions, {}); //#2625
  1623. if (complete) { // allows using a callback with the global animation without overwriting it
  1624. animOptions.complete = complete;
  1625. }
  1626. animate(this, params, animOptions);
  1627. } else {
  1628. this.attr(params, null, complete);
  1629. }
  1630. return this;
  1631. },
  1632. /**
  1633. * Build an SVG gradient out of a common JavaScript configuration object
  1634. */
  1635. colorGradient: function (color, prop, elem) {
  1636. var renderer = this.renderer,
  1637. colorObject,
  1638. gradName,
  1639. gradAttr,
  1640. radAttr,
  1641. gradients,
  1642. gradientObject,
  1643. stops,
  1644. stopColor,
  1645. stopOpacity,
  1646. radialReference,
  1647. n,
  1648. id,
  1649. key = [];
  1650. // Apply linear or radial gradients
  1651. if (color.linearGradient) {
  1652. gradName = 'linearGradient';
  1653. } else if (color.radialGradient) {
  1654. gradName = 'radialGradient';
  1655. }
  1656. if (gradName) {
  1657. gradAttr = color[gradName];
  1658. gradients = renderer.gradients;
  1659. stops = color.stops;
  1660. radialReference = elem.radialReference;
  1661. // Keep < 2.2 kompatibility
  1662. if (isArray(gradAttr)) {
  1663. color[gradName] = gradAttr = {
  1664. x1: gradAttr[0],
  1665. y1: gradAttr[1],
  1666. x2: gradAttr[2],
  1667. y2: gradAttr[3],
  1668. gradientUnits: 'userSpaceOnUse'
  1669. };
  1670. }
  1671. // Correct the radial gradient for the radial reference system
  1672. if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) {
  1673. radAttr = gradAttr; // Save the radial attributes for updating
  1674. gradAttr = merge(gradAttr,
  1675. renderer.getRadialAttr(radialReference, radAttr),
  1676. { gradientUnits: 'userSpaceOnUse' }
  1677. );
  1678. }
  1679. // Build the unique key to detect whether we need to create a new element (#1282)
  1680. for (n in gradAttr) {
  1681. if (n !== 'id') {
  1682. key.push(n, gradAttr[n]);
  1683. }
  1684. }
  1685. for (n in stops) {
  1686. key.push(stops[n]);
  1687. }
  1688. key = key.join(',');
  1689. // Check if a gradient object with the same config object is created within this renderer
  1690. if (gradients[key]) {
  1691. id = gradients[key].attr('id');
  1692. } else {
  1693. // Set the id and create the element
  1694. gradAttr.id = id = PREFIX + idCounter++;
  1695. gradients[key] = gradientObject = renderer.createElement(gradName)
  1696. .attr(gradAttr)
  1697. .add(renderer.defs);
  1698. gradientObject.radAttr = radAttr;
  1699. // The gradient needs to keep a list of stops to be able to destroy them
  1700. gradientObject.stops = [];
  1701. each(stops, function (stop) {
  1702. var stopObject;
  1703. if (stop[1].indexOf('rgba') === 0) {
  1704. colorObject = Color(stop[1]);
  1705. stopColor = colorObject.get('rgb');
  1706. stopOpacity = colorObject.get('a');
  1707. } else {
  1708. stopColor = stop[1];
  1709. stopOpacity = 1;
  1710. }
  1711. stopObject = renderer.createElement('stop').attr({
  1712. offset: stop[0],
  1713. 'stop-color': stopColor,
  1714. 'stop-opacity': stopOpacity
  1715. }).add(gradientObject);
  1716. // Add the stop element to the gradient
  1717. gradientObject.stops.push(stopObject);
  1718. });
  1719. }
  1720. // Set the reference to the gradient object
  1721. elem.setAttribute(prop, 'url(' + renderer.url + '#' + id + ')');
  1722. elem.gradient = key;
  1723. }
  1724. },
  1725. /**
  1726. * Apply a polyfill to the text-stroke CSS property, by copying the text element
  1727. * and apply strokes to the copy.
  1728. *
  1729. * Contrast checks at http://jsfiddle.net/highcharts/43soe9m1/2/
  1730. *
  1731. * docs: update default, document the polyfill and the limitations on hex colors and pixel values, document contrast pseudo-color
  1732. */
  1733. applyTextShadow: function (textShadow) {
  1734. var elem = this.element,
  1735. tspans,
  1736. hasContrast = textShadow.indexOf('contrast') !== -1,
  1737. styles = {},
  1738. forExport = this.renderer.forExport,
  1739. // IE10 and IE11 report textShadow in elem.style even though it doesn't work. Check
  1740. // this again with new IE release. In exports, the rendering is passed to PhantomJS.
  1741. supports = forExport || (elem.style.textShadow !== UNDEFINED && !isMS);
  1742. // When the text shadow is set to contrast, use dark stroke for light text and vice versa
  1743. if (hasContrast) {
  1744. styles.textShadow = textShadow = textShadow.replace(/contrast/g, this.renderer.getContrast(elem.style.fill));
  1745. }
  1746. // Safari with retina displays as well as PhantomJS bug (#3974). Firefox does not tolerate this,
  1747. // it removes the text shadows.
  1748. if (isWebKit || forExport) {
  1749. styles.textRendering = 'geometricPrecision';
  1750. }
  1751. /* Selective side-by-side testing in supported browser (http://jsfiddle.net/highcharts/73L1ptrh/)
  1752. if (elem.textContent.indexOf('2.') === 0) {
  1753. elem.style['text-shadow'] = 'none';
  1754. supports = false;
  1755. }
  1756. // */
  1757. // No reason to polyfill, we've got native support
  1758. if (supports) {
  1759. this.css(styles); // Apply altered textShadow or textRendering workaround
  1760. } else {
  1761. this.fakeTS = true; // Fake text shadow
  1762. // In order to get the right y position of the clones,
  1763. // copy over the y setter
  1764. this.ySetter = this.xSetter;
  1765. tspans = [].slice.call(elem.getElementsByTagName('tspan'));
  1766. each(textShadow.split(/\s?,\s?/g), function (textShadow) {
  1767. var firstChild = elem.firstChild,
  1768. color,
  1769. strokeWidth;
  1770. textShadow = textShadow.split(' ');
  1771. color = textShadow[textShadow.length - 1];
  1772. // Approximately tune the settings to the text-shadow behaviour
  1773. strokeWidth = textShadow[textShadow.length - 2];
  1774. if (strokeWidth) {
  1775. each(tspans, function (tspan, y) {
  1776. var clone;
  1777. // Let the first line start at the correct X position
  1778. if (y === 0) {
  1779. tspan.setAttribute('x', elem.getAttribute('x'));
  1780. y = elem.getAttribute('y');
  1781. tspan.setAttribute('y', y || 0);
  1782. if (y === null) {
  1783. elem.setAttribute('y', 0);
  1784. }
  1785. }
  1786. // Create the clone and apply shadow properties
  1787. clone = tspan.cloneNode(1);
  1788. attr(clone, {
  1789. 'class': PREFIX + 'text-shadow',
  1790. 'fill': color,
  1791. 'stroke': color,
  1792. 'stroke-opacity': 1 / mathMax(pInt(strokeWidth), 3),
  1793. 'stroke-width': strokeWidth,
  1794. 'stroke-linejoin': 'round'
  1795. });
  1796. elem.insertBefore(clone, firstChild);
  1797. });
  1798. }
  1799. });
  1800. }
  1801. },
  1802. /**
  1803. * Set or get a given attribute
  1804. * @param {Object|String} hash
  1805. * @param {Mixed|Undefined} val
  1806. */
  1807. attr: function (hash, val, complete) {
  1808. var key,
  1809. value,
  1810. element = this.element,
  1811. hasSetSymbolSize,
  1812. ret = this,
  1813. skipAttr;
  1814. // single key-value pair
  1815. if (typeof hash === 'string' && val !== UNDEFINED) {
  1816. key = hash;
  1817. hash = {};
  1818. hash[key] = val;
  1819. }
  1820. // used as a getter: first argument is a string, second is undefined
  1821. if (typeof hash === 'string') {
  1822. ret = (this[hash + 'Getter'] || this._defaultGetter).call(this, hash, element);
  1823. // setter
  1824. } else {
  1825. for (key in hash) {
  1826. value = hash[key];
  1827. skipAttr = false;
  1828. if (this.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) {
  1829. if (!hasSetSymbolSize) {
  1830. this.symbolAttr(hash);
  1831. hasSetSymbolSize = true;
  1832. }
  1833. skipAttr = true;
  1834. }
  1835. if (this.rotation && (key === 'x' || key === 'y')) {
  1836. this.doTransform = true;
  1837. }
  1838. if (!skipAttr) {
  1839. (this[key + 'Setter'] || this._defaultSetter).call(this, value, key, element);
  1840. }
  1841. // Let the shadow follow the main element
  1842. if (this.shadows && /^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(key)) {
  1843. this.updateShadows(key, value);
  1844. }
  1845. }
  1846. // Update transform. Do this outside the loop to prevent redundant updating for batch setting
  1847. // of attributes.
  1848. if (this.doTransform) {
  1849. this.updateTransform();
  1850. this.doTransform = false;
  1851. }
  1852. }
  1853. // In accordance with animate, run a complete callback
  1854. if (complete) {
  1855. complete();
  1856. }
  1857. return ret;
  1858. },
  1859. updateShadows: function (key, value) {
  1860. var shadows = this.shadows,
  1861. i = shadows.length;
  1862. while (i--) {
  1863. shadows[i].setAttribute(
  1864. key,
  1865. key === 'height' ?
  1866. mathMax(value - (shadows[i].cutHeight || 0), 0) :
  1867. key === 'd' ? this.d : value
  1868. );
  1869. }
  1870. },
  1871. /**
  1872. * Add a class name to an element
  1873. */
  1874. addClass: function (className) {
  1875. var element = this.element,
  1876. currentClassName = attr(element, 'class') || '';
  1877. if (currentClassName.indexOf(className) === -1) {
  1878. attr(element, 'class', currentClassName + ' ' + className);
  1879. }
  1880. return this;
  1881. },
  1882. /* hasClass and removeClass are not (yet) needed
  1883. hasClass: function (className) {
  1884. return attr(this.element, 'class').indexOf(className) !== -1;
  1885. },
  1886. removeClass: function (className) {
  1887. attr(this.element, 'class', attr(this.element, 'class').replace(className, ''));
  1888. return this;
  1889. },
  1890. */
  1891. /**
  1892. * If one of the symbol size affecting parameters are changed,
  1893. * check all the others only once for each call to an element's
  1894. * .attr() method
  1895. * @param {Object} hash
  1896. */
  1897. symbolAttr: function (hash) {
  1898. var wrapper = this;
  1899. each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function (key) {
  1900. wrapper[key] = pick(hash[key], wrapper[key]);
  1901. });
  1902. wrapper.attr({
  1903. d: wrapper.renderer.symbols[wrapper.symbolName](
  1904. wrapper.x,
  1905. wrapper.y,
  1906. wrapper.width,
  1907. wrapper.height,
  1908. wrapper
  1909. )
  1910. });
  1911. },
  1912. /**
  1913. * Apply a clipping path to this object
  1914. * @param {String} id
  1915. */
  1916. clip: function (clipRect) {
  1917. return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : NONE);
  1918. },
  1919. /**
  1920. * Calculate the coordinates needed for drawing a rectangle crisply and return the
  1921. * calculated attributes
  1922. * @param {Number} strokeWidth
  1923. * @param {Number} x
  1924. * @param {Number} y
  1925. * @param {Number} width
  1926. * @param {Number} height
  1927. */
  1928. crisp: function (rect) {
  1929. var wrapper = this,
  1930. key,
  1931. attribs = {},
  1932. normalizer,
  1933. strokeWidth = rect.strokeWidth || wrapper.strokeWidth || 0;
  1934. normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors
  1935. // normalize for crisp edges
  1936. rect.x = mathFloor(rect.x || wrapper.x || 0) + normalizer;
  1937. rect.y = mathFloor(rect.y || wrapper.y || 0) + normalizer;
  1938. rect.width = mathFloor((rect.width || wrapper.width || 0) - 2 * normalizer);
  1939. rect.height = mathFloor((rect.height || wrapper.height || 0) - 2 * normalizer);
  1940. rect.strokeWidth = strokeWidth;
  1941. for (key in rect) {
  1942. if (wrapper[key] !== rect[key]) { // only set attribute if changed
  1943. wrapper[key] = attribs[key] = rect[key];
  1944. }
  1945. }
  1946. return attribs;
  1947. },
  1948. /**
  1949. * Set styles for the element
  1950. * @param {Object} styles
  1951. */
  1952. css: function (styles) {
  1953. var elemWrapper = this,
  1954. oldStyles = elemWrapper.styles,
  1955. newStyles = {},
  1956. elem = elemWrapper.element,
  1957. textWidth,
  1958. n,
  1959. serializedCss = '',
  1960. hyphenate,
  1961. hasNew = !oldStyles;
  1962. // convert legacy
  1963. if (styles && styles.color) {
  1964. styles.fill = styles.color;
  1965. }
  1966. // Filter out existing styles to increase performance (#2640)
  1967. if (oldStyles) {
  1968. for (n in styles) {
  1969. if (styles[n] !== oldStyles[n]) {
  1970. newStyles[n] = styles[n];
  1971. hasNew = true;
  1972. }
  1973. }
  1974. }
  1975. if (hasNew) {
  1976. textWidth = elemWrapper.textWidth =
  1977. (styles && styles.width && elem.nodeName.toLowerCase() === 'text' && pInt(styles.width)) ||
  1978. elemWrapper.textWidth; // #3501
  1979. // Merge the new styles with the old ones
  1980. if (oldStyles) {
  1981. styles = extend(
  1982. oldStyles,
  1983. newStyles
  1984. );
  1985. }
  1986. // store object
  1987. elemWrapper.styles = styles;
  1988. if (textWidth && (useCanVG || (!hasSVG && elemWrapper.renderer.forExport))) {
  1989. delete styles.width;
  1990. }
  1991. // serialize and set style attribute
  1992. if (isMS && !hasSVG) {
  1993. css(elemWrapper.element, styles);
  1994. } else {
  1995. /*jslint unparam: true*/
  1996. hyphenate = function (a, b) { return '-' + b.toLowerCase(); };
  1997. /*jslint unparam: false*/
  1998. for (n in styles) {
  1999. serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';';
  2000. }
  2001. attr(elem, 'style', serializedCss); // #1881
  2002. }
  2003. // re-build text
  2004. if (textWidth && elemWrapper.added) {
  2005. elemWrapper.renderer.buildText(elemWrapper);
  2006. }
  2007. }
  2008. return elemWrapper;
  2009. },
  2010. /**
  2011. * Add an event listener
  2012. * @param {String} eventType
  2013. * @param {Function} handler
  2014. */
  2015. on: function (eventType, handler) {
  2016. var svgElement = this,
  2017. element = svgElement.element;
  2018. // touch
  2019. if (hasTouch && eventType === 'click') {
  2020. element.ontouchstart = function (e) {
  2021. svgElement.touchEventFired = Date.now();
  2022. e.preventDefault();
  2023. handler.call(element, e);
  2024. };
  2025. element.onclick = function (e) {
  2026. if (userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { // #2269
  2027. handler.call(element, e);
  2028. }
  2029. };
  2030. } else {
  2031. // simplest possible event model for internal use
  2032. element['on' + eventType] = handler;
  2033. }
  2034. return this;
  2035. },
  2036. /**
  2037. * Set the coordinates needed to draw a consistent radial gradient across
  2038. * pie slices regardless of positioning inside the chart. The format is
  2039. * [centerX, centerY, diameter] in pixels.
  2040. */
  2041. setRadialReference: function (coordinates) {
  2042. var existingGradient = this.renderer.gradients[this.element.gradient];
  2043. this.element.radialReference = coordinates;
  2044. // On redrawing objects with an existing gradient, the gradient needs
  2045. // to be repositioned (#3801)
  2046. if (existingGradient && existingGradient.radAttr) {
  2047. existingGradient.animate(
  2048. this.renderer.getRadialAttr(
  2049. coordinates,
  2050. existingGradient.radAttr
  2051. )
  2052. );
  2053. }
  2054. return this;
  2055. },
  2056. /**
  2057. * Move an object and its children by x and y values
  2058. * @param {Number} x
  2059. * @param {Number} y
  2060. */
  2061. translate: function (x, y) {
  2062. return this.attr({
  2063. translateX: x,
  2064. translateY: y
  2065. });
  2066. },
  2067. /**
  2068. * Invert a group, rotate and flip
  2069. */
  2070. invert: function () {
  2071. var wrapper = this;
  2072. wrapper.inverted = true;
  2073. wrapper.updateTransform();
  2074. return wrapper;
  2075. },
  2076. /**
  2077. * Private method to update the transform attribute based on internal
  2078. * properties
  2079. */
  2080. updateTransform: function () {
  2081. var wrapper = this,
  2082. translateX = wrapper.translateX || 0,
  2083. translateY = wrapper.translateY || 0,
  2084. scaleX = wrapper.scaleX,
  2085. scaleY = wrapper.scaleY,
  2086. inverted = wrapper.inverted,
  2087. rotation = wrapper.rotation,
  2088. element = wrapper.element,
  2089. transform;
  2090. // flipping affects translate as adjustment for flipping around the group's axis
  2091. if (inverted) {
  2092. translateX += wrapper.attr('width');
  2093. translateY += wrapper.attr('height');
  2094. }
  2095. // Apply translate. Nearly all transformed elements have translation, so instead
  2096. // of checking for translate = 0, do it always (#1767, #1846).
  2097. transform = ['translate(' + translateX + ',' + translateY + ')'];
  2098. // apply rotation
  2099. if (inverted) {
  2100. transform.push('rotate(90) scale(-1,1)');
  2101. } else if (rotation) { // text rotation
  2102. transform.push('rotate(' + rotation + ' ' + (element.getAttribute('x') || 0) + ' ' + (element.getAttribute('y') || 0) + ')');
  2103. // Delete bBox memo when the rotation changes
  2104. //delete wrapper.bBox;
  2105. }
  2106. // apply scale
  2107. if (defined(scaleX) || defined(scaleY)) {
  2108. transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')');
  2109. }
  2110. if (transform.length) {
  2111. element.setAttribute('transform', transform.join(' '));
  2112. }
  2113. },
  2114. /**
  2115. * Bring the element to the front
  2116. */
  2117. toFront: function () {
  2118. var element = this.element;
  2119. element.parentNode.appendChild(element);
  2120. return this;
  2121. },
  2122. /**
  2123. * Break down alignment options like align, verticalAlign, x and y
  2124. * to x and y relative to the chart.
  2125. *
  2126. * @param {Object} alignOptions
  2127. * @param {Boolean} alignByTranslate
  2128. * @param {String[Object} box The box to align to, needs a width and height. When the
  2129. * box is a string, it refers to an object in the Renderer. For example, when
  2130. * box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height
  2131. * x and y properties.
  2132. *
  2133. */
  2134. align: function (alignOptions, alignByTranslate, box) {
  2135. var align,
  2136. vAlign,
  2137. x,
  2138. y,
  2139. attribs = {},
  2140. alignTo,
  2141. renderer = this.renderer,
  2142. alignedObjects = renderer.alignedObjects;
  2143. // First call on instanciate
  2144. if (alignOptions) {
  2145. this.alignOptions = alignOptions;
  2146. this.alignByTranslate = alignByTranslate;
  2147. if (!box || isString(box)) { // boxes other than renderer handle this internally
  2148. this.alignTo = alignTo = box || 'renderer';
  2149. erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize
  2150. alignedObjects.push(this);
  2151. box = null; // reassign it below
  2152. }
  2153. // When called on resize, no arguments are supplied
  2154. } else {
  2155. alignOptions = this.alignOptions;
  2156. alignByTranslate = this.alignByTranslate;
  2157. alignTo = this.alignTo;
  2158. }
  2159. box = pick(box, renderer[alignTo], renderer);
  2160. // Assign variables
  2161. align = alignOptions.align;
  2162. vAlign = alignOptions.verticalAlign;
  2163. x = (box.x || 0) + (alignOptions.x || 0); // default: left align
  2164. y = (box.y || 0) + (alignOptions.y || 0); // default: top align
  2165. // Align
  2166. if (align === 'right' || align === 'center') {
  2167. x += (box.width - (alignOptions.width || 0)) /
  2168. { right: 1, center: 2 }[align];
  2169. }
  2170. attribs[alignByTranslate ? 'translateX' : 'x'] = mathRound(x);
  2171. // Vertical align
  2172. if (vAlign === 'bottom' || vAlign === 'middle') {
  2173. y += (box.height - (alignOptions.height || 0)) /
  2174. ({ bottom: 1, middle: 2 }[vAlign] || 1);
  2175. }
  2176. attribs[alignByTranslate ? 'translateY' : 'y'] = mathRound(y);
  2177. // Animate only if already placed
  2178. this[this.placed ? 'animate' : 'attr'](attribs);
  2179. this.placed = true;
  2180. this.alignAttr = attribs;
  2181. return this;
  2182. },
  2183. /**
  2184. * Get the bounding box (width, height, x and y) for the element
  2185. */
  2186. getBBox: function (reload) {
  2187. var wrapper = this,
  2188. bBox,// = wrapper.bBox,
  2189. renderer = wrapper.renderer,
  2190. width,
  2191. height,
  2192. rotation = wrapper.rotation,
  2193. element = wrapper.element,
  2194. styles = wrapper.styles,
  2195. rad = rotation * deg2rad,
  2196. textStr = wrapper.textStr,
  2197. textShadow,
  2198. elemStyle = element.style,
  2199. toggleTextShadowShim,
  2200. cacheKey;
  2201. if (textStr !== UNDEFINED) {
  2202. // Properties that affect bounding box
  2203. cacheKey = ['', rotation || 0, styles && styles.fontSize, element.style.width].join(',');
  2204. // Since numbers are monospaced, and numerical labels appear a lot in a chart,
  2205. // we assume that a label of n characters has the same bounding box as others
  2206. // of the same length.
  2207. if (textStr === '' || numRegex.test(textStr)) {
  2208. cacheKey = 'num:' + textStr.toString().length + cacheKey;
  2209. // Caching all strings reduces rendering time by 4-5%.
  2210. } else {
  2211. cacheKey = textStr + cacheKey;
  2212. }
  2213. }
  2214. if (cacheKey && !reload) {
  2215. bBox = renderer.cache[cacheKey];
  2216. }
  2217. // No cache found
  2218. if (!bBox) {
  2219. // SVG elements
  2220. if (element.namespaceURI === SVG_NS || renderer.forExport) {
  2221. try { // Fails in Firefox if the container has display: none.
  2222. // When the text shadow shim is used, we need to hide the fake shadows
  2223. // to get the correct bounding box (#3872)
  2224. toggleTextShadowShim = this.fakeTS && function (display) {
  2225. each(element.querySelectorAll('.' + PREFIX + 'text-shadow'), function (tspan) {
  2226. tspan.style.display = display;
  2227. });
  2228. };
  2229. // Workaround for #3842, Firefox reporting wrong bounding box for shadows
  2230. if (isFirefox && elemStyle.textShadow) {
  2231. textShadow = elemStyle.textShadow;
  2232. elemStyle.textShadow = '';
  2233. } else if (toggleTextShadowShim) {
  2234. toggleTextShadowShim(NONE);
  2235. }
  2236. bBox = element.getBBox ?
  2237. // SVG: use extend because IE9 is not allowed to change width and height in case
  2238. // of rotation (below)
  2239. extend({}, element.getBBox()) :
  2240. // Canvas renderer and legacy IE in export mode
  2241. {
  2242. width: element.offsetWidth,
  2243. height: element.offsetHeight
  2244. };
  2245. // #3842
  2246. if (textShadow) {
  2247. elemStyle.textShadow = textShadow;
  2248. } else if (toggleTextShadowShim) {
  2249. toggleTextShadowShim('');
  2250. }
  2251. } catch (e) {}
  2252. // If the bBox is not set, the try-catch block above failed. The other condition
  2253. // is for Opera that returns a width of -Infinity on hidden elements.
  2254. if (!bBox || bBox.width < 0) {
  2255. bBox = { width: 0, height: 0 };
  2256. }
  2257. // VML Renderer or useHTML within SVG
  2258. } else {
  2259. bBox = wrapper.htmlGetBBox();
  2260. }
  2261. // True SVG elements as well as HTML elements in modern browsers using the .useHTML option
  2262. // need to compensated for rotation
  2263. if (renderer.isSVG) {
  2264. width = bBox.width;
  2265. height = bBox.height;
  2266. // Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669, #2568)
  2267. if (isMS && styles && styles.fontSize === '11px' && height.toPrecision(3) === '16.9') {
  2268. bBox.height = height = 14;
  2269. }
  2270. // Adjust for rotated text
  2271. if (rotation) {
  2272. bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad));
  2273. bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad));
  2274. }
  2275. }
  2276. // Cache it
  2277. if (cacheKey) {
  2278. renderer.cache[cacheKey] = bBox;
  2279. }
  2280. }
  2281. return bBox;
  2282. },
  2283. /**
  2284. * Show the element
  2285. */
  2286. show: function (inherit) {
  2287. return this.attr({ visibility: inherit ? 'inherit' : VISIBLE });
  2288. },
  2289. /**
  2290. * Hide the element
  2291. */
  2292. hide: function () {
  2293. return this.attr({ visibility: HIDDEN });
  2294. },
  2295. fadeOut: function (duration) {
  2296. var elemWrapper = this;
  2297. elemWrapper.animate({
  2298. opacity: 0
  2299. }, {
  2300. duration: duration || 150,
  2301. complete: function () {
  2302. elemWrapper.attr({ y: -9999 }); // #3088, assuming we're only using this for tooltips
  2303. }
  2304. });
  2305. },
  2306. /**
  2307. * Add the element
  2308. * @param {Object|Undefined} parent Can be an element, an element wrapper or undefined
  2309. * to append the element to the renderer.box.
  2310. */
  2311. add: function (parent) {
  2312. var renderer = this.renderer,
  2313. element = this.element,
  2314. inserted;
  2315. if (parent) {
  2316. this.parentGroup = parent;
  2317. }
  2318. // mark as inverted
  2319. this.parentInverted = parent && parent.inverted;
  2320. // build formatted text
  2321. if (this.textStr !== undefined) {
  2322. renderer.buildText(this);
  2323. }
  2324. // Mark as added
  2325. this.added = true;
  2326. // If we're adding to renderer root, or other elements in the group
  2327. // have a z index, we need to handle it
  2328. if (!parent || parent.handleZ || this.zIndex) {
  2329. inserted = this.zIndexSetter();
  2330. }
  2331. // If zIndex is not handled, append at the end
  2332. if (!inserted) {
  2333. (parent ? parent.element : renderer.box).appendChild(element);
  2334. }
  2335. // fire an event for internal hooks
  2336. if (this.onAdd) {
  2337. this.onAdd();
  2338. }
  2339. return this;
  2340. },
  2341. /**
  2342. * Removes a child either by removeChild or move to garbageBin.
  2343. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not.
  2344. */
  2345. safeRemoveChild: function (element) {
  2346. var parentNode = element.parentNode;
  2347. if (parentNode) {
  2348. parentNode.removeChild(element);
  2349. }
  2350. },
  2351. /**
  2352. * Destroy the element and element wrapper
  2353. */
  2354. destroy: function () {
  2355. var wrapper = this,
  2356. element = wrapper.element || {},
  2357. shadows = wrapper.shadows,
  2358. parentToClean = wrapper.renderer.isSVG && element.nodeName === 'SPAN' && wrapper.parentGroup,
  2359. grandParent,
  2360. key,
  2361. i;
  2362. // remove events
  2363. element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null;
  2364. stop(wrapper); // stop running animations
  2365. if (wrapper.clipPath) {
  2366. wrapper.clipPath = wrapper.clipPath.destroy();
  2367. }
  2368. // Destroy stops in case this is a gradient object
  2369. if (wrapper.stops) {
  2370. for (i = 0; i < wrapper.stops.length; i++) {
  2371. wrapper.stops[i] = wrapper.stops[i].destroy();
  2372. }
  2373. wrapper.stops = null;
  2374. }
  2375. // remove element
  2376. wrapper.safeRemoveChild(element);
  2377. // destroy shadows
  2378. if (shadows) {
  2379. each(shadows, function (shadow) {
  2380. wrapper.safeRemoveChild(shadow);
  2381. });
  2382. }
  2383. // In case of useHTML, clean up empty containers emulating SVG groups (#1960, #2393, #2697).
  2384. while (parentToClean && parentToClean.div && parentToClean.div.childNodes.length === 0) {
  2385. grandParent = parentToClean.parentGroup;
  2386. wrapper.safeRemoveChild(parentToClean.div);
  2387. delete parentToClean.div;
  2388. parentToClean = grandParent;
  2389. }
  2390. // remove from alignObjects
  2391. if (wrapper.alignTo) {
  2392. erase(wrapper.renderer.alignedObjects, wrapper);
  2393. }
  2394. for (key in wrapper) {
  2395. delete wrapper[key];
  2396. }
  2397. return null;
  2398. },
  2399. /**
  2400. * Add a shadow to the element. Must be done after the element is added to the DOM
  2401. * @param {Boolean|Object} shadowOptions
  2402. */
  2403. shadow: function (shadowOptions, group, cutOff) {
  2404. var shadows = [],
  2405. i,
  2406. shadow,
  2407. element = this.element,
  2408. strokeWidth,
  2409. shadowWidth,
  2410. shadowElementOpacity,
  2411. // compensate for inverted plot area
  2412. transform;
  2413. if (shadowOptions) {
  2414. shadowWidth = pick(shadowOptions.width, 3);
  2415. shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth;
  2416. transform = this.parentInverted ?
  2417. '(-1,-1)' :
  2418. '(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')';
  2419. for (i = 1; i <= shadowWidth; i++) {
  2420. shadow = element.cloneNode(0);
  2421. strokeWidth = (shadowWidth * 2) + 1 - (2 * i);
  2422. attr(shadow, {
  2423. 'isShadow': 'true',
  2424. 'stroke': shadowOptions.color || 'black',
  2425. 'stroke-opacity': shadowElementOpacity * i,
  2426. 'stroke-width': strokeWidth,
  2427. 'transform': 'translate' + transform,
  2428. 'fill': NONE
  2429. });
  2430. if (cutOff) {
  2431. attr(shadow, 'height', mathMax(attr(shadow, 'height') - strokeWidth, 0));
  2432. shadow.cutHeight = strokeWidth;
  2433. }
  2434. if (group) {
  2435. group.element.appendChild(shadow);
  2436. } else {
  2437. element.parentNode.insertBefore(shadow, element);
  2438. }
  2439. shadows.push(shadow);
  2440. }
  2441. this.shadows = shadows;
  2442. }
  2443. return this;
  2444. },
  2445. xGetter: function (key) {
  2446. if (this.element.nodeName === 'circle') {
  2447. key = { x: 'cx', y: 'cy' }[key] || key;
  2448. }
  2449. return this._defaultGetter(key);
  2450. },
  2451. /**
  2452. * Get the current value of an attribute or pseudo attribute, used mainly
  2453. * for animation.
  2454. */
  2455. _defaultGetter: function (key) {
  2456. var ret = pick(this[key], this.element ? this.element.getAttribute(key) : null, 0);
  2457. if (/^[\-0-9\.]+$/.test(ret)) { // is numerical
  2458. ret = parseFloat(ret);
  2459. }
  2460. return ret;
  2461. },
  2462. dSetter: function (value, key, element) {
  2463. if (value && value.join) { // join path
  2464. value = value.join(' ');
  2465. }
  2466. if (/(NaN| {2}|^$)/.test(value)) {
  2467. value = 'M 0 0';
  2468. }
  2469. element.setAttribute(key, value);
  2470. this[key] = value;
  2471. },
  2472. dashstyleSetter: function (value) {
  2473. var i;
  2474. value = value && value.toLowerCase();
  2475. if (value) {
  2476. value = value
  2477. .replace('shortdashdotdot', '3,1,1,1,1,1,')
  2478. .replace('shortdashdot', '3,1,1,1')
  2479. .replace('shortdot', '1,1,')
  2480. .replace('shortdash', '3,1,')
  2481. .replace('longdash', '8,3,')
  2482. .replace(/dot/g, '1,3,')
  2483. .replace('dash', '4,3,')
  2484. .replace(/,$/, '')
  2485. .split(','); // ending comma
  2486. i = value.length;
  2487. while (i--) {
  2488. value[i] = pInt(value[i]) * this['stroke-width'];
  2489. }
  2490. value = value.join(',')
  2491. .replace('NaN', 'none'); // #3226
  2492. this.element.setAttribute('stroke-dasharray', value);
  2493. }
  2494. },
  2495. alignSetter: function (value) {
  2496. this.element.setAttribute('text-anchor', { left: 'start', center: 'middle', right: 'end' }[value]);
  2497. },
  2498. opacitySetter: function (value, key, element) {
  2499. this[key] = value;
  2500. element.setAttribute(key, value);
  2501. },
  2502. titleSetter: function (value) {
  2503. var titleNode = this.element.getElementsByTagName('title')[0];
  2504. if (!titleNode) {
  2505. titleNode = doc.createElementNS(SVG_NS, 'title');
  2506. this.element.appendChild(titleNode);
  2507. }
  2508. titleNode.appendChild(
  2509. doc.createTextNode(
  2510. (String(pick(value), '')).replace(/<[^>]*>/g, '') // #3276, #3895
  2511. )
  2512. );
  2513. },
  2514. textSetter: function (value) {
  2515. if (value !== this.textStr) {
  2516. // Delete bBox memo when the text changes
  2517. delete this.bBox;
  2518. this.textStr = value;
  2519. if (this.added) {
  2520. this.renderer.buildText(this);
  2521. }
  2522. }
  2523. },
  2524. fillSetter: function (value, key, element) {
  2525. if (typeof value === 'string') {
  2526. element.setAttribute(key, value);
  2527. } else if (value) {
  2528. this.colorGradient(value, key, element);
  2529. }
  2530. },
  2531. visibilitySetter: function (value, key, element) {
  2532. // IE9-11 doesn't handle visibilty:inherit well, so we remove the attribute instead (#2881, #3909)
  2533. if (value === 'inherit') {
  2534. element.removeAttribute(key);
  2535. } else {
  2536. element.setAttribute(key, value);
  2537. }
  2538. },
  2539. zIndexSetter: function (value, key) {
  2540. var renderer = this.renderer,
  2541. parentGroup = this.parentGroup,
  2542. parentWrapper = parentGroup || renderer,
  2543. parentNode = parentWrapper.element || renderer.box,
  2544. childNodes,
  2545. otherElement,
  2546. otherZIndex,
  2547. element = this.element,
  2548. inserted,
  2549. run = this.added,
  2550. i;
  2551. if (defined(value)) {
  2552. element.setAttribute(key, value); // So we can read it for other elements in the group
  2553. value = +value;
  2554. if (this[key] === value) { // Only update when needed (#3865)
  2555. run = false;
  2556. }
  2557. this[key] = value;
  2558. }
  2559. // Insert according to this and other elements' zIndex. Before .add() is called,
  2560. // nothing is done. Then on add, or by later calls to zIndexSetter, the node
  2561. // is placed on the right place in the DOM.
  2562. if (run) {
  2563. value = this.zIndex;
  2564. if (value && parentGroup) {
  2565. parentGroup.handleZ = true;
  2566. }
  2567. childNodes = parentNode.childNodes;
  2568. for (i = 0; i < childNodes.length && !inserted; i++) {
  2569. otherElement = childNodes[i];
  2570. otherZIndex = attr(otherElement, 'zIndex');
  2571. if (otherElement !== element && (
  2572. // Insert before the first element with a higher zIndex
  2573. pInt(otherZIndex) > value ||
  2574. // If no zIndex given, insert before the first element with a zIndex
  2575. (!defined(value) && defined(otherZIndex))
  2576. )) {
  2577. parentNode.insertBefore(element, otherElement);
  2578. inserted = true;
  2579. }
  2580. }
  2581. if (!inserted) {
  2582. parentNode.appendChild(element);
  2583. }
  2584. }
  2585. return inserted;
  2586. },
  2587. _defaultSetter: function (value, key, element) {
  2588. element.setAttribute(key, value);
  2589. }
  2590. };
  2591. // Some shared setters and getters
  2592. SVGElement.prototype.yGetter = SVGElement.prototype.xGetter;
  2593. SVGElement.prototype.translateXSetter = SVGElement.prototype.translateYSetter =
  2594. SVGElement.prototype.rotationSetter = SVGElement.prototype.verticalAlignSetter =
  2595. SVGElement.prototype.scaleXSetter = SVGElement.prototype.scaleYSetter = function (value, key) {
  2596. this[key] = value;
  2597. this.doTransform = true;
  2598. };
  2599. // WebKit and Batik have problems with a stroke-width of zero, so in this case we remove the
  2600. // stroke attribute altogether. #1270, #1369, #3065, #3072.
  2601. SVGElement.prototype['stroke-widthSetter'] = SVGElement.prototype.strokeSetter = function (value, key, element) {
  2602. this[key] = value;
  2603. // Only apply the stroke attribute if the stroke width is defined and larger than 0
  2604. if (this.stroke && this['stroke-width']) {
  2605. this.strokeWidth = this['stroke-width'];
  2606. SVGElement.prototype.fillSetter.call(this, this.stroke, 'stroke', element); // use prototype as instance may be overridden
  2607. element.setAttribute('stroke-width', this['stroke-width']);
  2608. this.hasStroke = true;
  2609. } else if (key === 'stroke-width' && value === 0 && this.hasStroke) {
  2610. element.removeAttribute('stroke');
  2611. this.hasStroke = false;
  2612. }
  2613. };
  2614. /**
  2615. * The default SVG renderer
  2616. */
  2617. var SVGRenderer = function () {
  2618. this.init.apply(this, arguments);
  2619. };
  2620. SVGRenderer.prototype = {
  2621. Element: SVGElement,
  2622. /**
  2623. * Initialize the SVGRenderer
  2624. * @param {Object} container
  2625. * @param {Number} width
  2626. * @param {Number} height
  2627. * @param {Boolean} forExport
  2628. */
  2629. init: function (container, width, height, style, forExport, allowHTML) {
  2630. var renderer = this,
  2631. loc = location,
  2632. boxWrapper,
  2633. element,
  2634. desc;
  2635. boxWrapper = renderer.createElement('svg')
  2636. .attr({
  2637. version: '1.1'
  2638. })
  2639. .css(this.getStyle(style));
  2640. element = boxWrapper.element;
  2641. container.appendChild(element);
  2642. // For browsers other than IE, add the namespace attribute (#1978)
  2643. if (container.innerHTML.indexOf('xmlns') === -1) {
  2644. attr(element, 'xmlns', SVG_NS);
  2645. }
  2646. // object properties
  2647. renderer.isSVG = true;
  2648. renderer.box = element;
  2649. renderer.boxWrapper = boxWrapper;
  2650. renderer.alignedObjects = [];
  2651. // Page url used for internal references. #24, #672, #1070
  2652. renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ?
  2653. loc.href
  2654. .replace(/#.*?$/, '') // remove the hash
  2655. .replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes
  2656. .replace(/ /g, '%20') : // replace spaces (needed for Safari only)
  2657. '';
  2658. // Add description
  2659. desc = this.createElement('desc').add();
  2660. desc.element.appendChild(doc.createTextNode('Created with ' + PRODUCT + ' ' + VERSION));
  2661. renderer.defs = this.createElement('defs').add();
  2662. renderer.allowHTML = allowHTML;
  2663. renderer.forExport = forExport;
  2664. renderer.gradients = {}; // Object where gradient SvgElements are stored
  2665. renderer.cache = {}; // Cache for numerical bounding boxes
  2666. renderer.setSize(width, height, false);
  2667. // Issue 110 workaround:
  2668. // In Firefox, if a div is positioned by percentage, its pixel position may land
  2669. // between pixels. The container itself doesn't display this, but an SVG element
  2670. // inside this container will be drawn at subpixel precision. In order to draw
  2671. // sharp lines, this must be compensated for. This doesn't seem to work inside
  2672. // iframes though (like in jsFiddle).
  2673. var subPixelFix, rect;
  2674. if (isFirefox && container.getBoundingClientRect) {
  2675. renderer.subPixelFix = subPixelFix = function () {
  2676. css(container, { left: 0, top: 0 });
  2677. rect = container.getBoundingClientRect();
  2678. css(container, {
  2679. left: (mathCeil(rect.left) - rect.left) + PX,
  2680. top: (mathCeil(rect.top) - rect.top) + PX
  2681. });
  2682. };
  2683. // run the fix now
  2684. subPixelFix();
  2685. // run it on resize
  2686. addEvent(win, 'resize', subPixelFix);
  2687. }
  2688. },
  2689. getStyle: function (style) {
  2690. return (this.style = extend({
  2691. fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif', // default font
  2692. fontSize: '12px'
  2693. }, style));
  2694. },
  2695. /**
  2696. * Detect whether the renderer is hidden. This happens when one of the parent elements
  2697. * has display: none. #608.
  2698. */
  2699. isHidden: function () {
  2700. return !this.boxWrapper.getBBox().width;
  2701. },
  2702. /**
  2703. * Destroys the renderer and its allocated members.
  2704. */
  2705. destroy: function () {
  2706. var renderer = this,
  2707. rendererDefs = renderer.defs;
  2708. renderer.box = null;
  2709. renderer.boxWrapper = renderer.boxWrapper.destroy();
  2710. // Call destroy on all gradient elements
  2711. destroyObjectProperties(renderer.gradients || {});
  2712. renderer.gradients = null;
  2713. // Defs are null in VMLRenderer
  2714. // Otherwise, destroy them here.
  2715. if (rendererDefs) {
  2716. renderer.defs = rendererDefs.destroy();
  2717. }
  2718. // Remove sub pixel fix handler
  2719. // We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed
  2720. // See issue #982
  2721. if (renderer.subPixelFix) {
  2722. removeEvent(win, 'resize', renderer.subPixelFix);
  2723. }
  2724. renderer.alignedObjects = null;
  2725. return null;
  2726. },
  2727. /**
  2728. * Create a wrapper for an SVG element
  2729. * @param {Object} nodeName
  2730. */
  2731. createElement: function (nodeName) {
  2732. var wrapper = new this.Element();
  2733. wrapper.init(this, nodeName);
  2734. return wrapper;
  2735. },
  2736. /**
  2737. * Dummy function for use in canvas renderer
  2738. */
  2739. draw: function () {},
  2740. /**
  2741. * Get converted radial gradient attributes
  2742. */
  2743. getRadialAttr: function (radialReference, gradAttr) {
  2744. return {
  2745. cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2],
  2746. cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2],
  2747. r: gradAttr.r * radialReference[2]
  2748. };
  2749. },
  2750. /**
  2751. * Parse a simple HTML string into SVG tspans
  2752. *
  2753. * @param {Object} textNode The parent text SVG node
  2754. */
  2755. buildText: function (wrapper) {
  2756. var textNode = wrapper.element,
  2757. renderer = this,
  2758. forExport = renderer.forExport,
  2759. textStr = pick(wrapper.textStr, '').toString(),
  2760. hasMarkup = textStr.indexOf('<') !== -1,
  2761. lines,
  2762. childNodes = textNode.childNodes,
  2763. styleRegex,
  2764. hrefRegex,
  2765. parentX = attr(textNode, 'x'),
  2766. textStyles = wrapper.styles,
  2767. width = wrapper.textWidth,
  2768. textLineHeight = textStyles && textStyles.lineHeight,
  2769. textShadow = textStyles && textStyles.textShadow,
  2770. ellipsis = textStyles && textStyles.textOverflow === 'ellipsis',
  2771. i = childNodes.length,
  2772. tempParent = width && !wrapper.added && this.box,
  2773. getLineHeight = function (tspan) {
  2774. return textLineHeight ?
  2775. pInt(textLineHeight) :
  2776. renderer.fontMetrics(
  2777. /(px|em)$/.test(tspan && tspan.style.fontSize) ?
  2778. tspan.style.fontSize :
  2779. ((textStyles && textStyles.fontSize) || renderer.style.fontSize || 12),
  2780. tspan
  2781. ).h;
  2782. },
  2783. unescapeAngleBrackets = function (inputStr) {
  2784. return inputStr.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
  2785. };
  2786. /// remove old text
  2787. while (i--) {
  2788. textNode.removeChild(childNodes[i]);
  2789. }
  2790. // Skip tspans, add text directly to text node. The forceTSpan is a hook
  2791. // used in text outline hack.
  2792. if (!hasMarkup && !textShadow && !ellipsis && textStr.indexOf(' ') === -1) {
  2793. textNode.appendChild(doc.createTextNode(unescapeAngleBrackets(textStr)));
  2794. return;
  2795. // Complex strings, add more logic
  2796. } else {
  2797. styleRegex = /<.*style="([^"]+)".*>/;
  2798. hrefRegex = /<.*href="(http[^"]+)".*>/;
  2799. if (tempParent) {
  2800. tempParent.appendChild(textNode); // attach it to the DOM to read offset width
  2801. }
  2802. if (hasMarkup) {
  2803. lines = textStr
  2804. .replace(/<(b|strong)>/g, '<span style="font-weight:bold">')
  2805. .replace(/<(i|em)>/g, '<span style="font-style:italic">')
  2806. .replace(/<a/g, '<span')
  2807. .replace(/<\/(b|strong|i|em|a)>/g, '</span>')
  2808. .split(/<br.*?>/g);
  2809. } else {
  2810. lines = [textStr];
  2811. }
  2812. // remove empty line at end
  2813. if (lines[lines.length - 1] === '') {
  2814. lines.pop();
  2815. }
  2816. // build the lines
  2817. each(lines, function (line, lineNo) {
  2818. var spans, spanNo = 0;
  2819. line = line.replace(/<span/g, '|||<span').replace(/<\/span>/g, '</span>|||');
  2820. spans = line.split('|||');
  2821. each(spans, function (span) {
  2822. if (span !== '' || spans.length === 1) {
  2823. var attributes = {},
  2824. tspan = doc.createElementNS(SVG_NS, 'tspan'),
  2825. spanStyle; // #390
  2826. if (styleRegex.test(span)) {
  2827. spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2');
  2828. attr(tspan, 'style', spanStyle);
  2829. }
  2830. if (hrefRegex.test(span) && !forExport) { // Not for export - #1529
  2831. attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"');
  2832. css(tspan, { cursor: 'pointer' });
  2833. }
  2834. span = unescapeAngleBrackets(span.replace(/<(.|\n)*?>/g, '') || ' ');
  2835. // Nested tags aren't supported, and cause crash in Safari (#1596)
  2836. if (span !== ' ') {
  2837. // add the text node
  2838. tspan.appendChild(doc.createTextNode(span));
  2839. if (!spanNo) { // first span in a line, align it to the left
  2840. if (lineNo && parentX !== null) {
  2841. attributes.x = parentX;
  2842. }
  2843. } else {
  2844. attributes.dx = 0; // #16
  2845. }
  2846. // add attributes
  2847. attr(tspan, attributes);
  2848. // Append it
  2849. textNode.appendChild(tspan);
  2850. // first span on subsequent line, add the line height
  2851. if (!spanNo && lineNo) {
  2852. // allow getting the right offset height in exporting in IE
  2853. if (!hasSVG && forExport) {
  2854. css(tspan, { display: 'block' });
  2855. }
  2856. // Set the line height based on the font size of either
  2857. // the text element or the tspan element
  2858. attr(
  2859. tspan,
  2860. 'dy',
  2861. getLineHeight(tspan)
  2862. );
  2863. }
  2864. /*if (width) {
  2865. renderer.breakText(wrapper, width);
  2866. }*/
  2867. // Check width and apply soft breaks or ellipsis
  2868. if (width) {
  2869. var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273
  2870. hasWhiteSpace = spans.length > 1 || lineNo || (words.length > 1 && textStyles.whiteSpace !== 'nowrap'),
  2871. tooLong,
  2872. wasTooLong,
  2873. actualWidth,
  2874. rest = [],
  2875. dy = getLineHeight(tspan),
  2876. softLineNo = 1,
  2877. rotation = wrapper.rotation,
  2878. wordStr = span, // for ellipsis
  2879. cursor = wordStr.length, // binary search cursor
  2880. bBox;
  2881. while ((hasWhiteSpace || ellipsis) && (words.length || rest.length)) {
  2882. wrapper.rotation = 0; // discard rotation when computing box
  2883. bBox = wrapper.getBBox(true);
  2884. actualWidth = bBox.width;
  2885. // Old IE cannot measure the actualWidth for SVG elements (#2314)
  2886. if (!hasSVG && renderer.forExport) {
  2887. actualWidth = renderer.measureSpanWidth(tspan.firstChild.data, wrapper.styles);
  2888. }
  2889. tooLong = actualWidth > width;
  2890. // For ellipsis, do a binary search for the correct string length
  2891. if (wasTooLong === undefined) {
  2892. wasTooLong = tooLong; // First time
  2893. }
  2894. if (ellipsis && wasTooLong) {
  2895. cursor /= 2;
  2896. if (wordStr === '' || (!tooLong && cursor < 0.5)) {
  2897. words = []; // All ok, break out
  2898. } else {
  2899. if (tooLong) {
  2900. wasTooLong = true;
  2901. }
  2902. wordStr = span.substring(0, wordStr.length + (tooLong ? -1 : 1) * mathCeil(cursor));
  2903. words = [wordStr + (width > 3 ? '\u2026' : '')];
  2904. tspan.removeChild(tspan.firstChild);
  2905. }
  2906. // Looping down, this is the first word sequence that is not too long,
  2907. // so we can move on to build the next line.
  2908. } else if (!tooLong || words.length === 1) {
  2909. words = rest;
  2910. rest = [];
  2911. if (words.length) {
  2912. softLineNo++;
  2913. tspan = doc.createElementNS(SVG_NS, 'tspan');
  2914. attr(tspan, {
  2915. dy: dy,
  2916. x: parentX
  2917. });
  2918. if (spanStyle) { // #390
  2919. attr(tspan, 'style', spanStyle);
  2920. }
  2921. textNode.appendChild(tspan);
  2922. }
  2923. if (actualWidth > width) { // a single word is pressing it out
  2924. width = actualWidth;
  2925. }
  2926. } else { // append to existing line tspan
  2927. tspan.removeChild(tspan.firstChild);
  2928. rest.unshift(words.pop());
  2929. }
  2930. if (words.length) {
  2931. tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-')));
  2932. }
  2933. }
  2934. if (wasTooLong) {
  2935. wrapper.attr('title', wrapper.textStr);
  2936. }
  2937. wrapper.rotation = rotation;
  2938. }
  2939. spanNo++;
  2940. }
  2941. }
  2942. });
  2943. });
  2944. if (tempParent) {
  2945. tempParent.removeChild(textNode); // attach it to the DOM to read offset width
  2946. }
  2947. // Apply the text shadow
  2948. if (textShadow && wrapper.applyTextShadow) {
  2949. wrapper.applyTextShadow(textShadow);
  2950. }
  2951. }
  2952. },
  2953. /*
  2954. breakText: function (wrapper, width) {
  2955. var bBox = wrapper.getBBox(),
  2956. node = wrapper.element,
  2957. textLength = node.textContent.length,
  2958. pos = mathRound(width * textLength / bBox.width), // try this position first, based on average character width
  2959. increment = 0,
  2960. finalPos;
  2961. if (bBox.width > width) {
  2962. while (finalPos === undefined) {
  2963. textLength = node.getSubStringLength(0, pos);
  2964. if (textLength <= width) {
  2965. if (increment === -1) {
  2966. finalPos = pos;
  2967. } else {
  2968. increment = 1;
  2969. }
  2970. } else {
  2971. if (increment === 1) {
  2972. finalPos = pos - 1;
  2973. } else {
  2974. increment = -1;
  2975. }
  2976. }
  2977. pos += increment;
  2978. }
  2979. }
  2980. console.log(finalPos, node.getSubStringLength(0, finalPos))
  2981. },
  2982. */
  2983. /**
  2984. * Returns white for dark colors and black for bright colors
  2985. */
  2986. getContrast: function (color) {
  2987. color = Color(color).rgba;
  2988. return color[0] + color[1] + color[2] > 384 ? '#000000' : '#FFFFFF';
  2989. },
  2990. /**
  2991. * Create a button with preset states
  2992. * @param {String} text
  2993. * @param {Number} x
  2994. * @param {Number} y
  2995. * @param {Function} callback
  2996. * @param {Object} normalState
  2997. * @param {Object} hoverState
  2998. * @param {Object} pressedState
  2999. */
  3000. button: function (text, x, y, callback, normalState, hoverState, pressedState, disabledState, shape) {
  3001. var label = this.label(text, x, y, shape, null, null, null, null, 'button'),
  3002. curState = 0,
  3003. stateOptions,
  3004. stateStyle,
  3005. normalStyle,
  3006. hoverStyle,
  3007. pressedStyle,
  3008. disabledStyle,
  3009. verticalGradient = { x1: 0, y1: 0, x2: 0, y2: 1 };
  3010. // Normal state - prepare the attributes
  3011. normalState = merge({
  3012. 'stroke-width': 1,
  3013. stroke: '#CCCCCC',
  3014. fill: {
  3015. linearGradient: verticalGradient,
  3016. stops: [
  3017. [0, '#FEFEFE'],
  3018. [1, '#F6F6F6']
  3019. ]
  3020. },
  3021. r: 2,
  3022. padding: 5,
  3023. style: {
  3024. color: 'black'
  3025. }
  3026. }, normalState);
  3027. normalStyle = normalState.style;
  3028. delete normalState.style;
  3029. // Hover state
  3030. hoverState = merge(normalState, {
  3031. stroke: '#68A',
  3032. fill: {
  3033. linearGradient: verticalGradient,
  3034. stops: [
  3035. [0, '#FFF'],
  3036. [1, '#ACF']
  3037. ]
  3038. }
  3039. }, hoverState);
  3040. hoverStyle = hoverState.style;
  3041. delete hoverState.style;
  3042. // Pressed state
  3043. pressedState = merge(normalState, {
  3044. stroke: '#68A',
  3045. fill: {
  3046. linearGradient: verticalGradient,
  3047. stops: [
  3048. [0, '#9BD'],
  3049. [1, '#CDF']
  3050. ]
  3051. }
  3052. }, pressedState);
  3053. pressedStyle = pressedState.style;
  3054. delete pressedState.style;
  3055. // Disabled state
  3056. disabledState = merge(normalState, {
  3057. style: {
  3058. color: '#CCC'
  3059. }
  3060. }, disabledState);
  3061. disabledStyle = disabledState.style;
  3062. delete disabledState.style;
  3063. // Add the events. IE9 and IE10 need mouseover and mouseout to funciton (#667).
  3064. addEvent(label.element, isMS ? 'mouseover' : 'mouseenter', function () {
  3065. if (curState !== 3) {
  3066. label.attr(hoverState)
  3067. .css(hoverStyle);
  3068. }
  3069. });
  3070. addEvent(label.element, isMS ? 'mouseout' : 'mouseleave', function () {
  3071. if (curState !== 3) {
  3072. stateOptions = [normalState, hoverState, pressedState][curState];
  3073. stateStyle = [normalStyle, hoverStyle, pressedStyle][curState];
  3074. label.attr(stateOptions)
  3075. .css(stateStyle);
  3076. }
  3077. });
  3078. label.setState = function (state) {
  3079. label.state = curState = state;
  3080. if (!state) {
  3081. label.attr(normalState)
  3082. .css(normalStyle);
  3083. } else if (state === 2) {
  3084. label.attr(pressedState)
  3085. .css(pressedStyle);
  3086. } else if (state === 3) {
  3087. label.attr(disabledState)
  3088. .css(disabledStyle);
  3089. }
  3090. };
  3091. return label
  3092. .on('click', function (e) {
  3093. if (curState !== 3) {
  3094. callback.call(label, e);
  3095. }
  3096. })
  3097. .attr(normalState)
  3098. .css(extend({ cursor: 'default' }, normalStyle));
  3099. },
  3100. /**
  3101. * Make a straight line crisper by not spilling out to neighbour pixels
  3102. * @param {Array} points
  3103. * @param {Number} width
  3104. */
  3105. crispLine: function (points, width) {
  3106. // points format: [M, 0, 0, L, 100, 0]
  3107. // normalize to a crisp line
  3108. if (points[1] === points[4]) {
  3109. // Substract due to #1129. Now bottom and left axis gridlines behave the same.
  3110. points[1] = points[4] = mathRound(points[1]) - (width % 2 / 2);
  3111. }
  3112. if (points[2] === points[5]) {
  3113. points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2);
  3114. }
  3115. return points;
  3116. },
  3117. /**
  3118. * Draw a path
  3119. * @param {Array} path An SVG path in array form
  3120. */
  3121. path: function (path) {
  3122. var attr = {
  3123. fill: NONE
  3124. };
  3125. if (isArray(path)) {
  3126. attr.d = path;
  3127. } else if (isObject(path)) { // attributes
  3128. extend(attr, path);
  3129. }
  3130. return this.createElement('path').attr(attr);
  3131. },
  3132. /**
  3133. * Draw and return an SVG circle
  3134. * @param {Number} x The x position
  3135. * @param {Number} y The y position
  3136. * @param {Number} r The radius
  3137. */
  3138. circle: function (x, y, r) {
  3139. var attr = isObject(x) ?
  3140. x :
  3141. {
  3142. x: x,
  3143. y: y,
  3144. r: r
  3145. },
  3146. wrapper = this.createElement('circle');
  3147. wrapper.xSetter = function (value) {
  3148. this.element.setAttribute('cx', value);
  3149. };
  3150. wrapper.ySetter = function (value) {
  3151. this.element.setAttribute('cy', value);
  3152. };
  3153. return wrapper.attr(attr);
  3154. },
  3155. /**
  3156. * Draw and return an arc
  3157. * @param {Number} x X position
  3158. * @param {Number} y Y position
  3159. * @param {Number} r Radius
  3160. * @param {Number} innerR Inner radius like used in donut charts
  3161. * @param {Number} start Starting angle
  3162. * @param {Number} end Ending angle
  3163. */
  3164. arc: function (x, y, r, innerR, start, end) {
  3165. var arc;
  3166. if (isObject(x)) {
  3167. y = x.y;
  3168. r = x.r;
  3169. innerR = x.innerR;
  3170. start = x.start;
  3171. end = x.end;
  3172. x = x.x;
  3173. }
  3174. // Arcs are defined as symbols for the ability to set
  3175. // attributes in attr and animate
  3176. arc = this.symbol('arc', x || 0, y || 0, r || 0, r || 0, {
  3177. innerR: innerR || 0,
  3178. start: start || 0,
  3179. end: end || 0
  3180. });
  3181. arc.r = r; // #959
  3182. return arc;
  3183. },
  3184. /**
  3185. * Draw and return a rectangle
  3186. * @param {Number} x Left position
  3187. * @param {Number} y Top position
  3188. * @param {Number} width
  3189. * @param {Number} height
  3190. * @param {Number} r Border corner radius
  3191. * @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing
  3192. */
  3193. rect: function (x, y, width, height, r, strokeWidth) {
  3194. r = isObject(x) ? x.r : r;
  3195. var wrapper = this.createElement('rect'),
  3196. attribs = isObject(x) ? x : x === UNDEFINED ? {} : {
  3197. x: x,
  3198. y: y,
  3199. width: mathMax(width, 0),
  3200. height: mathMax(height, 0)
  3201. };
  3202. if (strokeWidth !== UNDEFINED) {
  3203. attribs.strokeWidth = strokeWidth;
  3204. attribs = wrapper.crisp(attribs);
  3205. }
  3206. if (r) {
  3207. attribs.r = r;
  3208. }
  3209. wrapper.rSetter = function (value) {
  3210. attr(this.element, {
  3211. rx: value,
  3212. ry: value
  3213. });
  3214. };
  3215. return wrapper.attr(attribs);
  3216. },
  3217. /**
  3218. * Resize the box and re-align all aligned elements
  3219. * @param {Object} width
  3220. * @param {Object} height
  3221. * @param {Boolean} animate
  3222. *
  3223. */
  3224. setSize: function (width, height, animate) {
  3225. var renderer = this,
  3226. alignedObjects = renderer.alignedObjects,
  3227. i = alignedObjects.length;
  3228. renderer.width = width;
  3229. renderer.height = height;
  3230. renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({
  3231. width: width,
  3232. height: height
  3233. });
  3234. while (i--) {
  3235. alignedObjects[i].align();
  3236. }
  3237. },
  3238. /**
  3239. * Create a group
  3240. * @param {String} name The group will be given a class name of 'highcharts-{name}'.
  3241. * This can be used for styling and scripting.
  3242. */
  3243. g: function (name) {
  3244. var elem = this.createElement('g');
  3245. return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem;
  3246. },
  3247. /**
  3248. * Display an image
  3249. * @param {String} src
  3250. * @param {Number} x
  3251. * @param {Number} y
  3252. * @param {Number} width
  3253. * @param {Number} height
  3254. */
  3255. image: function (src, x, y, width, height) {
  3256. var attribs = {
  3257. preserveAspectRatio: NONE
  3258. },
  3259. elemWrapper;
  3260. // optional properties
  3261. if (arguments.length > 1) {
  3262. extend(attribs, {
  3263. x: x,
  3264. y: y,
  3265. width: width,
  3266. height: height
  3267. });
  3268. }
  3269. elemWrapper = this.createElement('image').attr(attribs);
  3270. // set the href in the xlink namespace
  3271. if (elemWrapper.element.setAttributeNS) {
  3272. elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink',
  3273. 'href', src);
  3274. } else {
  3275. // could be exporting in IE
  3276. // using href throws "not supported" in ie7 and under, requries regex shim to fix later
  3277. elemWrapper.element.setAttribute('hc-svg-href', src);
  3278. }
  3279. return elemWrapper;
  3280. },
  3281. /**
  3282. * Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object.
  3283. *
  3284. * @param {Object} symbol
  3285. * @param {Object} x
  3286. * @param {Object} y
  3287. * @param {Object} radius
  3288. * @param {Object} options
  3289. */
  3290. symbol: function (symbol, x, y, width, height, options) {
  3291. var obj,
  3292. // get the symbol definition function
  3293. symbolFn = this.symbols[symbol],
  3294. // check if there's a path defined for this symbol
  3295. path = symbolFn && symbolFn(
  3296. mathRound(x),
  3297. mathRound(y),
  3298. width,
  3299. height,
  3300. options
  3301. ),
  3302. imageElement,
  3303. imageRegex = /^url\((.*?)\)$/,
  3304. imageSrc,
  3305. imageSize,
  3306. centerImage;
  3307. if (path) {
  3308. obj = this.path(path);
  3309. // expando properties for use in animate and attr
  3310. extend(obj, {
  3311. symbolName: symbol,
  3312. x: x,
  3313. y: y,
  3314. width: width,
  3315. height: height
  3316. });
  3317. if (options) {
  3318. extend(obj, options);
  3319. }
  3320. // image symbols
  3321. } else if (imageRegex.test(symbol)) {
  3322. // On image load, set the size and position
  3323. centerImage = function (img, size) {
  3324. if (img.element) { // it may be destroyed in the meantime (#1390)
  3325. img.attr({
  3326. width: size[0],
  3327. height: size[1]
  3328. });
  3329. if (!img.alignByTranslate) { // #185
  3330. img.translate(
  3331. mathRound((width - size[0]) / 2), // #1378
  3332. mathRound((height - size[1]) / 2)
  3333. );
  3334. }
  3335. }
  3336. };
  3337. imageSrc = symbol.match(imageRegex)[1];
  3338. imageSize = symbolSizes[imageSrc] || (options && options.width && options.height && [options.width, options.height]);
  3339. // Ireate the image synchronously, add attribs async
  3340. obj = this.image(imageSrc)
  3341. .attr({
  3342. x: x,
  3343. y: y
  3344. });
  3345. obj.isImg = true;
  3346. if (imageSize) {
  3347. centerImage(obj, imageSize);
  3348. } else {
  3349. // Initialize image to be 0 size so export will still function if there's no cached sizes.
  3350. obj.attr({ width: 0, height: 0 });
  3351. // Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8,
  3352. // the created element must be assigned to a variable in order to load (#292).
  3353. imageElement = createElement('img', {
  3354. onload: function () {
  3355. // Special case for SVGs on IE11, the width is not accessible until the image is
  3356. // part of the DOM (#2854).
  3357. if (this.width === 0) {
  3358. css(this, {
  3359. position: ABSOLUTE,
  3360. top: '-999em'
  3361. });
  3362. document.body.appendChild(this);
  3363. }
  3364. // Center the image
  3365. centerImage(obj, symbolSizes[imageSrc] = [this.width, this.height]);
  3366. // Clean up after #2854 workaround.
  3367. if (this.parentNode) {
  3368. this.parentNode.removeChild(this);
  3369. }
  3370. },
  3371. src: imageSrc
  3372. });
  3373. }
  3374. }
  3375. return obj;
  3376. },
  3377. /**
  3378. * An extendable collection of functions for defining symbol paths.
  3379. */
  3380. symbols: {
  3381. 'circle': function (x, y, w, h) {
  3382. var cpw = 0.166 * w;
  3383. return [
  3384. M, x + w / 2, y,
  3385. 'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h,
  3386. 'C', x - cpw, y + h, x - cpw, y, x + w / 2, y,
  3387. 'Z'
  3388. ];
  3389. },
  3390. 'square': function (x, y, w, h) {
  3391. return [
  3392. M, x, y,
  3393. L, x + w, y,
  3394. x + w, y + h,
  3395. x, y + h,
  3396. 'Z'
  3397. ];
  3398. },
  3399. 'triangle': function (x, y, w, h) {
  3400. return [
  3401. M, x + w / 2, y,
  3402. L, x + w, y + h,
  3403. x, y + h,
  3404. 'Z'
  3405. ];
  3406. },
  3407. 'triangle-down': function (x, y, w, h) {
  3408. return [
  3409. M, x, y,
  3410. L, x + w, y,
  3411. x + w / 2, y + h,
  3412. 'Z'
  3413. ];
  3414. },
  3415. 'diamond': function (x, y, w, h) {
  3416. return [
  3417. M, x + w / 2, y,
  3418. L, x + w, y + h / 2,
  3419. x + w / 2, y + h,
  3420. x, y + h / 2,
  3421. 'Z'
  3422. ];
  3423. },
  3424. 'arc': function (x, y, w, h, options) {
  3425. var start = options.start,
  3426. radius = options.r || w || h,
  3427. end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561)
  3428. innerRadius = options.innerR,
  3429. open = options.open,
  3430. cosStart = mathCos(start),
  3431. sinStart = mathSin(start),
  3432. cosEnd = mathCos(end),
  3433. sinEnd = mathSin(end),
  3434. longArc = options.end - start < mathPI ? 0 : 1;
  3435. return [
  3436. M,
  3437. x + radius * cosStart,
  3438. y + radius * sinStart,
  3439. 'A', // arcTo
  3440. radius, // x radius
  3441. radius, // y radius
  3442. 0, // slanting
  3443. longArc, // long or short arc
  3444. 1, // clockwise
  3445. x + radius * cosEnd,
  3446. y + radius * sinEnd,
  3447. open ? M : L,
  3448. x + innerRadius * cosEnd,
  3449. y + innerRadius * sinEnd,
  3450. 'A', // arcTo
  3451. innerRadius, // x radius
  3452. innerRadius, // y radius
  3453. 0, // slanting
  3454. longArc, // long or short arc
  3455. 0, // clockwise
  3456. x + innerRadius * cosStart,
  3457. y + innerRadius * sinStart,
  3458. open ? '' : 'Z' // close
  3459. ];
  3460. },
  3461. /**
  3462. * Callout shape used for default tooltips, also used for rounded rectangles in VML
  3463. */
  3464. callout: function (x, y, w, h, options) {
  3465. var arrowLength = 6,
  3466. halfDistance = 6,
  3467. r = mathMin((options && options.r) || 0, w, h),
  3468. safeDistance = r + halfDistance,
  3469. anchorX = options && options.anchorX,
  3470. anchorY = options && options.anchorY,
  3471. path;
  3472. path = [
  3473. 'M', x + r, y,
  3474. 'L', x + w - r, y, // top side
  3475. 'C', x + w, y, x + w, y, x + w, y + r, // top-right corner
  3476. 'L', x + w, y + h - r, // right side
  3477. 'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-right corner
  3478. 'L', x + r, y + h, // bottom side
  3479. 'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner
  3480. 'L', x, y + r, // left side
  3481. 'C', x, y, x, y, x + r, y // top-right corner
  3482. ];
  3483. if (anchorX && anchorX > w && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace right side
  3484. path.splice(13, 3,
  3485. 'L', x + w, anchorY - halfDistance,
  3486. x + w + arrowLength, anchorY,
  3487. x + w, anchorY + halfDistance,
  3488. x + w, y + h - r
  3489. );
  3490. } else if (anchorX && anchorX < 0 && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace left side
  3491. path.splice(33, 3,
  3492. 'L', x, anchorY + halfDistance,
  3493. x - arrowLength, anchorY,
  3494. x, anchorY - halfDistance,
  3495. x, y + r
  3496. );
  3497. } else if (anchorY && anchorY > h && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace bottom
  3498. path.splice(23, 3,
  3499. 'L', anchorX + halfDistance, y + h,
  3500. anchorX, y + h + arrowLength,
  3501. anchorX - halfDistance, y + h,
  3502. x + r, y + h
  3503. );
  3504. } else if (anchorY && anchorY < 0 && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace top
  3505. path.splice(3, 3,
  3506. 'L', anchorX - halfDistance, y,
  3507. anchorX, y - arrowLength,
  3508. anchorX + halfDistance, y,
  3509. w - r, y
  3510. );
  3511. }
  3512. return path;
  3513. }
  3514. },
  3515. /**
  3516. * Define a clipping rectangle
  3517. * @param {String} id
  3518. * @param {Number} x
  3519. * @param {Number} y
  3520. * @param {Number} width
  3521. * @param {Number} height
  3522. */
  3523. clipRect: function (x, y, width, height) {
  3524. var wrapper,
  3525. id = PREFIX + idCounter++,
  3526. clipPath = this.createElement('clipPath').attr({
  3527. id: id
  3528. }).add(this.defs);
  3529. wrapper = this.rect(x, y, width, height, 0).add(clipPath);
  3530. wrapper.id = id;
  3531. wrapper.clipPath = clipPath;
  3532. wrapper.count = 0;
  3533. return wrapper;
  3534. },
  3535. /**
  3536. * Add text to the SVG object
  3537. * @param {String} str
  3538. * @param {Number} x Left position
  3539. * @param {Number} y Top position
  3540. * @param {Boolean} useHTML Use HTML to render the text
  3541. */
  3542. text: function (str, x, y, useHTML) {
  3543. // declare variables
  3544. var renderer = this,
  3545. fakeSVG = useCanVG || (!hasSVG && renderer.forExport),
  3546. wrapper,
  3547. attr = {};
  3548. if (useHTML && (renderer.allowHTML || !renderer.forExport)) {
  3549. return renderer.html(str, x, y);
  3550. }
  3551. attr.x = Math.round(x || 0); // X is always needed for line-wrap logic
  3552. if (y) {
  3553. attr.y = Math.round(y);
  3554. }
  3555. if (str || str === 0) {
  3556. attr.text = str;
  3557. }
  3558. wrapper = renderer.createElement('text')
  3559. .attr(attr);
  3560. // Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063)
  3561. if (fakeSVG) {
  3562. wrapper.css({
  3563. position: ABSOLUTE
  3564. });
  3565. }
  3566. if (!useHTML) {
  3567. wrapper.xSetter = function (value, key, element) {
  3568. var tspans = element.getElementsByTagName('tspan'),
  3569. tspan,
  3570. parentVal = element.getAttribute(key),
  3571. i;
  3572. for (i = 0; i < tspans.length; i++) {
  3573. tspan = tspans[i];
  3574. // If the x values are equal, the tspan represents a linebreak
  3575. if (tspan.getAttribute(key) === parentVal) {
  3576. tspan.setAttribute(key, value);
  3577. }
  3578. }
  3579. element.setAttribute(key, value);
  3580. };
  3581. }
  3582. return wrapper;
  3583. },
  3584. /**
  3585. * Utility to return the baseline offset and total line height from the font size
  3586. */
  3587. fontMetrics: function (fontSize, elem) {
  3588. var lineHeight,
  3589. baseline,
  3590. style;
  3591. fontSize = fontSize || this.style.fontSize;
  3592. if (!fontSize && elem && win.getComputedStyle) {
  3593. elem = elem.element || elem; // SVGElement
  3594. style = win.getComputedStyle(elem, "");
  3595. fontSize = style && style.fontSize; // #4309, the style doesn't exist inside a hidden iframe in Firefox
  3596. }
  3597. fontSize = /px/.test(fontSize) ? pInt(fontSize) : /em/.test(fontSize) ? parseFloat(fontSize) * 12 : 12;
  3598. // Empirical values found by comparing font size and bounding box height.
  3599. // Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/
  3600. lineHeight = fontSize < 24 ? fontSize + 3 : mathRound(fontSize * 1.2);
  3601. baseline = mathRound(lineHeight * 0.8);
  3602. return {
  3603. h: lineHeight,
  3604. b: baseline,
  3605. f: fontSize
  3606. };
  3607. },
  3608. /**
  3609. * Correct X and Y positioning of a label for rotation (#1764)
  3610. */
  3611. rotCorr: function (baseline, rotation, alterY) {
  3612. var y = baseline;
  3613. if (rotation && alterY) {
  3614. y = mathMax(y * mathCos(rotation * deg2rad), 4);
  3615. }
  3616. return {
  3617. x: (-baseline / 3) * mathSin(rotation * deg2rad),
  3618. y: y
  3619. };
  3620. },
  3621. /**
  3622. * Add a label, a text item that can hold a colored or gradient background
  3623. * as well as a border and shadow.
  3624. * @param {string} str
  3625. * @param {Number} x
  3626. * @param {Number} y
  3627. * @param {String} shape
  3628. * @param {Number} anchorX In case the shape has a pointer, like a flag, this is the
  3629. * coordinates it should be pinned to
  3630. * @param {Number} anchorY
  3631. * @param {Boolean} baseline Whether to position the label relative to the text baseline,
  3632. * like renderer.text, or to the upper border of the rectangle.
  3633. * @param {String} className Class name for the group
  3634. */
  3635. label: function (str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) {
  3636. var renderer = this,
  3637. wrapper = renderer.g(className),
  3638. text = renderer.text('', 0, 0, useHTML)
  3639. .attr({
  3640. zIndex: 1
  3641. }),
  3642. //.add(wrapper),
  3643. box,
  3644. bBox,
  3645. alignFactor = 0,
  3646. padding = 3,
  3647. paddingLeft = 0,
  3648. width,
  3649. height,
  3650. wrapperX,
  3651. wrapperY,
  3652. crispAdjust = 0,
  3653. deferredAttr = {},
  3654. baselineOffset,
  3655. needsBox;
  3656. /**
  3657. * This function runs after the label is added to the DOM (when the bounding box is
  3658. * available), and after the text of the label is updated to detect the new bounding
  3659. * box and reflect it in the border box.
  3660. */
  3661. function updateBoxSize() {
  3662. var boxX,
  3663. boxY,
  3664. style = text.element.style;
  3665. bBox = (width === undefined || height === undefined || wrapper.styles.textAlign) && defined(text.textStr) &&
  3666. text.getBBox(); //#3295 && 3514 box failure when string equals 0
  3667. wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft;
  3668. wrapper.height = (height || bBox.height || 0) + 2 * padding;
  3669. // update the label-scoped y offset
  3670. baselineOffset = padding + renderer.fontMetrics(style && style.fontSize, text).b;
  3671. if (needsBox) {
  3672. // create the border box if it is not already present
  3673. if (!box) {
  3674. boxX = mathRound(-alignFactor * padding) + crispAdjust;
  3675. boxY = (baseline ? -baselineOffset : 0) + crispAdjust;
  3676. wrapper.box = box = shape ?
  3677. renderer.symbol(shape, boxX, boxY, wrapper.width, wrapper.height, deferredAttr) :
  3678. renderer.rect(boxX, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]);
  3679. if (!box.isImg) { // #4324, fill "none" causes it to be ignored by mouse events in IE
  3680. box.attr('fill', NONE);
  3681. }
  3682. box.add(wrapper);
  3683. }
  3684. // apply the box attributes
  3685. if (!box.isImg) { // #1630
  3686. box.attr(extend({
  3687. width: mathRound(wrapper.width),
  3688. height: mathRound(wrapper.height)
  3689. }, deferredAttr));
  3690. }
  3691. deferredAttr = null;
  3692. }
  3693. }
  3694. /**
  3695. * This function runs after setting text or padding, but only if padding is changed
  3696. */
  3697. function updateTextPadding() {
  3698. var styles = wrapper.styles,
  3699. textAlign = styles && styles.textAlign,
  3700. x = paddingLeft + padding * (1 - alignFactor),
  3701. y;
  3702. // determin y based on the baseline
  3703. y = baseline ? 0 : baselineOffset;
  3704. // compensate for alignment
  3705. if (defined(width) && bBox && (textAlign === 'center' || textAlign === 'right')) {
  3706. x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width);
  3707. }
  3708. // update if anything changed
  3709. if (x !== text.x || y !== text.y) {
  3710. text.attr('x', x);
  3711. if (y !== UNDEFINED) {
  3712. text.attr('y', y);
  3713. }
  3714. }
  3715. // record current values
  3716. text.x = x;
  3717. text.y = y;
  3718. }
  3719. /**
  3720. * Set a box attribute, or defer it if the box is not yet created
  3721. * @param {Object} key
  3722. * @param {Object} value
  3723. */
  3724. function boxAttr(key, value) {
  3725. if (box) {
  3726. box.attr(key, value);
  3727. } else {
  3728. deferredAttr[key] = value;
  3729. }
  3730. }
  3731. /**
  3732. * After the text element is added, get the desired size of the border box
  3733. * and add it before the text in the DOM.
  3734. */
  3735. wrapper.onAdd = function () {
  3736. text.add(wrapper);
  3737. wrapper.attr({
  3738. text: (str || str === 0) ? str : '', // alignment is available now // #3295: 0 not rendered if given as a value
  3739. x: x,
  3740. y: y
  3741. });
  3742. if (box && defined(anchorX)) {
  3743. wrapper.attr({
  3744. anchorX: anchorX,
  3745. anchorY: anchorY
  3746. });
  3747. }
  3748. };
  3749. /*
  3750. * Add specific attribute setters.
  3751. */
  3752. // only change local variables
  3753. wrapper.widthSetter = function (value) {
  3754. width = value;
  3755. };
  3756. wrapper.heightSetter = function (value) {
  3757. height = value;
  3758. };
  3759. wrapper.paddingSetter = function (value) {
  3760. if (defined(value) && value !== padding) {
  3761. padding = wrapper.padding = value;
  3762. updateTextPadding();
  3763. }
  3764. };
  3765. wrapper.paddingLeftSetter = function (value) {
  3766. if (defined(value) && value !== paddingLeft) {
  3767. paddingLeft = value;
  3768. updateTextPadding();
  3769. }
  3770. };
  3771. // change local variable and prevent setting attribute on the group
  3772. wrapper.alignSetter = function (value) {
  3773. alignFactor = { left: 0, center: 0.5, right: 1 }[value];
  3774. };
  3775. // apply these to the box and the text alike
  3776. wrapper.textSetter = function (value) {
  3777. if (value !== UNDEFINED) {
  3778. text.textSetter(value);
  3779. }
  3780. updateBoxSize();
  3781. updateTextPadding();
  3782. };
  3783. // apply these to the box but not to the text
  3784. wrapper['stroke-widthSetter'] = function (value, key) {
  3785. if (value) {
  3786. needsBox = true;
  3787. }
  3788. crispAdjust = value % 2 / 2;
  3789. boxAttr(key, value);
  3790. };
  3791. wrapper.strokeSetter = wrapper.fillSetter = wrapper.rSetter = function (value, key) {
  3792. if (key === 'fill' && value) {
  3793. needsBox = true;
  3794. }
  3795. boxAttr(key, value);
  3796. };
  3797. wrapper.anchorXSetter = function (value, key) {
  3798. anchorX = value;
  3799. boxAttr(key, mathRound(value) - crispAdjust - wrapperX);
  3800. };
  3801. wrapper.anchorYSetter = function (value, key) {
  3802. anchorY = value;
  3803. boxAttr(key, value - wrapperY);
  3804. };
  3805. // rename attributes
  3806. wrapper.xSetter = function (value) {
  3807. wrapper.x = value; // for animation getter
  3808. if (alignFactor) {
  3809. value -= alignFactor * ((width || bBox.width) + padding);
  3810. }
  3811. wrapperX = mathRound(value);
  3812. wrapper.attr('translateX', wrapperX);
  3813. };
  3814. wrapper.ySetter = function (value) {
  3815. wrapperY = wrapper.y = mathRound(value);
  3816. wrapper.attr('translateY', wrapperY);
  3817. };
  3818. // Redirect certain methods to either the box or the text
  3819. var baseCss = wrapper.css;
  3820. return extend(wrapper, {
  3821. /**
  3822. * Pick up some properties and apply them to the text instead of the wrapper
  3823. */
  3824. css: function (styles) {
  3825. if (styles) {
  3826. var textStyles = {};
  3827. styles = merge(styles); // create a copy to avoid altering the original object (#537)
  3828. each(wrapper.textProps, function (prop) {
  3829. if (styles[prop] !== UNDEFINED) {
  3830. textStyles[prop] = styles[prop];
  3831. delete styles[prop];
  3832. }
  3833. });
  3834. text.css(textStyles);
  3835. }
  3836. return baseCss.call(wrapper, styles);
  3837. },
  3838. /**
  3839. * Return the bounding box of the box, not the group
  3840. */
  3841. getBBox: function () {
  3842. return {
  3843. width: bBox.width + 2 * padding,
  3844. height: bBox.height + 2 * padding,
  3845. x: bBox.x - padding,
  3846. y: bBox.y - padding
  3847. };
  3848. },
  3849. /**
  3850. * Apply the shadow to the box
  3851. */
  3852. shadow: function (b) {
  3853. if (box) {
  3854. box.shadow(b);
  3855. }
  3856. return wrapper;
  3857. },
  3858. /**
  3859. * Destroy and release memory.
  3860. */
  3861. destroy: function () {
  3862. // Added by button implementation
  3863. removeEvent(wrapper.element, 'mouseenter');
  3864. removeEvent(wrapper.element, 'mouseleave');
  3865. if (text) {
  3866. text = text.destroy();
  3867. }
  3868. if (box) {
  3869. box = box.destroy();
  3870. }
  3871. // Call base implementation to destroy the rest
  3872. SVGElement.prototype.destroy.call(wrapper);
  3873. // Release local pointers (#1298)
  3874. wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = null;
  3875. }
  3876. });
  3877. }
  3878. }; // end SVGRenderer
  3879. // general renderer
  3880. Renderer = SVGRenderer;
  3881. // extend SvgElement for useHTML option
  3882. extend(SVGElement.prototype, {
  3883. /**
  3884. * Apply CSS to HTML elements. This is used in text within SVG rendering and
  3885. * by the VML renderer
  3886. */
  3887. htmlCss: function (styles) {
  3888. var wrapper = this,
  3889. element = wrapper.element,
  3890. textWidth = styles && element.tagName === 'SPAN' && styles.width;
  3891. if (textWidth) {
  3892. delete styles.width;
  3893. wrapper.textWidth = textWidth;
  3894. wrapper.updateTransform();
  3895. }
  3896. if (styles && styles.textOverflow === 'ellipsis') {
  3897. styles.whiteSpace = 'nowrap';
  3898. styles.overflow = 'hidden';
  3899. }
  3900. wrapper.styles = extend(wrapper.styles, styles);
  3901. css(wrapper.element, styles);
  3902. return wrapper;
  3903. },
  3904. /**
  3905. * VML and useHTML method for calculating the bounding box based on offsets
  3906. * @param {Boolean} refresh Whether to force a fresh value from the DOM or to
  3907. * use the cached value
  3908. *
  3909. * @return {Object} A hash containing values for x, y, width and height
  3910. */
  3911. htmlGetBBox: function () {
  3912. var wrapper = this,
  3913. element = wrapper.element;
  3914. // faking getBBox in exported SVG in legacy IE
  3915. // faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?)
  3916. if (element.nodeName === 'text') {
  3917. element.style.position = ABSOLUTE;
  3918. }
  3919. return {
  3920. x: element.offsetLeft,
  3921. y: element.offsetTop,
  3922. width: element.offsetWidth,
  3923. height: element.offsetHeight
  3924. };
  3925. },
  3926. /**
  3927. * VML override private method to update elements based on internal
  3928. * properties based on SVG transform
  3929. */
  3930. htmlUpdateTransform: function () {
  3931. // aligning non added elements is expensive
  3932. if (!this.added) {
  3933. this.alignOnAdd = true;
  3934. return;
  3935. }
  3936. var wrapper = this,
  3937. renderer = wrapper.renderer,
  3938. elem = wrapper.element,
  3939. translateX = wrapper.translateX || 0,
  3940. translateY = wrapper.translateY || 0,
  3941. x = wrapper.x || 0,
  3942. y = wrapper.y || 0,
  3943. align = wrapper.textAlign || 'left',
  3944. alignCorrection = { left: 0, center: 0.5, right: 1 }[align],
  3945. shadows = wrapper.shadows,
  3946. styles = wrapper.styles;
  3947. // apply translate
  3948. css(elem, {
  3949. marginLeft: translateX,
  3950. marginTop: translateY
  3951. });
  3952. if (shadows) { // used in labels/tooltip
  3953. each(shadows, function (shadow) {
  3954. css(shadow, {
  3955. marginLeft: translateX + 1,
  3956. marginTop: translateY + 1
  3957. });
  3958. });
  3959. }
  3960. // apply inversion
  3961. if (wrapper.inverted) { // wrapper is a group
  3962. each(elem.childNodes, function (child) {
  3963. renderer.invertChild(child, elem);
  3964. });
  3965. }
  3966. if (elem.tagName === 'SPAN') {
  3967. var width,
  3968. rotation = wrapper.rotation,
  3969. baseline,
  3970. textWidth = pInt(wrapper.textWidth),
  3971. currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth, wrapper.textAlign].join(',');
  3972. if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed
  3973. baseline = renderer.fontMetrics(elem.style.fontSize).b;
  3974. // Renderer specific handling of span rotation
  3975. if (defined(rotation)) {
  3976. wrapper.setSpanRotation(rotation, alignCorrection, baseline);
  3977. }
  3978. width = pick(wrapper.elemWidth, elem.offsetWidth);
  3979. // Update textWidth
  3980. if (width > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254
  3981. css(elem, {
  3982. width: textWidth + PX,
  3983. display: 'block',
  3984. whiteSpace: (styles && styles.whiteSpace) || 'normal' // #3331
  3985. });
  3986. width = textWidth;
  3987. }
  3988. wrapper.getSpanCorrection(width, baseline, alignCorrection, rotation, align);
  3989. }
  3990. // apply position with correction
  3991. css(elem, {
  3992. left: (x + (wrapper.xCorr || 0)) + PX,
  3993. top: (y + (wrapper.yCorr || 0)) + PX
  3994. });
  3995. // force reflow in webkit to apply the left and top on useHTML element (#1249)
  3996. if (isWebKit) {
  3997. baseline = elem.offsetHeight; // assigned to baseline for JSLint purpose
  3998. }
  3999. // record current text transform
  4000. wrapper.cTT = currentTextTransform;
  4001. }
  4002. },
  4003. /**
  4004. * Set the rotation of an individual HTML span
  4005. */
  4006. setSpanRotation: function (rotation, alignCorrection, baseline) {
  4007. var rotationStyle = {},
  4008. cssTransformKey = isMS ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : '';
  4009. rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)';
  4010. rotationStyle[cssTransformKey + (isFirefox ? 'Origin' : '-origin')] = rotationStyle.transformOrigin = (alignCorrection * 100) + '% ' + baseline + 'px';
  4011. css(this.element, rotationStyle);
  4012. },
  4013. /**
  4014. * Get the correction in X and Y positioning as the element is rotated.
  4015. */
  4016. getSpanCorrection: function (width, baseline, alignCorrection) {
  4017. this.xCorr = -width * alignCorrection;
  4018. this.yCorr = -baseline;
  4019. }
  4020. });
  4021. // Extend SvgRenderer for useHTML option.
  4022. extend(SVGRenderer.prototype, {
  4023. /**
  4024. * Create HTML text node. This is used by the VML renderer as well as the SVG
  4025. * renderer through the useHTML option.
  4026. *
  4027. * @param {String} str
  4028. * @param {Number} x
  4029. * @param {Number} y
  4030. */
  4031. html: function (str, x, y) {
  4032. var wrapper = this.createElement('span'),
  4033. element = wrapper.element,
  4034. renderer = wrapper.renderer;
  4035. // Text setter
  4036. wrapper.textSetter = function (value) {
  4037. if (value !== element.innerHTML) {
  4038. delete this.bBox;
  4039. }
  4040. element.innerHTML = this.textStr = value;
  4041. wrapper.htmlUpdateTransform();
  4042. };
  4043. // Various setters which rely on update transform
  4044. wrapper.xSetter = wrapper.ySetter = wrapper.alignSetter = wrapper.rotationSetter = function (value, key) {
  4045. if (key === 'align') {
  4046. key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML.
  4047. }
  4048. wrapper[key] = value;
  4049. wrapper.htmlUpdateTransform();
  4050. };
  4051. // Set the default attributes
  4052. wrapper.attr({
  4053. text: str,
  4054. x: mathRound(x),
  4055. y: mathRound(y)
  4056. })
  4057. .css({
  4058. position: ABSOLUTE,
  4059. fontFamily: this.style.fontFamily,
  4060. fontSize: this.style.fontSize
  4061. });
  4062. // Keep the whiteSpace style outside the wrapper.styles collection
  4063. element.style.whiteSpace = 'nowrap';
  4064. // Use the HTML specific .css method
  4065. wrapper.css = wrapper.htmlCss;
  4066. // This is specific for HTML within SVG
  4067. if (renderer.isSVG) {
  4068. wrapper.add = function (svgGroupWrapper) {
  4069. var htmlGroup,
  4070. container = renderer.box.parentNode,
  4071. parentGroup,
  4072. parents = [];
  4073. this.parentGroup = svgGroupWrapper;
  4074. // Create a mock group to hold the HTML elements
  4075. if (svgGroupWrapper) {
  4076. htmlGroup = svgGroupWrapper.div;
  4077. if (!htmlGroup) {
  4078. // Read the parent chain into an array and read from top down
  4079. parentGroup = svgGroupWrapper;
  4080. while (parentGroup) {
  4081. parents.push(parentGroup);
  4082. // Move up to the next parent group
  4083. parentGroup = parentGroup.parentGroup;
  4084. }
  4085. // Ensure dynamically updating position when any parent is translated
  4086. each(parents.reverse(), function (parentGroup) {
  4087. var htmlGroupStyle,
  4088. cls = attr(parentGroup.element, 'class');
  4089. if (cls) {
  4090. cls = { className: cls };
  4091. } // else null
  4092. // Create a HTML div and append it to the parent div to emulate
  4093. // the SVG group structure
  4094. htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, cls, {
  4095. position: ABSOLUTE,
  4096. left: (parentGroup.translateX || 0) + PX,
  4097. top: (parentGroup.translateY || 0) + PX
  4098. }, htmlGroup || container); // the top group is appended to container
  4099. // Shortcut
  4100. htmlGroupStyle = htmlGroup.style;
  4101. // Set listeners to update the HTML div's position whenever the SVG group
  4102. // position is changed
  4103. extend(parentGroup, {
  4104. translateXSetter: function (value, key) {
  4105. htmlGroupStyle.left = value + PX;
  4106. parentGroup[key] = value;
  4107. parentGroup.doTransform = true;
  4108. },
  4109. translateYSetter: function (value, key) {
  4110. htmlGroupStyle.top = value + PX;
  4111. parentGroup[key] = value;
  4112. parentGroup.doTransform = true;
  4113. }
  4114. });
  4115. // These properties are set as attributes on the SVG group, and as
  4116. // identical CSS properties on the div. (#3542)
  4117. each(['opacity', 'visibility'], function (prop) {
  4118. wrap(parentGroup, prop + 'Setter', function (proceed, value, key, elem) {
  4119. proceed.call(this, value, key, elem);
  4120. htmlGroupStyle[key] = value;
  4121. });
  4122. });
  4123. });
  4124. }
  4125. } else {
  4126. htmlGroup = container;
  4127. }
  4128. htmlGroup.appendChild(element);
  4129. // Shared with VML:
  4130. wrapper.added = true;
  4131. if (wrapper.alignOnAdd) {
  4132. wrapper.htmlUpdateTransform();
  4133. }
  4134. return wrapper;
  4135. };
  4136. }
  4137. return wrapper;
  4138. }
  4139. });
  4140. /* ****************************************************************************
  4141. * *
  4142. * START OF INTERNET EXPLORER <= 8 SPECIFIC CODE *
  4143. * *
  4144. * For applications and websites that don't need IE support, like platform *
  4145. * targeted mobile apps and web apps, this code can be removed. *
  4146. * *
  4147. *****************************************************************************/
  4148. /**
  4149. * @constructor
  4150. */
  4151. var VMLRenderer, VMLElement;
  4152. if (!hasSVG && !useCanVG) {
  4153. /**
  4154. * The VML element wrapper.
  4155. */
  4156. VMLElement = {
  4157. /**
  4158. * Initialize a new VML element wrapper. It builds the markup as a string
  4159. * to minimize DOM traffic.
  4160. * @param {Object} renderer
  4161. * @param {Object} nodeName
  4162. */
  4163. init: function (renderer, nodeName) {
  4164. var wrapper = this,
  4165. markup = ['<', nodeName, ' filled="f" stroked="f"'],
  4166. style = ['position: ', ABSOLUTE, ';'],
  4167. isDiv = nodeName === DIV;
  4168. // divs and shapes need size
  4169. if (nodeName === 'shape' || isDiv) {
  4170. style.push('left:0;top:0;width:1px;height:1px;');
  4171. }
  4172. style.push('visibility: ', isDiv ? HIDDEN : VISIBLE);
  4173. markup.push(' style="', style.join(''), '"/>');
  4174. // create element with default attributes and style
  4175. if (nodeName) {
  4176. markup = isDiv || nodeName === 'span' || nodeName === 'img' ?
  4177. markup.join('')
  4178. : renderer.prepVML(markup);
  4179. wrapper.element = createElement(markup);
  4180. }
  4181. wrapper.renderer = renderer;
  4182. },
  4183. /**
  4184. * Add the node to the given parent
  4185. * @param {Object} parent
  4186. */
  4187. add: function (parent) {
  4188. var wrapper = this,
  4189. renderer = wrapper.renderer,
  4190. element = wrapper.element,
  4191. box = renderer.box,
  4192. inverted = parent && parent.inverted,
  4193. // get the parent node
  4194. parentNode = parent ?
  4195. parent.element || parent :
  4196. box;
  4197. // if the parent group is inverted, apply inversion on all children
  4198. if (inverted) { // only on groups
  4199. renderer.invertChild(element, parentNode);
  4200. }
  4201. // append it
  4202. parentNode.appendChild(element);
  4203. // align text after adding to be able to read offset
  4204. wrapper.added = true;
  4205. if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) {
  4206. wrapper.updateTransform();
  4207. }
  4208. // fire an event for internal hooks
  4209. if (wrapper.onAdd) {
  4210. wrapper.onAdd();
  4211. }
  4212. return wrapper;
  4213. },
  4214. /**
  4215. * VML always uses htmlUpdateTransform
  4216. */
  4217. updateTransform: SVGElement.prototype.htmlUpdateTransform,
  4218. /**
  4219. * Set the rotation of a span with oldIE's filter
  4220. */
  4221. setSpanRotation: function () {
  4222. // Adjust for alignment and rotation. Rotation of useHTML content is not yet implemented
  4223. // but it can probably be implemented for Firefox 3.5+ on user request. FF3.5+
  4224. // has support for CSS3 transform. The getBBox method also needs to be updated
  4225. // to compensate for the rotation, like it currently does for SVG.
  4226. // Test case: http://jsfiddle.net/highcharts/Ybt44/
  4227. var rotation = this.rotation,
  4228. costheta = mathCos(rotation * deg2rad),
  4229. sintheta = mathSin(rotation * deg2rad);
  4230. css(this.element, {
  4231. filter: rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta,
  4232. ', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta,
  4233. ', sizingMethod=\'auto expand\')'].join('') : NONE
  4234. });
  4235. },
  4236. /**
  4237. * Get the positioning correction for the span after rotating.
  4238. */
  4239. getSpanCorrection: function (width, baseline, alignCorrection, rotation, align) {
  4240. var costheta = rotation ? mathCos(rotation * deg2rad) : 1,
  4241. sintheta = rotation ? mathSin(rotation * deg2rad) : 0,
  4242. height = pick(this.elemHeight, this.element.offsetHeight),
  4243. quad,
  4244. nonLeft = align && align !== 'left';
  4245. // correct x and y
  4246. this.xCorr = costheta < 0 && -width;
  4247. this.yCorr = sintheta < 0 && -height;
  4248. // correct for baseline and corners spilling out after rotation
  4249. quad = costheta * sintheta < 0;
  4250. this.xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection);
  4251. this.yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1);
  4252. // correct for the length/height of the text
  4253. if (nonLeft) {
  4254. this.xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1);
  4255. if (rotation) {
  4256. this.yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1);
  4257. }
  4258. css(this.element, {
  4259. textAlign: align
  4260. });
  4261. }
  4262. },
  4263. /**
  4264. * Converts a subset of an SVG path definition to its VML counterpart. Takes an array
  4265. * as the parameter and returns a string.
  4266. */
  4267. pathToVML: function (value) {
  4268. // convert paths
  4269. var i = value.length,
  4270. path = [];
  4271. while (i--) {
  4272. // Multiply by 10 to allow subpixel precision.
  4273. // Substracting half a pixel seems to make the coordinates
  4274. // align with SVG, but this hasn't been tested thoroughly
  4275. if (isNumber(value[i])) {
  4276. path[i] = mathRound(value[i] * 10) - 5;
  4277. } else if (value[i] === 'Z') { // close the path
  4278. path[i] = 'x';
  4279. } else {
  4280. path[i] = value[i];
  4281. // When the start X and end X coordinates of an arc are too close,
  4282. // they are rounded to the same value above. In this case, substract or
  4283. // add 1 from the end X and Y positions. #186, #760, #1371, #1410.
  4284. if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) {
  4285. // Start and end X
  4286. if (path[i + 5] === path[i + 7]) {
  4287. path[i + 7] += value[i + 7] > value[i + 5] ? 1 : -1;
  4288. }
  4289. // Start and end Y
  4290. if (path[i + 6] === path[i + 8]) {
  4291. path[i + 8] += value[i + 8] > value[i + 6] ? 1 : -1;
  4292. }
  4293. }
  4294. }
  4295. }
  4296. // Loop up again to handle path shortcuts (#2132)
  4297. /*while (i++ < path.length) {
  4298. if (path[i] === 'H') { // horizontal line to
  4299. path[i] = 'L';
  4300. path.splice(i + 2, 0, path[i - 1]);
  4301. } else if (path[i] === 'V') { // vertical line to
  4302. path[i] = 'L';
  4303. path.splice(i + 1, 0, path[i - 2]);
  4304. }
  4305. }*/
  4306. return path.join(' ') || 'x';
  4307. },
  4308. /**
  4309. * Set the element's clipping to a predefined rectangle
  4310. *
  4311. * @param {String} id The id of the clip rectangle
  4312. */
  4313. clip: function (clipRect) {
  4314. var wrapper = this,
  4315. clipMembers,
  4316. cssRet;
  4317. if (clipRect) {
  4318. clipMembers = clipRect.members;
  4319. erase(clipMembers, wrapper); // Ensure unique list of elements (#1258)
  4320. clipMembers.push(wrapper);
  4321. wrapper.destroyClip = function () {
  4322. erase(clipMembers, wrapper);
  4323. };
  4324. cssRet = clipRect.getCSS(wrapper);
  4325. } else {
  4326. if (wrapper.destroyClip) {
  4327. wrapper.destroyClip();
  4328. }
  4329. cssRet = { clip: docMode8 ? 'inherit' : 'rect(auto)' }; // #1214
  4330. }
  4331. return wrapper.css(cssRet);
  4332. },
  4333. /**
  4334. * Set styles for the element
  4335. * @param {Object} styles
  4336. */
  4337. css: SVGElement.prototype.htmlCss,
  4338. /**
  4339. * Removes a child either by removeChild or move to garbageBin.
  4340. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not.
  4341. */
  4342. safeRemoveChild: function (element) {
  4343. // discardElement will detach the node from its parent before attaching it
  4344. // to the garbage bin. Therefore it is important that the node is attached and have parent.
  4345. if (element.parentNode) {
  4346. discardElement(element);
  4347. }
  4348. },
  4349. /**
  4350. * Extend element.destroy by removing it from the clip members array
  4351. */
  4352. destroy: function () {
  4353. if (this.destroyClip) {
  4354. this.destroyClip();
  4355. }
  4356. return SVGElement.prototype.destroy.apply(this);
  4357. },
  4358. /**
  4359. * Add an event listener. VML override for normalizing event parameters.
  4360. * @param {String} eventType
  4361. * @param {Function} handler
  4362. */
  4363. on: function (eventType, handler) {
  4364. // simplest possible event model for internal use
  4365. this.element['on' + eventType] = function () {
  4366. var evt = win.event;
  4367. evt.target = evt.srcElement;
  4368. handler(evt);
  4369. };
  4370. return this;
  4371. },
  4372. /**
  4373. * In stacked columns, cut off the shadows so that they don't overlap
  4374. */
  4375. cutOffPath: function (path, length) {
  4376. var len;
  4377. path = path.split(/[ ,]/);
  4378. len = path.length;
  4379. if (len === 9 || len === 11) {
  4380. path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length;
  4381. }
  4382. return path.join(' ');
  4383. },
  4384. /**
  4385. * Apply a drop shadow by copying elements and giving them different strokes
  4386. * @param {Boolean|Object} shadowOptions
  4387. */
  4388. shadow: function (shadowOptions, group, cutOff) {
  4389. var shadows = [],
  4390. i,
  4391. element = this.element,
  4392. renderer = this.renderer,
  4393. shadow,
  4394. elemStyle = element.style,
  4395. markup,
  4396. path = element.path,
  4397. strokeWidth,
  4398. modifiedPath,
  4399. shadowWidth,
  4400. shadowElementOpacity;
  4401. // some times empty paths are not strings
  4402. if (path && typeof path.value !== 'string') {
  4403. path = 'x';
  4404. }
  4405. modifiedPath = path;
  4406. if (shadowOptions) {
  4407. shadowWidth = pick(shadowOptions.width, 3);
  4408. shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth;
  4409. for (i = 1; i <= 3; i++) {
  4410. strokeWidth = (shadowWidth * 2) + 1 - (2 * i);
  4411. // Cut off shadows for stacked column items
  4412. if (cutOff) {
  4413. modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5);
  4414. }
  4415. markup = ['<shape isShadow="true" strokeweight="', strokeWidth,
  4416. '" filled="false" path="', modifiedPath,
  4417. '" coordsize="10 10" style="', element.style.cssText, '" />'];
  4418. shadow = createElement(renderer.prepVML(markup),
  4419. null, {
  4420. left: pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1),
  4421. top: pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1)
  4422. }
  4423. );
  4424. if (cutOff) {
  4425. shadow.cutOff = strokeWidth + 1;
  4426. }
  4427. // apply the opacity
  4428. markup = ['<stroke color="', shadowOptions.color || 'black', '" opacity="', shadowElementOpacity * i, '"/>'];
  4429. createElement(renderer.prepVML(markup), null, null, shadow);
  4430. // insert it
  4431. if (group) {
  4432. group.element.appendChild(shadow);
  4433. } else {
  4434. element.parentNode.insertBefore(shadow, element);
  4435. }
  4436. // record it
  4437. shadows.push(shadow);
  4438. }
  4439. this.shadows = shadows;
  4440. }
  4441. return this;
  4442. },
  4443. updateShadows: noop, // Used in SVG only
  4444. setAttr: function (key, value) {
  4445. if (docMode8) { // IE8 setAttribute bug
  4446. this.element[key] = value;
  4447. } else {
  4448. this.element.setAttribute(key, value);
  4449. }
  4450. },
  4451. classSetter: function (value) {
  4452. // IE8 Standards mode has problems retrieving the className unless set like this
  4453. this.element.className = value;
  4454. },
  4455. dashstyleSetter: function (value, key, element) {
  4456. var strokeElem = element.getElementsByTagName('stroke')[0] ||
  4457. createElement(this.renderer.prepVML(['<stroke/>']), null, null, element);
  4458. strokeElem[key] = value || 'solid';
  4459. this[key] = value; /* because changing stroke-width will change the dash length
  4460. and cause an epileptic effect */
  4461. },
  4462. dSetter: function (value, key, element) {
  4463. var i,
  4464. shadows = this.shadows;
  4465. value = value || [];
  4466. this.d = value.join && value.join(' '); // used in getter for animation
  4467. element.path = value = this.pathToVML(value);
  4468. // update shadows
  4469. if (shadows) {
  4470. i = shadows.length;
  4471. while (i--) {
  4472. shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value;
  4473. }
  4474. }
  4475. this.setAttr(key, value);
  4476. },
  4477. fillSetter: function (value, key, element) {
  4478. var nodeName = element.nodeName;
  4479. if (nodeName === 'SPAN') { // text color
  4480. element.style.color = value;
  4481. } else if (nodeName !== 'IMG') { // #1336
  4482. element.filled = value !== NONE;
  4483. this.setAttr('fillcolor', this.renderer.color(value, element, key, this));
  4484. }
  4485. },
  4486. opacitySetter: noop, // Don't bother - animation is too slow and filters introduce artifacts
  4487. rotationSetter: function (value, key, element) {
  4488. var style = element.style;
  4489. this[key] = style[key] = value; // style is for #1873
  4490. // Correction for the 1x1 size of the shape container. Used in gauge needles.
  4491. style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX;
  4492. style.top = mathRound(mathCos(value * deg2rad)) + PX;
  4493. },
  4494. strokeSetter: function (value, key, element) {
  4495. this.setAttr('strokecolor', this.renderer.color(value, element, key));
  4496. },
  4497. 'stroke-widthSetter': function (value, key, element) {
  4498. element.stroked = !!value; // VML "stroked" attribute
  4499. this[key] = value; // used in getter, issue #113
  4500. if (isNumber(value)) {
  4501. value += PX;
  4502. }
  4503. this.setAttr('strokeweight', value);
  4504. },
  4505. titleSetter: function (value, key) {
  4506. this.setAttr(key, value);
  4507. },
  4508. visibilitySetter: function (value, key, element) {
  4509. // Handle inherited visibility
  4510. if (value === 'inherit') {
  4511. value = VISIBLE;
  4512. }
  4513. // Let the shadow follow the main element
  4514. if (this.shadows) {
  4515. each(this.shadows, function (shadow) {
  4516. shadow.style[key] = value;
  4517. });
  4518. }
  4519. // Instead of toggling the visibility CSS property, move the div out of the viewport.
  4520. // This works around #61 and #586
  4521. if (element.nodeName === 'DIV') {
  4522. value = value === HIDDEN ? '-999em' : 0;
  4523. // In order to redraw, IE7 needs the div to be visible when tucked away
  4524. // outside the viewport. So the visibility is actually opposite of
  4525. // the expected value. This applies to the tooltip only.
  4526. if (!docMode8) {
  4527. element.style[key] = value ? VISIBLE : HIDDEN;
  4528. }
  4529. key = 'top';
  4530. }
  4531. element.style[key] = value;
  4532. },
  4533. xSetter: function (value, key, element) {
  4534. this[key] = value; // used in getter
  4535. if (key === 'x') {
  4536. key = 'left';
  4537. } else if (key === 'y') {
  4538. key = 'top';
  4539. }/* else {
  4540. value = mathMax(0, value); // don't set width or height below zero (#311)
  4541. }*/
  4542. // clipping rectangle special
  4543. if (this.updateClipping) {
  4544. this[key] = value; // the key is now 'left' or 'top' for 'x' and 'y'
  4545. this.updateClipping();
  4546. } else {
  4547. // normal
  4548. element.style[key] = value;
  4549. }
  4550. },
  4551. zIndexSetter: function (value, key, element) {
  4552. element.style[key] = value;
  4553. }
  4554. };
  4555. Highcharts.VMLElement = VMLElement = extendClass(SVGElement, VMLElement);
  4556. // Some shared setters
  4557. VMLElement.prototype.ySetter =
  4558. VMLElement.prototype.widthSetter =
  4559. VMLElement.prototype.heightSetter =
  4560. VMLElement.prototype.xSetter;
  4561. /**
  4562. * The VML renderer
  4563. */
  4564. var VMLRendererExtension = { // inherit SVGRenderer
  4565. Element: VMLElement,
  4566. isIE8: userAgent.indexOf('MSIE 8.0') > -1,
  4567. /**
  4568. * Initialize the VMLRenderer
  4569. * @param {Object} container
  4570. * @param {Number} width
  4571. * @param {Number} height
  4572. */
  4573. init: function (container, width, height, style) {
  4574. var renderer = this,
  4575. boxWrapper,
  4576. box,
  4577. css;
  4578. renderer.alignedObjects = [];
  4579. boxWrapper = renderer.createElement(DIV)
  4580. .css(extend(this.getStyle(style), { position: RELATIVE}));
  4581. box = boxWrapper.element;
  4582. container.appendChild(boxWrapper.element);
  4583. // generate the containing box
  4584. renderer.isVML = true;
  4585. renderer.box = box;
  4586. renderer.boxWrapper = boxWrapper;
  4587. renderer.cache = {};
  4588. renderer.setSize(width, height, false);
  4589. // The only way to make IE6 and IE7 print is to use a global namespace. However,
  4590. // with IE8 the only way to make the dynamic shapes visible in screen and print mode
  4591. // seems to be to add the xmlns attribute and the behaviour style inline.
  4592. if (!doc.namespaces.hcv) {
  4593. doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml');
  4594. // Setup default CSS (#2153, #2368, #2384)
  4595. css = 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' +
  4596. '{ behavior:url(#default#VML); display: inline-block; } ';
  4597. try {
  4598. doc.createStyleSheet().cssText = css;
  4599. } catch (e) {
  4600. doc.styleSheets[0].cssText += css;
  4601. }
  4602. }
  4603. },
  4604. /**
  4605. * Detect whether the renderer is hidden. This happens when one of the parent elements
  4606. * has display: none
  4607. */
  4608. isHidden: function () {
  4609. return !this.box.offsetWidth;
  4610. },
  4611. /**
  4612. * Define a clipping rectangle. In VML it is accomplished by storing the values
  4613. * for setting the CSS style to all associated members.
  4614. *
  4615. * @param {Number} x
  4616. * @param {Number} y
  4617. * @param {Number} width
  4618. * @param {Number} height
  4619. */
  4620. clipRect: function (x, y, width, height) {
  4621. // create a dummy element
  4622. var clipRect = this.createElement(),
  4623. isObj = isObject(x);
  4624. // mimic a rectangle with its style object for automatic updating in attr
  4625. return extend(clipRect, {
  4626. members: [],
  4627. count: 0,
  4628. left: (isObj ? x.x : x) + 1,
  4629. top: (isObj ? x.y : y) + 1,
  4630. width: (isObj ? x.width : width) - 1,
  4631. height: (isObj ? x.height : height) - 1,
  4632. getCSS: function (wrapper) {
  4633. var element = wrapper.element,
  4634. nodeName = element.nodeName,
  4635. isShape = nodeName === 'shape',
  4636. inverted = wrapper.inverted,
  4637. rect = this,
  4638. top = rect.top - (isShape ? element.offsetTop : 0),
  4639. left = rect.left,
  4640. right = left + rect.width,
  4641. bottom = top + rect.height,
  4642. ret = {
  4643. clip: 'rect(' +
  4644. mathRound(inverted ? left : top) + 'px,' +
  4645. mathRound(inverted ? bottom : right) + 'px,' +
  4646. mathRound(inverted ? right : bottom) + 'px,' +
  4647. mathRound(inverted ? top : left) + 'px)'
  4648. };
  4649. // issue 74 workaround
  4650. if (!inverted && docMode8 && nodeName === 'DIV') {
  4651. extend(ret, {
  4652. width: right + PX,
  4653. height: bottom + PX
  4654. });
  4655. }
  4656. return ret;
  4657. },
  4658. // used in attr and animation to update the clipping of all members
  4659. updateClipping: function () {
  4660. each(clipRect.members, function (member) {
  4661. if (member.element) { // Deleted series, like in stock/members/series-remove demo. Should be removed from members, but this will do.
  4662. member.css(clipRect.getCSS(member));
  4663. }
  4664. });
  4665. }
  4666. });
  4667. },
  4668. /**
  4669. * Take a color and return it if it's a string, make it a gradient if it's a
  4670. * gradient configuration object, and apply opacity.
  4671. *
  4672. * @param {Object} color The color or config object
  4673. */
  4674. color: function (color, elem, prop, wrapper) {
  4675. var renderer = this,
  4676. colorObject,
  4677. regexRgba = /^rgba/,
  4678. markup,
  4679. fillType,
  4680. ret = NONE;
  4681. // Check for linear or radial gradient
  4682. if (color && color.linearGradient) {
  4683. fillType = 'gradient';
  4684. } else if (color && color.radialGradient) {
  4685. fillType = 'pattern';
  4686. }
  4687. if (fillType) {
  4688. var stopColor,
  4689. stopOpacity,
  4690. gradient = color.linearGradient || color.radialGradient,
  4691. x1,
  4692. y1,
  4693. x2,
  4694. y2,
  4695. opacity1,
  4696. opacity2,
  4697. color1,
  4698. color2,
  4699. fillAttr = '',
  4700. stops = color.stops,
  4701. firstStop,
  4702. lastStop,
  4703. colors = [],
  4704. addFillNode = function () {
  4705. // Add the fill subnode. When colors attribute is used, the meanings of opacity and o:opacity2
  4706. // are reversed.
  4707. markup = ['<fill colors="' + colors.join(',') + '" opacity="', opacity2, '" o:opacity2="', opacity1,
  4708. '" type="', fillType, '" ', fillAttr, 'focus="100%" method="any" />'];
  4709. createElement(renderer.prepVML(markup), null, null, elem);
  4710. };
  4711. // Extend from 0 to 1
  4712. firstStop = stops[0];
  4713. lastStop = stops[stops.length - 1];
  4714. if (firstStop[0] > 0) {
  4715. stops.unshift([
  4716. 0,
  4717. firstStop[1]
  4718. ]);
  4719. }
  4720. if (lastStop[0] < 1) {
  4721. stops.push([
  4722. 1,
  4723. lastStop[1]
  4724. ]);
  4725. }
  4726. // Compute the stops
  4727. each(stops, function (stop, i) {
  4728. if (regexRgba.test(stop[1])) {
  4729. colorObject = Color(stop[1]);
  4730. stopColor = colorObject.get('rgb');
  4731. stopOpacity = colorObject.get('a');
  4732. } else {
  4733. stopColor = stop[1];
  4734. stopOpacity = 1;
  4735. }
  4736. // Build the color attribute
  4737. colors.push((stop[0] * 100) + '% ' + stopColor);
  4738. // Only start and end opacities are allowed, so we use the first and the last
  4739. if (!i) {
  4740. opacity1 = stopOpacity;
  4741. color2 = stopColor;
  4742. } else {
  4743. opacity2 = stopOpacity;
  4744. color1 = stopColor;
  4745. }
  4746. });
  4747. // Apply the gradient to fills only.
  4748. if (prop === 'fill') {
  4749. // Handle linear gradient angle
  4750. if (fillType === 'gradient') {
  4751. x1 = gradient.x1 || gradient[0] || 0;
  4752. y1 = gradient.y1 || gradient[1] || 0;
  4753. x2 = gradient.x2 || gradient[2] || 0;
  4754. y2 = gradient.y2 || gradient[3] || 0;
  4755. fillAttr = 'angle="' + (90 - math.atan(
  4756. (y2 - y1) / // y vector
  4757. (x2 - x1) // x vector
  4758. ) * 180 / mathPI) + '"';
  4759. addFillNode();
  4760. // Radial (circular) gradient
  4761. } else {
  4762. var r = gradient.r,
  4763. sizex = r * 2,
  4764. sizey = r * 2,
  4765. cx = gradient.cx,
  4766. cy = gradient.cy,
  4767. radialReference = elem.radialReference,
  4768. bBox,
  4769. applyRadialGradient = function () {
  4770. if (radialReference) {
  4771. bBox = wrapper.getBBox();
  4772. cx += (radialReference[0] - bBox.x) / bBox.width - 0.5;
  4773. cy += (radialReference[1] - bBox.y) / bBox.height - 0.5;
  4774. sizex *= radialReference[2] / bBox.width;
  4775. sizey *= radialReference[2] / bBox.height;
  4776. }
  4777. fillAttr = 'src="' + defaultOptions.global.VMLRadialGradientURL + '" ' +
  4778. 'size="' + sizex + ',' + sizey + '" ' +
  4779. 'origin="0.5,0.5" ' +
  4780. 'position="' + cx + ',' + cy + '" ' +
  4781. 'color2="' + color2 + '" ';
  4782. addFillNode();
  4783. };
  4784. // Apply radial gradient
  4785. if (wrapper.added) {
  4786. applyRadialGradient();
  4787. } else {
  4788. // We need to know the bounding box to get the size and position right
  4789. wrapper.onAdd = applyRadialGradient;
  4790. }
  4791. // The fill element's color attribute is broken in IE8 standards mode, so we
  4792. // need to set the parent shape's fillcolor attribute instead.
  4793. ret = color1;
  4794. }
  4795. // Gradients are not supported for VML stroke, return the first color. #722.
  4796. } else {
  4797. ret = stopColor;
  4798. }
  4799. // if the color is an rgba color, split it and add a fill node
  4800. // to hold the opacity component
  4801. } else if (regexRgba.test(color) && elem.tagName !== 'IMG') {
  4802. colorObject = Color(color);
  4803. markup = ['<', prop, ' opacity="', colorObject.get('a'), '"/>'];
  4804. createElement(this.prepVML(markup), null, null, elem);
  4805. ret = colorObject.get('rgb');
  4806. } else {
  4807. var propNodes = elem.getElementsByTagName(prop); // 'stroke' or 'fill' node
  4808. if (propNodes.length) {
  4809. propNodes[0].opacity = 1;
  4810. propNodes[0].type = 'solid';
  4811. }
  4812. ret = color;
  4813. }
  4814. return ret;
  4815. },
  4816. /**
  4817. * Take a VML string and prepare it for either IE8 or IE6/IE7.
  4818. * @param {Array} markup A string array of the VML markup to prepare
  4819. */
  4820. prepVML: function (markup) {
  4821. var vmlStyle = 'display:inline-block;behavior:url(#default#VML);',
  4822. isIE8 = this.isIE8;
  4823. markup = markup.join('');
  4824. if (isIE8) { // add xmlns and style inline
  4825. markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />');
  4826. if (markup.indexOf('style="') === -1) {
  4827. markup = markup.replace('/>', ' style="' + vmlStyle + '" />');
  4828. } else {
  4829. markup = markup.replace('style="', 'style="' + vmlStyle);
  4830. }
  4831. } else { // add namespace
  4832. markup = markup.replace('<', '<hcv:');
  4833. }
  4834. return markup;
  4835. },
  4836. /**
  4837. * Create rotated and aligned text
  4838. * @param {String} str
  4839. * @param {Number} x
  4840. * @param {Number} y
  4841. */
  4842. text: SVGRenderer.prototype.html,
  4843. /**
  4844. * Create and return a path element
  4845. * @param {Array} path
  4846. */
  4847. path: function (path) {
  4848. var attr = {
  4849. // subpixel precision down to 0.1 (width and height = 1px)
  4850. coordsize: '10 10'
  4851. };
  4852. if (isArray(path)) {
  4853. attr.d = path;
  4854. } else if (isObject(path)) { // attributes
  4855. extend(attr, path);
  4856. }
  4857. // create the shape
  4858. return this.createElement('shape').attr(attr);
  4859. },
  4860. /**
  4861. * Create and return a circle element. In VML circles are implemented as
  4862. * shapes, which is faster than v:oval
  4863. * @param {Number} x
  4864. * @param {Number} y
  4865. * @param {Number} r
  4866. */
  4867. circle: function (x, y, r) {
  4868. var circle = this.symbol('circle');
  4869. if (isObject(x)) {
  4870. r = x.r;
  4871. y = x.y;
  4872. x = x.x;
  4873. }
  4874. circle.isCircle = true; // Causes x and y to mean center (#1682)
  4875. circle.r = r;
  4876. return circle.attr({ x: x, y: y });
  4877. },
  4878. /**
  4879. * Create a group using an outer div and an inner v:group to allow rotating
  4880. * and flipping. A simple v:group would have problems with positioning
  4881. * child HTML elements and CSS clip.
  4882. *
  4883. * @param {String} name The name of the group
  4884. */
  4885. g: function (name) {
  4886. var wrapper,
  4887. attribs;
  4888. // set the class name
  4889. if (name) {
  4890. attribs = { 'className': PREFIX + name, 'class': PREFIX + name };
  4891. }
  4892. // the div to hold HTML and clipping
  4893. wrapper = this.createElement(DIV).attr(attribs);
  4894. return wrapper;
  4895. },
  4896. /**
  4897. * VML override to create a regular HTML image
  4898. * @param {String} src
  4899. * @param {Number} x
  4900. * @param {Number} y
  4901. * @param {Number} width
  4902. * @param {Number} height
  4903. */
  4904. image: function (src, x, y, width, height) {
  4905. var obj = this.createElement('img')
  4906. .attr({ src: src });
  4907. if (arguments.length > 1) {
  4908. obj.attr({
  4909. x: x,
  4910. y: y,
  4911. width: width,
  4912. height: height
  4913. });
  4914. }
  4915. return obj;
  4916. },
  4917. /**
  4918. * For rectangles, VML uses a shape for rect to overcome bugs and rotation problems
  4919. */
  4920. createElement: function (nodeName) {
  4921. return nodeName === 'rect' ? this.symbol(nodeName) : SVGRenderer.prototype.createElement.call(this, nodeName);
  4922. },
  4923. /**
  4924. * In the VML renderer, each child of an inverted div (group) is inverted
  4925. * @param {Object} element
  4926. * @param {Object} parentNode
  4927. */
  4928. invertChild: function (element, parentNode) {
  4929. var ren = this,
  4930. parentStyle = parentNode.style,
  4931. imgStyle = element.tagName === 'IMG' && element.style; // #1111
  4932. css(element, {
  4933. flip: 'x',
  4934. left: pInt(parentStyle.width) - (imgStyle ? pInt(imgStyle.top) : 1),
  4935. top: pInt(parentStyle.height) - (imgStyle ? pInt(imgStyle.left) : 1),
  4936. rotation: -90
  4937. });
  4938. // Recursively invert child elements, needed for nested composite shapes like box plots and error bars. #1680, #1806.
  4939. each(element.childNodes, function (child) {
  4940. ren.invertChild(child, element);
  4941. });
  4942. },
  4943. /**
  4944. * Symbol definitions that override the parent SVG renderer's symbols
  4945. *
  4946. */
  4947. symbols: {
  4948. // VML specific arc function
  4949. arc: function (x, y, w, h, options) {
  4950. var start = options.start,
  4951. end = options.end,
  4952. radius = options.r || w || h,
  4953. innerRadius = options.innerR,
  4954. cosStart = mathCos(start),
  4955. sinStart = mathSin(start),
  4956. cosEnd = mathCos(end),
  4957. sinEnd = mathSin(end),
  4958. ret;
  4959. if (end - start === 0) { // no angle, don't show it.
  4960. return ['x'];
  4961. }
  4962. ret = [
  4963. 'wa', // clockwise arc to
  4964. x - radius, // left
  4965. y - radius, // top
  4966. x + radius, // right
  4967. y + radius, // bottom
  4968. x + radius * cosStart, // start x
  4969. y + radius * sinStart, // start y
  4970. x + radius * cosEnd, // end x
  4971. y + radius * sinEnd // end y
  4972. ];
  4973. if (options.open && !innerRadius) {
  4974. ret.push(
  4975. 'e',
  4976. M,
  4977. x,// - innerRadius,
  4978. y// - innerRadius
  4979. );
  4980. }
  4981. ret.push(
  4982. 'at', // anti clockwise arc to
  4983. x - innerRadius, // left
  4984. y - innerRadius, // top
  4985. x + innerRadius, // right
  4986. y + innerRadius, // bottom
  4987. x + innerRadius * cosEnd, // start x
  4988. y + innerRadius * sinEnd, // start y
  4989. x + innerRadius * cosStart, // end x
  4990. y + innerRadius * sinStart, // end y
  4991. 'x', // finish path
  4992. 'e' // close
  4993. );
  4994. ret.isArc = true;
  4995. return ret;
  4996. },
  4997. // Add circle symbol path. This performs significantly faster than v:oval.
  4998. circle: function (x, y, w, h, wrapper) {
  4999. if (wrapper) {
  5000. w = h = 2 * wrapper.r;
  5001. }
  5002. // Center correction, #1682
  5003. if (wrapper && wrapper.isCircle) {
  5004. x -= w / 2;
  5005. y -= h / 2;
  5006. }
  5007. // Return the path
  5008. return [
  5009. 'wa', // clockwisearcto
  5010. x, // left
  5011. y, // top
  5012. x + w, // right
  5013. y + h, // bottom
  5014. x + w, // start x
  5015. y + h / 2, // start y
  5016. x + w, // end x
  5017. y + h / 2, // end y
  5018. //'x', // finish path
  5019. 'e' // close
  5020. ];
  5021. },
  5022. /**
  5023. * Add rectangle symbol path which eases rotation and omits arcsize problems
  5024. * compared to the built-in VML roundrect shape. When borders are not rounded,
  5025. * use the simpler square path, else use the callout path without the arrow.
  5026. */
  5027. rect: function (x, y, w, h, options) {
  5028. return SVGRenderer.prototype.symbols[
  5029. !defined(options) || !options.r ? 'square' : 'callout'
  5030. ].call(0, x, y, w, h, options);
  5031. }
  5032. }
  5033. };
  5034. Highcharts.VMLRenderer = VMLRenderer = function () {
  5035. this.init.apply(this, arguments);
  5036. };
  5037. VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension);
  5038. // general renderer
  5039. Renderer = VMLRenderer;
  5040. }
  5041. // This method is used with exporting in old IE, when emulating SVG (see #2314)
  5042. SVGRenderer.prototype.measureSpanWidth = function (text, styles) {
  5043. var measuringSpan = doc.createElement('span'),
  5044. offsetWidth,
  5045. textNode = doc.createTextNode(text);
  5046. measuringSpan.appendChild(textNode);
  5047. css(measuringSpan, styles);
  5048. this.box.appendChild(measuringSpan);
  5049. offsetWidth = measuringSpan.offsetWidth;
  5050. discardElement(measuringSpan); // #2463
  5051. return offsetWidth;
  5052. };
  5053. /* ****************************************************************************
  5054. * *
  5055. * END OF INTERNET EXPLORER <= 8 SPECIFIC CODE *
  5056. * *
  5057. *****************************************************************************/
  5058. /* ****************************************************************************
  5059. * *
  5060. * START OF ANDROID < 3 SPECIFIC CODE. THIS CAN BE REMOVED IF YOU'RE NOT *
  5061. * TARGETING THAT SYSTEM. *
  5062. * *
  5063. *****************************************************************************/
  5064. var CanVGRenderer,
  5065. CanVGController;
  5066. if (useCanVG) {
  5067. /**
  5068. * The CanVGRenderer is empty from start to keep the source footprint small.
  5069. * When requested, the CanVGController downloads the rest of the source packaged
  5070. * together with the canvg library.
  5071. */
  5072. Highcharts.CanVGRenderer = CanVGRenderer = function () {
  5073. // Override the global SVG namespace to fake SVG/HTML that accepts CSS
  5074. SVG_NS = 'http://www.w3.org/1999/xhtml';
  5075. };
  5076. /**
  5077. * Start with an empty symbols object. This is needed when exporting is used (exporting.src.js will add a few symbols), but
  5078. * the implementation from SvgRenderer will not be merged in until first render.
  5079. */
  5080. CanVGRenderer.prototype.symbols = {};
  5081. /**
  5082. * Handles on demand download of canvg rendering support.
  5083. */
  5084. CanVGController = (function () {
  5085. // List of renderering calls
  5086. var deferredRenderCalls = [];
  5087. /**
  5088. * When downloaded, we are ready to draw deferred charts.
  5089. */
  5090. function drawDeferred() {
  5091. var callLength = deferredRenderCalls.length,
  5092. callIndex;
  5093. // Draw all pending render calls
  5094. for (callIndex = 0; callIndex < callLength; callIndex++) {
  5095. deferredRenderCalls[callIndex]();
  5096. }
  5097. // Clear the list
  5098. deferredRenderCalls = [];
  5099. }
  5100. return {
  5101. push: function (func, scriptLocation) {
  5102. // Only get the script once
  5103. if (deferredRenderCalls.length === 0) {
  5104. getScript(scriptLocation, drawDeferred);
  5105. }
  5106. // Register render call
  5107. deferredRenderCalls.push(func);
  5108. }
  5109. };
  5110. }());
  5111. Renderer = CanVGRenderer;
  5112. } // end CanVGRenderer
  5113. /* ****************************************************************************
  5114. * *
  5115. * END OF ANDROID < 3 SPECIFIC CODE *
  5116. * *
  5117. *****************************************************************************/
  5118. /**
  5119. * The Tick class
  5120. */
  5121. function Tick(axis, pos, type, noLabel) {
  5122. this.axis = axis;
  5123. this.pos = pos;
  5124. this.type = type || '';
  5125. this.isNew = true;
  5126. if (!type && !noLabel) {
  5127. this.addLabel();
  5128. }
  5129. }
  5130. Tick.prototype = {
  5131. /**
  5132. * Write the tick label
  5133. */
  5134. addLabel: function () {
  5135. var tick = this,
  5136. axis = tick.axis,
  5137. options = axis.options,
  5138. chart = axis.chart,
  5139. categories = axis.categories,
  5140. names = axis.names,
  5141. pos = tick.pos,
  5142. labelOptions = options.labels,
  5143. str,
  5144. tickPositions = axis.tickPositions,
  5145. isFirst = pos === tickPositions[0],
  5146. isLast = pos === tickPositions[tickPositions.length - 1],
  5147. value = categories ?
  5148. pick(categories[pos], names[pos], pos) :
  5149. pos,
  5150. label = tick.label,
  5151. tickPositionInfo = tickPositions.info,
  5152. dateTimeLabelFormat;
  5153. // Set the datetime label format. If a higher rank is set for this position, use that. If not,
  5154. // use the general format.
  5155. if (axis.isDatetimeAxis && tickPositionInfo) {
  5156. dateTimeLabelFormat = options.dateTimeLabelFormats[tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName];
  5157. }
  5158. // set properties for access in render method
  5159. tick.isFirst = isFirst;
  5160. tick.isLast = isLast;
  5161. // get the string
  5162. str = axis.labelFormatter.call({
  5163. axis: axis,
  5164. chart: chart,
  5165. isFirst: isFirst,
  5166. isLast: isLast,
  5167. dateTimeLabelFormat: dateTimeLabelFormat,
  5168. value: axis.isLog ? correctFloat(lin2log(value)) : value
  5169. });
  5170. // prepare CSS
  5171. //css = width && { width: mathMax(1, mathRound(width - 2 * (labelOptions.padding || 10))) + PX };
  5172. // first call
  5173. if (!defined(label)) {
  5174. tick.label = label =
  5175. defined(str) && labelOptions.enabled ?
  5176. chart.renderer.text(
  5177. str,
  5178. 0,
  5179. 0,
  5180. labelOptions.useHTML
  5181. )
  5182. //.attr(attr)
  5183. // without position absolute, IE export sometimes is wrong
  5184. .css(merge(labelOptions.style))
  5185. .add(axis.labelGroup) :
  5186. null;
  5187. tick.labelLength = label && label.getBBox().width; // Un-rotated length
  5188. tick.rotation = 0; // Base value to detect change for new calls to getBBox
  5189. // update
  5190. } else if (label) {
  5191. label.attr({ text: str });
  5192. }
  5193. },
  5194. /**
  5195. * Get the offset height or width of the label
  5196. */
  5197. getLabelSize: function () {
  5198. return this.label ?
  5199. this.label.getBBox()[this.axis.horiz ? 'height' : 'width'] :
  5200. 0;
  5201. },
  5202. /**
  5203. * Handle the label overflow by adjusting the labels to the left and right edge, or
  5204. * hide them if they collide into the neighbour label.
  5205. */
  5206. handleOverflow: function (xy) {
  5207. var axis = this.axis,
  5208. pxPos = xy.x,
  5209. chartWidth = axis.chart.chartWidth,
  5210. spacing = axis.chart.spacing,
  5211. leftBound = pick(axis.labelLeft, mathMin(axis.pos, spacing[3])),
  5212. rightBound = pick(axis.labelRight, mathMax(axis.pos + axis.len, chartWidth - spacing[1])),
  5213. label = this.label,
  5214. rotation = this.rotation,
  5215. factor = { left: 0, center: 0.5, right: 1 }[axis.labelAlign],
  5216. labelWidth = label.getBBox().width,
  5217. slotWidth = axis.slotWidth,
  5218. xCorrection = factor,
  5219. goRight = 1,
  5220. leftPos,
  5221. rightPos,
  5222. textWidth,
  5223. css = {};
  5224. // Check if the label overshoots the chart spacing box. If it does, move it.
  5225. // If it now overshoots the slotWidth, add ellipsis.
  5226. if (!rotation) {
  5227. leftPos = pxPos - factor * labelWidth;
  5228. rightPos = pxPos + (1 - factor) * labelWidth;
  5229. if (leftPos < leftBound) {
  5230. slotWidth = xy.x + slotWidth * (1 - factor) - leftBound;
  5231. } else if (rightPos > rightBound) {
  5232. slotWidth = rightBound - xy.x + slotWidth * factor;
  5233. goRight = -1;
  5234. }
  5235. slotWidth = mathMin(axis.slotWidth, slotWidth); // #4177
  5236. if (slotWidth < axis.slotWidth && axis.labelAlign === 'center') {
  5237. xy.x += goRight * (axis.slotWidth - slotWidth - xCorrection * (axis.slotWidth - mathMin(labelWidth, slotWidth)));
  5238. }
  5239. // If the label width exceeds the available space, set a text width to be
  5240. // picked up below. Also, if a width has been set before, we need to set a new
  5241. // one because the reported labelWidth will be limited by the box (#3938).
  5242. if (labelWidth > slotWidth || (axis.autoRotation && label.styles.width)) {
  5243. textWidth = slotWidth;
  5244. }
  5245. // Add ellipsis to prevent rotated labels to be clipped against the edge of the chart
  5246. } else if (rotation < 0 && pxPos - factor * labelWidth < leftBound) {
  5247. textWidth = mathRound(pxPos / mathCos(rotation * deg2rad) - leftBound);
  5248. } else if (rotation > 0 && pxPos + factor * labelWidth > rightBound) {
  5249. textWidth = mathRound((chartWidth - pxPos) / mathCos(rotation * deg2rad));
  5250. }
  5251. if (textWidth) {
  5252. css.width = textWidth;
  5253. if (!axis.options.labels.style.textOverflow) {
  5254. css.textOverflow = 'ellipsis';
  5255. }
  5256. label.css(css);
  5257. }
  5258. },
  5259. /**
  5260. * Get the x and y position for ticks and labels
  5261. */
  5262. getPosition: function (horiz, pos, tickmarkOffset, old) {
  5263. var axis = this.axis,
  5264. chart = axis.chart,
  5265. cHeight = (old && chart.oldChartHeight) || chart.chartHeight;
  5266. return {
  5267. x: horiz ?
  5268. axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB :
  5269. axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0),
  5270. y: horiz ?
  5271. cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) :
  5272. cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB
  5273. };
  5274. },
  5275. /**
  5276. * Get the x, y position of the tick label
  5277. */
  5278. getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) {
  5279. var axis = this.axis,
  5280. transA = axis.transA,
  5281. reversed = axis.reversed,
  5282. staggerLines = axis.staggerLines,
  5283. rotCorr = axis.tickRotCorr || { x: 0, y: 0 },
  5284. yOffset = pick(labelOptions.y, rotCorr.y + (axis.side === 2 ? 8 : -(label.getBBox().height / 2))),
  5285. line;
  5286. x = x + labelOptions.x + rotCorr.x - (tickmarkOffset && horiz ?
  5287. tickmarkOffset * transA * (reversed ? -1 : 1) : 0);
  5288. y = y + yOffset - (tickmarkOffset && !horiz ?
  5289. tickmarkOffset * transA * (reversed ? 1 : -1) : 0);
  5290. // Correct for staggered labels
  5291. if (staggerLines) {
  5292. line = (index / (step || 1) % staggerLines);
  5293. y += line * (axis.labelOffset / staggerLines);
  5294. }
  5295. return {
  5296. x: x,
  5297. y: mathRound(y)
  5298. };
  5299. },
  5300. /**
  5301. * Extendible method to return the path of the marker
  5302. */
  5303. getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) {
  5304. return renderer.crispLine([
  5305. M,
  5306. x,
  5307. y,
  5308. L,
  5309. x + (horiz ? 0 : -tickLength),
  5310. y + (horiz ? tickLength : 0)
  5311. ], tickWidth);
  5312. },
  5313. /**
  5314. * Put everything in place
  5315. *
  5316. * @param index {Number}
  5317. * @param old {Boolean} Use old coordinates to prepare an animation into new position
  5318. */
  5319. render: function (index, old, opacity) {
  5320. var tick = this,
  5321. axis = tick.axis,
  5322. options = axis.options,
  5323. chart = axis.chart,
  5324. renderer = chart.renderer,
  5325. horiz = axis.horiz,
  5326. type = tick.type,
  5327. label = tick.label,
  5328. pos = tick.pos,
  5329. labelOptions = options.labels,
  5330. gridLine = tick.gridLine,
  5331. gridPrefix = type ? type + 'Grid' : 'grid',
  5332. tickPrefix = type ? type + 'Tick' : 'tick',
  5333. gridLineWidth = options[gridPrefix + 'LineWidth'],
  5334. gridLineColor = options[gridPrefix + 'LineColor'],
  5335. dashStyle = options[gridPrefix + 'LineDashStyle'],
  5336. tickLength = options[tickPrefix + 'Length'],
  5337. tickWidth = pick(options[tickPrefix + 'Width'], !type && axis.isXAxis ? 1 : 0), // X axis defaults to 1
  5338. tickColor = options[tickPrefix + 'Color'],
  5339. tickPosition = options[tickPrefix + 'Position'],
  5340. gridLinePath,
  5341. mark = tick.mark,
  5342. markPath,
  5343. step = /*axis.labelStep || */labelOptions.step,
  5344. attribs,
  5345. show = true,
  5346. tickmarkOffset = axis.tickmarkOffset,
  5347. xy = tick.getPosition(horiz, pos, tickmarkOffset, old),
  5348. x = xy.x,
  5349. y = xy.y,
  5350. reverseCrisp = ((horiz && x === axis.pos + axis.len) || (!horiz && y === axis.pos)) ? -1 : 1; // #1480, #1687
  5351. opacity = pick(opacity, 1);
  5352. this.isActive = true;
  5353. // create the grid line
  5354. if (gridLineWidth) {
  5355. gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLineWidth * reverseCrisp, old, true);
  5356. if (gridLine === UNDEFINED) {
  5357. attribs = {
  5358. stroke: gridLineColor,
  5359. 'stroke-width': gridLineWidth
  5360. };
  5361. if (dashStyle) {
  5362. attribs.dashstyle = dashStyle;
  5363. }
  5364. if (!type) {
  5365. attribs.zIndex = 1;
  5366. }
  5367. if (old) {
  5368. attribs.opacity = 0;
  5369. }
  5370. tick.gridLine = gridLine =
  5371. gridLineWidth ?
  5372. renderer.path(gridLinePath)
  5373. .attr(attribs).add(axis.gridGroup) :
  5374. null;
  5375. }
  5376. // If the parameter 'old' is set, the current call will be followed
  5377. // by another call, therefore do not do any animations this time
  5378. if (!old && gridLine && gridLinePath) {
  5379. gridLine[tick.isNew ? 'attr' : 'animate']({
  5380. d: gridLinePath,
  5381. opacity: opacity
  5382. });
  5383. }
  5384. }
  5385. // create the tick mark
  5386. if (tickWidth && tickLength) {
  5387. // negate the length
  5388. if (tickPosition === 'inside') {
  5389. tickLength = -tickLength;
  5390. }
  5391. if (axis.opposite) {
  5392. tickLength = -tickLength;
  5393. }
  5394. markPath = tick.getMarkPath(x, y, tickLength, tickWidth * reverseCrisp, horiz, renderer);
  5395. if (mark) { // updating
  5396. mark.animate({
  5397. d: markPath,
  5398. opacity: opacity
  5399. });
  5400. } else { // first time
  5401. tick.mark = renderer.path(
  5402. markPath
  5403. ).attr({
  5404. stroke: tickColor,
  5405. 'stroke-width': tickWidth,
  5406. opacity: opacity
  5407. }).add(axis.axisGroup);
  5408. }
  5409. }
  5410. // the label is created on init - now move it into place
  5411. if (label && !isNaN(x)) {
  5412. label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step);
  5413. // Apply show first and show last. If the tick is both first and last, it is
  5414. // a single centered tick, in which case we show the label anyway (#2100).
  5415. if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) ||
  5416. (tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) {
  5417. show = false;
  5418. // Handle label overflow and show or hide accordingly
  5419. } else if (horiz && !axis.isRadial && !labelOptions.step && !labelOptions.rotation && !old && opacity !== 0) {
  5420. tick.handleOverflow(xy);
  5421. }
  5422. // apply step
  5423. if (step && index % step) {
  5424. // show those indices dividable by step
  5425. show = false;
  5426. }
  5427. // Set the new position, and show or hide
  5428. if (show && !isNaN(xy.y)) {
  5429. xy.opacity = opacity;
  5430. label[tick.isNew ? 'attr' : 'animate'](xy);
  5431. tick.isNew = false;
  5432. } else {
  5433. label.attr('y', -9999); // #1338
  5434. }
  5435. }
  5436. },
  5437. /**
  5438. * Destructor for the tick prototype
  5439. */
  5440. destroy: function () {
  5441. destroyObjectProperties(this, this.axis);
  5442. }
  5443. };
  5444. /**
  5445. * The object wrapper for plot lines and plot bands
  5446. * @param {Object} options
  5447. */
  5448. Highcharts.PlotLineOrBand = function (axis, options) {
  5449. this.axis = axis;
  5450. if (options) {
  5451. this.options = options;
  5452. this.id = options.id;
  5453. }
  5454. };
  5455. Highcharts.PlotLineOrBand.prototype = {
  5456. /**
  5457. * Render the plot line or plot band. If it is already existing,
  5458. * move it.
  5459. */
  5460. render: function () {
  5461. var plotLine = this,
  5462. axis = plotLine.axis,
  5463. horiz = axis.horiz,
  5464. options = plotLine.options,
  5465. optionsLabel = options.label,
  5466. label = plotLine.label,
  5467. width = options.width,
  5468. to = options.to,
  5469. from = options.from,
  5470. isBand = defined(from) && defined(to),
  5471. value = options.value,
  5472. dashStyle = options.dashStyle,
  5473. svgElem = plotLine.svgElem,
  5474. path = [],
  5475. addEvent,
  5476. eventType,
  5477. xs,
  5478. ys,
  5479. x,
  5480. y,
  5481. color = options.color,
  5482. zIndex = options.zIndex,
  5483. events = options.events,
  5484. attribs = {},
  5485. renderer = axis.chart.renderer;
  5486. // logarithmic conversion
  5487. if (axis.isLog) {
  5488. from = log2lin(from);
  5489. to = log2lin(to);
  5490. value = log2lin(value);
  5491. }
  5492. // plot line
  5493. if (width) {
  5494. path = axis.getPlotLinePath(value, width);
  5495. attribs = {
  5496. stroke: color,
  5497. 'stroke-width': width
  5498. };
  5499. if (dashStyle) {
  5500. attribs.dashstyle = dashStyle;
  5501. }
  5502. } else if (isBand) { // plot band
  5503. path = axis.getPlotBandPath(from, to, options);
  5504. if (color) {
  5505. attribs.fill = color;
  5506. }
  5507. if (options.borderWidth) {
  5508. attribs.stroke = options.borderColor;
  5509. attribs['stroke-width'] = options.borderWidth;
  5510. }
  5511. } else {
  5512. return;
  5513. }
  5514. // zIndex
  5515. if (defined(zIndex)) {
  5516. attribs.zIndex = zIndex;
  5517. }
  5518. // common for lines and bands
  5519. if (svgElem) {
  5520. if (path) {
  5521. svgElem.animate({
  5522. d: path
  5523. }, null, svgElem.onGetPath);
  5524. } else {
  5525. svgElem.hide();
  5526. svgElem.onGetPath = function () {
  5527. svgElem.show();
  5528. };
  5529. if (label) {
  5530. plotLine.label = label = label.destroy();
  5531. }
  5532. }
  5533. } else if (path && path.length) {
  5534. plotLine.svgElem = svgElem = renderer.path(path)
  5535. .attr(attribs).add();
  5536. // events
  5537. if (events) {
  5538. addEvent = function (eventType) {
  5539. svgElem.on(eventType, function (e) {
  5540. events[eventType].apply(plotLine, [e]);
  5541. });
  5542. };
  5543. for (eventType in events) {
  5544. addEvent(eventType);
  5545. }
  5546. }
  5547. }
  5548. // the plot band/line label
  5549. if (optionsLabel && defined(optionsLabel.text) && path && path.length && axis.width > 0 && axis.height > 0) {
  5550. // apply defaults
  5551. optionsLabel = merge({
  5552. align: horiz && isBand && 'center',
  5553. x: horiz ? !isBand && 4 : 10,
  5554. verticalAlign : !horiz && isBand && 'middle',
  5555. y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4,
  5556. rotation: horiz && !isBand && 90
  5557. }, optionsLabel);
  5558. // add the SVG element
  5559. if (!label) {
  5560. attribs = {
  5561. align: optionsLabel.textAlign || optionsLabel.align,
  5562. rotation: optionsLabel.rotation
  5563. };
  5564. if (defined(zIndex)) {
  5565. attribs.zIndex = zIndex;
  5566. }
  5567. plotLine.label = label = renderer.text(
  5568. optionsLabel.text,
  5569. 0,
  5570. 0,
  5571. optionsLabel.useHTML
  5572. )
  5573. .attr(attribs)
  5574. .css(optionsLabel.style)
  5575. .add();
  5576. }
  5577. // get the bounding box and align the label
  5578. // #3000 changed to better handle choice between plotband or plotline
  5579. xs = [path[1], path[4], (isBand ? path[6] : path[1])];
  5580. ys = [path[2], path[5], (isBand ? path[7] : path[2])];
  5581. x = arrayMin(xs);
  5582. y = arrayMin(ys);
  5583. label.align(optionsLabel, false, {
  5584. x: x,
  5585. y: y,
  5586. width: arrayMax(xs) - x,
  5587. height: arrayMax(ys) - y
  5588. });
  5589. label.show();
  5590. } else if (label) { // move out of sight
  5591. label.hide();
  5592. }
  5593. // chainable
  5594. return plotLine;
  5595. },
  5596. /**
  5597. * Remove the plot line or band
  5598. */
  5599. destroy: function () {
  5600. // remove it from the lookup
  5601. erase(this.axis.plotLinesAndBands, this);
  5602. delete this.axis;
  5603. destroyObjectProperties(this);
  5604. }
  5605. };
  5606. /**
  5607. * Object with members for extending the Axis prototype
  5608. */
  5609. AxisPlotLineOrBandExtension = {
  5610. /**
  5611. * Create the path for a plot band
  5612. */
  5613. getPlotBandPath: function (from, to) {
  5614. var toPath = this.getPlotLinePath(to, null, null, true),
  5615. path = this.getPlotLinePath(from, null, null, true);
  5616. if (path && toPath && path.toString() !== toPath.toString()) { // #3836
  5617. path.push(
  5618. toPath[4],
  5619. toPath[5],
  5620. toPath[1],
  5621. toPath[2]
  5622. );
  5623. } else { // outside the axis area
  5624. path = null;
  5625. }
  5626. return path;
  5627. },
  5628. addPlotBand: function (options) {
  5629. return this.addPlotBandOrLine(options, 'plotBands');
  5630. },
  5631. addPlotLine: function (options) {
  5632. return this.addPlotBandOrLine(options, 'plotLines');
  5633. },
  5634. /**
  5635. * Add a plot band or plot line after render time
  5636. *
  5637. * @param options {Object} The plotBand or plotLine configuration object
  5638. */
  5639. addPlotBandOrLine: function (options, coll) {
  5640. var obj = new Highcharts.PlotLineOrBand(this, options).render(),
  5641. userOptions = this.userOptions;
  5642. if (obj) { // #2189
  5643. // Add it to the user options for exporting and Axis.update
  5644. if (coll) {
  5645. userOptions[coll] = userOptions[coll] || [];
  5646. userOptions[coll].push(options);
  5647. }
  5648. this.plotLinesAndBands.push(obj);
  5649. }
  5650. return obj;
  5651. },
  5652. /**
  5653. * Remove a plot band or plot line from the chart by id
  5654. * @param {Object} id
  5655. */
  5656. removePlotBandOrLine: function (id) {
  5657. var plotLinesAndBands = this.plotLinesAndBands,
  5658. options = this.options,
  5659. userOptions = this.userOptions,
  5660. i = plotLinesAndBands.length;
  5661. while (i--) {
  5662. if (plotLinesAndBands[i].id === id) {
  5663. plotLinesAndBands[i].destroy();
  5664. }
  5665. }
  5666. each([options.plotLines || [], userOptions.plotLines || [], options.plotBands || [], userOptions.plotBands || []], function (arr) {
  5667. i = arr.length;
  5668. while (i--) {
  5669. if (arr[i].id === id) {
  5670. erase(arr, arr[i]);
  5671. }
  5672. }
  5673. });
  5674. }
  5675. };
  5676. /**
  5677. * Create a new axis object
  5678. * @param {Object} chart
  5679. * @param {Object} options
  5680. */
  5681. var Axis = Highcharts.Axis = function () {
  5682. this.init.apply(this, arguments);
  5683. };
  5684. Axis.prototype = {
  5685. /**
  5686. * Default options for the X axis - the Y axis has extended defaults
  5687. */
  5688. defaultOptions: {
  5689. // allowDecimals: null,
  5690. // alternateGridColor: null,
  5691. // categories: [],
  5692. dateTimeLabelFormats: {
  5693. millisecond: '%H:%M:%S.%L',
  5694. second: '%H:%M:%S',
  5695. minute: '%H:%M',
  5696. hour: '%H:%M',
  5697. day: '%e. %b',
  5698. week: '%e. %b',
  5699. month: '%b \'%y',
  5700. year: '%Y'
  5701. },
  5702. endOnTick: false,
  5703. gridLineColor: '#D8D8D8',
  5704. // gridLineDashStyle: 'solid',
  5705. // gridLineWidth: 0,
  5706. // reversed: false,
  5707. labels: {
  5708. enabled: true,
  5709. // rotation: 0,
  5710. // align: 'center',
  5711. // step: null,
  5712. style: {
  5713. color: '#606060',
  5714. cursor: 'default',
  5715. fontSize: '11px'
  5716. },
  5717. x: 0,
  5718. y: 15
  5719. /*formatter: function () {
  5720. return this.value;
  5721. },*/
  5722. },
  5723. lineColor: '#C0D0E0',
  5724. lineWidth: 1,
  5725. //linkedTo: null,
  5726. //max: undefined,
  5727. //min: undefined,
  5728. minPadding: 0.01,
  5729. maxPadding: 0.01,
  5730. //minRange: null,
  5731. minorGridLineColor: '#E0E0E0',
  5732. // minorGridLineDashStyle: null,
  5733. minorGridLineWidth: 1,
  5734. minorTickColor: '#A0A0A0',
  5735. //minorTickInterval: null,
  5736. minorTickLength: 2,
  5737. minorTickPosition: 'outside', // inside or outside
  5738. //minorTickWidth: 0,
  5739. //opposite: false,
  5740. //offset: 0,
  5741. //plotBands: [{
  5742. // events: {},
  5743. // zIndex: 1,
  5744. // labels: { align, x, verticalAlign, y, style, rotation, textAlign }
  5745. //}],
  5746. //plotLines: [{
  5747. // events: {}
  5748. // dashStyle: {}
  5749. // zIndex:
  5750. // labels: { align, x, verticalAlign, y, style, rotation, textAlign }
  5751. //}],
  5752. //reversed: false,
  5753. // showFirstLabel: true,
  5754. // showLastLabel: true,
  5755. startOfWeek: 1,
  5756. startOnTick: false,
  5757. tickColor: '#C0D0E0',
  5758. //tickInterval: null,
  5759. tickLength: 10,
  5760. tickmarkPlacement: 'between', // on or between
  5761. tickPixelInterval: 100,
  5762. tickPosition: 'outside',
  5763. //tickWidth: 1,
  5764. title: {
  5765. //text: null,
  5766. align: 'middle', // low, middle or high
  5767. //margin: 0 for horizontal, 10 for vertical axes,
  5768. //rotation: 0,
  5769. //side: 'outside',
  5770. style: {
  5771. color: '#707070'
  5772. }
  5773. //x: 0,
  5774. //y: 0
  5775. },
  5776. type: 'linear' // linear, logarithmic or datetime
  5777. //visible: true
  5778. },
  5779. /**
  5780. * This options set extends the defaultOptions for Y axes
  5781. */
  5782. defaultYAxisOptions: {
  5783. endOnTick: true,
  5784. gridLineWidth: 1,
  5785. tickPixelInterval: 72,
  5786. showLastLabel: true,
  5787. labels: {
  5788. x: -8,
  5789. y: 3
  5790. },
  5791. lineWidth: 0,
  5792. maxPadding: 0.05,
  5793. minPadding: 0.05,
  5794. startOnTick: true,
  5795. //tickWidth: 0,
  5796. title: {
  5797. rotation: 270,
  5798. text: 'Values'
  5799. },
  5800. stackLabels: {
  5801. enabled: false,
  5802. //align: dynamic,
  5803. //y: dynamic,
  5804. //x: dynamic,
  5805. //verticalAlign: dynamic,
  5806. //textAlign: dynamic,
  5807. //rotation: 0,
  5808. formatter: function () {
  5809. return Highcharts.numberFormat(this.total, -1);
  5810. },
  5811. style: merge(defaultPlotOptions.line.dataLabels.style, { color: '#000000' })
  5812. }
  5813. },
  5814. /**
  5815. * These options extend the defaultOptions for left axes
  5816. */
  5817. defaultLeftAxisOptions: {
  5818. labels: {
  5819. x: -15,
  5820. y: null
  5821. },
  5822. title: {
  5823. rotation: 270
  5824. }
  5825. },
  5826. /**
  5827. * These options extend the defaultOptions for right axes
  5828. */
  5829. defaultRightAxisOptions: {
  5830. labels: {
  5831. x: 15,
  5832. y: null
  5833. },
  5834. title: {
  5835. rotation: 90
  5836. }
  5837. },
  5838. /**
  5839. * These options extend the defaultOptions for bottom axes
  5840. */
  5841. defaultBottomAxisOptions: {
  5842. labels: {
  5843. autoRotation: [-45],
  5844. x: 0,
  5845. y: null // based on font size
  5846. // overflow: undefined,
  5847. // staggerLines: null
  5848. },
  5849. title: {
  5850. rotation: 0
  5851. }
  5852. },
  5853. /**
  5854. * These options extend the defaultOptions for top axes
  5855. */
  5856. defaultTopAxisOptions: {
  5857. labels: {
  5858. autoRotation: [-45],
  5859. x: 0,
  5860. y: -15
  5861. // overflow: undefined
  5862. // staggerLines: null
  5863. },
  5864. title: {
  5865. rotation: 0
  5866. }
  5867. },
  5868. /**
  5869. * Initialize the axis
  5870. */
  5871. init: function (chart, userOptions) {
  5872. var isXAxis = userOptions.isX,
  5873. axis = this;
  5874. axis.chart = chart;
  5875. // Flag, is the axis horizontal
  5876. axis.horiz = chart.inverted ? !isXAxis : isXAxis;
  5877. // Flag, isXAxis
  5878. axis.isXAxis = isXAxis;
  5879. axis.coll = isXAxis ? 'xAxis' : 'yAxis';
  5880. axis.opposite = userOptions.opposite; // needed in setOptions
  5881. axis.side = userOptions.side || (axis.horiz ?
  5882. (axis.opposite ? 0 : 2) : // top : bottom
  5883. (axis.opposite ? 1 : 3)); // right : left
  5884. axis.setOptions(userOptions);
  5885. var options = this.options,
  5886. type = options.type,
  5887. isDatetimeAxis = type === 'datetime';
  5888. axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format
  5889. // Flag, stagger lines or not
  5890. axis.userOptions = userOptions;
  5891. //axis.axisTitleMargin = UNDEFINED,// = options.title.margin,
  5892. axis.minPixelPadding = 0;
  5893. axis.reversed = options.reversed;
  5894. axis.visible = options.visible !== false;
  5895. axis.zoomEnabled = options.zoomEnabled !== false;
  5896. // Initial categories
  5897. axis.categories = options.categories || type === 'category';
  5898. axis.names = axis.names || []; // Preserve on update (#3830)
  5899. // Elements
  5900. //axis.axisGroup = UNDEFINED;
  5901. //axis.gridGroup = UNDEFINED;
  5902. //axis.axisTitle = UNDEFINED;
  5903. //axis.axisLine = UNDEFINED;
  5904. // Shorthand types
  5905. axis.isLog = type === 'logarithmic';
  5906. axis.isDatetimeAxis = isDatetimeAxis;
  5907. // Flag, if axis is linked to another axis
  5908. axis.isLinked = defined(options.linkedTo);
  5909. // Linked axis.
  5910. //axis.linkedParent = UNDEFINED;
  5911. // Tick positions
  5912. //axis.tickPositions = UNDEFINED; // array containing predefined positions
  5913. // Tick intervals
  5914. //axis.tickInterval = UNDEFINED;
  5915. //axis.minorTickInterval = UNDEFINED;
  5916. // Major ticks
  5917. axis.ticks = {};
  5918. axis.labelEdge = [];
  5919. // Minor ticks
  5920. axis.minorTicks = {};
  5921. // List of plotLines/Bands
  5922. axis.plotLinesAndBands = [];
  5923. // Alternate bands
  5924. axis.alternateBands = {};
  5925. // Axis metrics
  5926. //axis.left = UNDEFINED;
  5927. //axis.top = UNDEFINED;
  5928. //axis.width = UNDEFINED;
  5929. //axis.height = UNDEFINED;
  5930. //axis.bottom = UNDEFINED;
  5931. //axis.right = UNDEFINED;
  5932. //axis.transA = UNDEFINED;
  5933. //axis.transB = UNDEFINED;
  5934. //axis.oldTransA = UNDEFINED;
  5935. axis.len = 0;
  5936. //axis.oldMin = UNDEFINED;
  5937. //axis.oldMax = UNDEFINED;
  5938. //axis.oldUserMin = UNDEFINED;
  5939. //axis.oldUserMax = UNDEFINED;
  5940. //axis.oldAxisLength = UNDEFINED;
  5941. axis.minRange = axis.userMinRange = options.minRange || options.maxZoom;
  5942. axis.range = options.range;
  5943. axis.offset = options.offset || 0;
  5944. // Dictionary for stacks
  5945. axis.stacks = {};
  5946. axis.oldStacks = {};
  5947. axis.stacksTouched = 0;
  5948. // Min and max in the data
  5949. //axis.dataMin = UNDEFINED,
  5950. //axis.dataMax = UNDEFINED,
  5951. // The axis range
  5952. axis.max = null;
  5953. axis.min = null;
  5954. // User set min and max
  5955. //axis.userMin = UNDEFINED,
  5956. //axis.userMax = UNDEFINED,
  5957. // Crosshair options
  5958. axis.crosshair = pick(options.crosshair, splat(chart.options.tooltip.crosshairs)[isXAxis ? 0 : 1], false);
  5959. // Run Axis
  5960. var eventType,
  5961. events = axis.options.events;
  5962. // Register
  5963. if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update()
  5964. if (isXAxis && !this.isColorAxis) { // #2713
  5965. chart.axes.splice(chart.xAxis.length, 0, axis);
  5966. } else {
  5967. chart.axes.push(axis);
  5968. }
  5969. chart[axis.coll].push(axis);
  5970. }
  5971. axis.series = axis.series || []; // populated by Series
  5972. // inverted charts have reversed xAxes as default
  5973. if (chart.inverted && isXAxis && axis.reversed === UNDEFINED) {
  5974. axis.reversed = true;
  5975. }
  5976. axis.removePlotBand = axis.removePlotBandOrLine;
  5977. axis.removePlotLine = axis.removePlotBandOrLine;
  5978. // register event listeners
  5979. for (eventType in events) {
  5980. addEvent(axis, eventType, events[eventType]);
  5981. }
  5982. // extend logarithmic axis
  5983. if (axis.isLog) {
  5984. axis.val2lin = log2lin;
  5985. axis.lin2val = lin2log;
  5986. }
  5987. },
  5988. /**
  5989. * Merge and set options
  5990. */
  5991. setOptions: function (userOptions) {
  5992. this.options = merge(
  5993. this.defaultOptions,
  5994. this.isXAxis ? {} : this.defaultYAxisOptions,
  5995. [this.defaultTopAxisOptions, this.defaultRightAxisOptions,
  5996. this.defaultBottomAxisOptions, this.defaultLeftAxisOptions][this.side],
  5997. merge(
  5998. defaultOptions[this.coll], // if set in setOptions (#1053)
  5999. userOptions
  6000. )
  6001. );
  6002. },
  6003. /**
  6004. * The default label formatter. The context is a special config object for the label.
  6005. */
  6006. defaultLabelFormatter: function () {
  6007. var axis = this.axis,
  6008. value = this.value,
  6009. categories = axis.categories,
  6010. dateTimeLabelFormat = this.dateTimeLabelFormat,
  6011. numericSymbols = defaultOptions.lang.numericSymbols,
  6012. i = numericSymbols && numericSymbols.length,
  6013. multi,
  6014. ret,
  6015. formatOption = axis.options.labels.format,
  6016. // make sure the same symbol is added for all labels on a linear axis
  6017. numericSymbolDetector = axis.isLog ? value : axis.tickInterval;
  6018. if (formatOption) {
  6019. ret = format(formatOption, this);
  6020. } else if (categories) {
  6021. ret = value;
  6022. } else if (dateTimeLabelFormat) { // datetime axis
  6023. ret = dateFormat(dateTimeLabelFormat, value);
  6024. } else if (i && numericSymbolDetector >= 1000) {
  6025. // Decide whether we should add a numeric symbol like k (thousands) or M (millions).
  6026. // If we are to enable this in tooltip or other places as well, we can move this
  6027. // logic to the numberFormatter and enable it by a parameter.
  6028. while (i-- && ret === UNDEFINED) {
  6029. multi = Math.pow(1000, i + 1);
  6030. if (numericSymbolDetector >= multi && (value * 10) % multi === 0 && numericSymbols[i] !== null) {
  6031. ret = Highcharts.numberFormat(value / multi, -1) + numericSymbols[i];
  6032. }
  6033. }
  6034. }
  6035. if (ret === UNDEFINED) {
  6036. if (mathAbs(value) >= 10000) { // add thousands separators
  6037. ret = Highcharts.numberFormat(value, -1);
  6038. } else { // small numbers
  6039. ret = Highcharts.numberFormat(value, -1, UNDEFINED, ''); // #2466
  6040. }
  6041. }
  6042. return ret;
  6043. },
  6044. /**
  6045. * Get the minimum and maximum for the series of each axis
  6046. */
  6047. getSeriesExtremes: function () {
  6048. var axis = this,
  6049. chart = axis.chart;
  6050. axis.hasVisibleSeries = false;
  6051. // Reset properties in case we're redrawing (#3353)
  6052. axis.dataMin = axis.dataMax = axis.threshold = null;
  6053. axis.softThreshold = !axis.isXAxis;
  6054. if (axis.buildStacks) {
  6055. axis.buildStacks();
  6056. }
  6057. // loop through this axis' series
  6058. each(axis.series, function (series) {
  6059. if (series.visible || !chart.options.chart.ignoreHiddenSeries) {
  6060. var seriesOptions = series.options,
  6061. xData,
  6062. threshold = seriesOptions.threshold,
  6063. seriesDataMin,
  6064. seriesDataMax;
  6065. axis.hasVisibleSeries = true;
  6066. // Validate threshold in logarithmic axes
  6067. if (axis.isLog && threshold <= 0) {
  6068. threshold = null;
  6069. }
  6070. // Get dataMin and dataMax for X axes
  6071. if (axis.isXAxis) {
  6072. xData = series.xData;
  6073. if (xData.length) {
  6074. axis.dataMin = mathMin(pick(axis.dataMin, xData[0]), arrayMin(xData));
  6075. axis.dataMax = mathMax(pick(axis.dataMax, xData[0]), arrayMax(xData));
  6076. }
  6077. // Get dataMin and dataMax for Y axes, as well as handle stacking and processed data
  6078. } else {
  6079. // Get this particular series extremes
  6080. series.getExtremes();
  6081. seriesDataMax = series.dataMax;
  6082. seriesDataMin = series.dataMin;
  6083. // Get the dataMin and dataMax so far. If percentage is used, the min and max are
  6084. // always 0 and 100. If seriesDataMin and seriesDataMax is null, then series
  6085. // doesn't have active y data, we continue with nulls
  6086. if (defined(seriesDataMin) && defined(seriesDataMax)) {
  6087. axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin);
  6088. axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax);
  6089. }
  6090. // Adjust to threshold
  6091. if (defined(threshold)) {
  6092. axis.threshold = threshold;
  6093. }
  6094. // If any series has a hard threshold, it takes precedence
  6095. if (!seriesOptions.softThreshold || axis.isLog) {
  6096. axis.softThreshold = false;
  6097. }
  6098. }
  6099. }
  6100. });
  6101. },
  6102. /**
  6103. * Translate from axis value to pixel position on the chart, or back
  6104. *
  6105. */
  6106. translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacement) {
  6107. var axis = this.linkedParent || this, // #1417
  6108. sign = 1,
  6109. cvsOffset = 0,
  6110. localA = old ? axis.oldTransA : axis.transA,
  6111. localMin = old ? axis.oldMin : axis.min,
  6112. returnValue,
  6113. minPixelPadding = axis.minPixelPadding,
  6114. doPostTranslate = (axis.doPostTranslate || (axis.isLog && handleLog)) && axis.lin2val;
  6115. if (!localA) {
  6116. localA = axis.transA;
  6117. }
  6118. // In vertical axes, the canvas coordinates start from 0 at the top like in
  6119. // SVG.
  6120. if (cvsCoord) {
  6121. sign *= -1; // canvas coordinates inverts the value
  6122. cvsOffset = axis.len;
  6123. }
  6124. // Handle reversed axis
  6125. if (axis.reversed) {
  6126. sign *= -1;
  6127. cvsOffset -= sign * (axis.sector || axis.len);
  6128. }
  6129. // From pixels to value
  6130. if (backwards) { // reverse translation
  6131. val = val * sign + cvsOffset;
  6132. val -= minPixelPadding;
  6133. returnValue = val / localA + localMin; // from chart pixel to value
  6134. if (doPostTranslate) { // log and ordinal axes
  6135. returnValue = axis.lin2val(returnValue);
  6136. }
  6137. // From value to pixels
  6138. } else {
  6139. if (doPostTranslate) { // log and ordinal axes
  6140. val = axis.val2lin(val);
  6141. }
  6142. if (pointPlacement === 'between') {
  6143. pointPlacement = 0.5;
  6144. }
  6145. returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) +
  6146. (isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0);
  6147. }
  6148. return returnValue;
  6149. },
  6150. /**
  6151. * Utility method to translate an axis value to pixel position.
  6152. * @param {Number} value A value in terms of axis units
  6153. * @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart
  6154. * or just the axis/pane itself.
  6155. */
  6156. toPixels: function (value, paneCoordinates) {
  6157. return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos);
  6158. },
  6159. /*
  6160. * Utility method to translate a pixel position in to an axis value
  6161. * @param {Number} pixel The pixel value coordinate
  6162. * @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the
  6163. * axis/pane itself.
  6164. */
  6165. toValue: function (pixel, paneCoordinates) {
  6166. return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true);
  6167. },
  6168. /**
  6169. * Create the path for a plot line that goes from the given value on
  6170. * this axis, across the plot to the opposite side
  6171. * @param {Number} value
  6172. * @param {Number} lineWidth Used for calculation crisp line
  6173. * @param {Number] old Use old coordinates (for resizing and rescaling)
  6174. */
  6175. getPlotLinePath: function (value, lineWidth, old, force, translatedValue) {
  6176. var axis = this,
  6177. chart = axis.chart,
  6178. axisLeft = axis.left,
  6179. axisTop = axis.top,
  6180. x1,
  6181. y1,
  6182. x2,
  6183. y2,
  6184. cHeight = (old && chart.oldChartHeight) || chart.chartHeight,
  6185. cWidth = (old && chart.oldChartWidth) || chart.chartWidth,
  6186. skip,
  6187. transB = axis.transB,
  6188. /**
  6189. * Check if x is between a and b. If not, either move to a/b or skip,
  6190. * depending on the force parameter.
  6191. */
  6192. between = function (x, a, b) {
  6193. if (x < a || x > b) {
  6194. if (force) {
  6195. x = mathMin(mathMax(a, x), b);
  6196. } else {
  6197. skip = true;
  6198. }
  6199. }
  6200. return x;
  6201. };
  6202. translatedValue = pick(translatedValue, axis.translate(value, null, null, old));
  6203. x1 = x2 = mathRound(translatedValue + transB);
  6204. y1 = y2 = mathRound(cHeight - translatedValue - transB);
  6205. if (isNaN(translatedValue)) { // no min or max
  6206. skip = true;
  6207. } else if (axis.horiz) {
  6208. y1 = axisTop;
  6209. y2 = cHeight - axis.bottom;
  6210. x1 = x2 = between(x1, axisLeft, axisLeft + axis.width);
  6211. } else {
  6212. x1 = axisLeft;
  6213. x2 = cWidth - axis.right;
  6214. y1 = y2 = between(y1, axisTop, axisTop + axis.height);
  6215. }
  6216. return skip && !force ?
  6217. null :
  6218. chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 1);
  6219. },
  6220. /**
  6221. * Set the tick positions of a linear axis to round values like whole tens or every five.
  6222. */
  6223. getLinearTickPositions: function (tickInterval, min, max) {
  6224. var pos,
  6225. lastPos,
  6226. roundedMin = correctFloat(mathFloor(min / tickInterval) * tickInterval),
  6227. roundedMax = correctFloat(mathCeil(max / tickInterval) * tickInterval),
  6228. tickPositions = [];
  6229. // For single points, add a tick regardless of the relative position (#2662)
  6230. if (min === max && isNumber(min)) {
  6231. return [min];
  6232. }
  6233. // Populate the intermediate values
  6234. pos = roundedMin;
  6235. while (pos <= roundedMax) {
  6236. // Place the tick on the rounded value
  6237. tickPositions.push(pos);
  6238. // Always add the raw tickInterval, not the corrected one.
  6239. pos = correctFloat(pos + tickInterval);
  6240. // If the interval is not big enough in the current min - max range to actually increase
  6241. // the loop variable, we need to break out to prevent endless loop. Issue #619
  6242. if (pos === lastPos) {
  6243. break;
  6244. }
  6245. // Record the last value
  6246. lastPos = pos;
  6247. }
  6248. return tickPositions;
  6249. },
  6250. /**
  6251. * Return the minor tick positions. For logarithmic axes, reuse the same logic
  6252. * as for major ticks.
  6253. */
  6254. getMinorTickPositions: function () {
  6255. var axis = this,
  6256. options = axis.options,
  6257. tickPositions = axis.tickPositions,
  6258. minorTickInterval = axis.minorTickInterval,
  6259. minorTickPositions = [],
  6260. pos,
  6261. i,
  6262. pointRangePadding = axis.pointRangePadding || 0,
  6263. min = axis.min - pointRangePadding, // #1498
  6264. max = axis.max + pointRangePadding, // #1498
  6265. range = max - min,
  6266. len;
  6267. // If minor ticks get too dense, they are hard to read, and may cause long running script. So we don't draw them.
  6268. if (range && range / minorTickInterval < axis.len / 3) { // #3875
  6269. if (axis.isLog) {
  6270. len = tickPositions.length;
  6271. for (i = 1; i < len; i++) {
  6272. minorTickPositions = minorTickPositions.concat(
  6273. axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true)
  6274. );
  6275. }
  6276. } else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314
  6277. minorTickPositions = minorTickPositions.concat(
  6278. axis.getTimeTicks(
  6279. axis.normalizeTimeTickInterval(minorTickInterval),
  6280. min,
  6281. max,
  6282. options.startOfWeek
  6283. )
  6284. );
  6285. } else {
  6286. for (pos = min + (tickPositions[0] - min) % minorTickInterval; pos <= max; pos += minorTickInterval) {
  6287. minorTickPositions.push(pos);
  6288. }
  6289. }
  6290. }
  6291. if(minorTickPositions.length !== 0) { // don't change the extremes, when there is no minor ticks
  6292. axis.trimTicks(minorTickPositions, options.startOnTick, options.endOnTick); // #3652 #3743 #1498
  6293. }
  6294. return minorTickPositions;
  6295. },
  6296. /**
  6297. * Adjust the min and max for the minimum range. Keep in mind that the series data is
  6298. * not yet processed, so we don't have information on data cropping and grouping, or
  6299. * updated axis.pointRange or series.pointRange. The data can't be processed until
  6300. * we have finally established min and max.
  6301. */
  6302. adjustForMinRange: function () {
  6303. var axis = this,
  6304. options = axis.options,
  6305. min = axis.min,
  6306. max = axis.max,
  6307. zoomOffset,
  6308. spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange,
  6309. closestDataRange,
  6310. i,
  6311. distance,
  6312. xData,
  6313. loopLength,
  6314. minArgs,
  6315. maxArgs,
  6316. minRange;
  6317. // Set the automatic minimum range based on the closest point distance
  6318. if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) {
  6319. if (defined(options.min) || defined(options.max)) {
  6320. axis.minRange = null; // don't do this again
  6321. } else {
  6322. // Find the closest distance between raw data points, as opposed to
  6323. // closestPointRange that applies to processed points (cropped and grouped)
  6324. each(axis.series, function (series) {
  6325. xData = series.xData;
  6326. loopLength = series.xIncrement ? 1 : xData.length - 1;
  6327. for (i = loopLength; i > 0; i--) {
  6328. distance = xData[i] - xData[i - 1];
  6329. if (closestDataRange === UNDEFINED || distance < closestDataRange) {
  6330. closestDataRange = distance;
  6331. }
  6332. }
  6333. });
  6334. axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin);
  6335. }
  6336. }
  6337. // if minRange is exceeded, adjust
  6338. if (max - min < axis.minRange) {
  6339. minRange = axis.minRange;
  6340. zoomOffset = (minRange - max + min) / 2;
  6341. // if min and max options have been set, don't go beyond it
  6342. minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)];
  6343. if (spaceAvailable) { // if space is available, stay within the data range
  6344. minArgs[2] = axis.dataMin;
  6345. }
  6346. min = arrayMax(minArgs);
  6347. maxArgs = [min + minRange, pick(options.max, min + minRange)];
  6348. if (spaceAvailable) { // if space is availabe, stay within the data range
  6349. maxArgs[2] = axis.dataMax;
  6350. }
  6351. max = arrayMin(maxArgs);
  6352. // now if the max is adjusted, adjust the min back
  6353. if (max - min < minRange) {
  6354. minArgs[0] = max - minRange;
  6355. minArgs[1] = pick(options.min, max - minRange);
  6356. min = arrayMax(minArgs);
  6357. }
  6358. }
  6359. // Record modified extremes
  6360. axis.min = min;
  6361. axis.max = max;
  6362. },
  6363. /**
  6364. * Update translation information
  6365. */
  6366. setAxisTranslation: function (saveOld) {
  6367. var axis = this,
  6368. range = axis.max - axis.min,
  6369. pointRange = axis.axisPointRange || 0,
  6370. closestPointRange,
  6371. minPointOffset = 0,
  6372. pointRangePadding = 0,
  6373. linkedParent = axis.linkedParent,
  6374. ordinalCorrection,
  6375. hasCategories = !!axis.categories,
  6376. transA = axis.transA,
  6377. isXAxis = axis.isXAxis;
  6378. // Adjust translation for padding. Y axis with categories need to go through the same (#1784).
  6379. if (isXAxis || hasCategories || pointRange) {
  6380. if (linkedParent) {
  6381. minPointOffset = linkedParent.minPointOffset;
  6382. pointRangePadding = linkedParent.pointRangePadding;
  6383. } else {
  6384. each(axis.series, function (series) {
  6385. var seriesPointRange = hasCategories ? 1 : (isXAxis ? series.pointRange : (axis.axisPointRange || 0)), // #2806
  6386. pointPlacement = series.options.pointPlacement,
  6387. seriesClosestPointRange = series.closestPointRange;
  6388. pointRange = mathMax(pointRange, seriesPointRange);
  6389. if (!axis.single) {
  6390. // minPointOffset is the value padding to the left of the axis in order to make
  6391. // room for points with a pointRange, typically columns. When the pointPlacement option
  6392. // is 'between' or 'on', this padding does not apply.
  6393. minPointOffset = mathMax(
  6394. minPointOffset,
  6395. isString(pointPlacement) ? 0 : seriesPointRange / 2
  6396. );
  6397. // Determine the total padding needed to the length of the axis to make room for the
  6398. // pointRange. If the series' pointPlacement is 'on', no padding is added.
  6399. pointRangePadding = mathMax(
  6400. pointRangePadding,
  6401. pointPlacement === 'on' ? 0 : seriesPointRange
  6402. );
  6403. }
  6404. // Set the closestPointRange
  6405. if (!series.noSharedTooltip && defined(seriesClosestPointRange)) {
  6406. closestPointRange = defined(closestPointRange) ?
  6407. mathMin(closestPointRange, seriesClosestPointRange) :
  6408. seriesClosestPointRange;
  6409. }
  6410. });
  6411. }
  6412. // Record minPointOffset and pointRangePadding
  6413. ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853
  6414. axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection;
  6415. axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection;
  6416. // pointRange means the width reserved for each point, like in a column chart
  6417. axis.pointRange = mathMin(pointRange, range);
  6418. // closestPointRange means the closest distance between points. In columns
  6419. // it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange
  6420. // is some other value
  6421. if (isXAxis) {
  6422. axis.closestPointRange = closestPointRange;
  6423. }
  6424. }
  6425. // Secondary values
  6426. if (saveOld) {
  6427. axis.oldTransA = transA;
  6428. }
  6429. axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1);
  6430. axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend
  6431. axis.minPixelPadding = transA * minPointOffset;
  6432. },
  6433. minFromRange: function () {
  6434. return this.max - this.range;
  6435. },
  6436. /**
  6437. * Set the tick positions to round values and optionally extend the extremes
  6438. * to the nearest tick
  6439. */
  6440. setTickInterval: function (secondPass) {
  6441. var axis = this,
  6442. chart = axis.chart,
  6443. options = axis.options,
  6444. isLog = axis.isLog,
  6445. isDatetimeAxis = axis.isDatetimeAxis,
  6446. isXAxis = axis.isXAxis,
  6447. isLinked = axis.isLinked,
  6448. maxPadding = options.maxPadding,
  6449. minPadding = options.minPadding,
  6450. length,
  6451. linkedParentExtremes,
  6452. tickIntervalOption = options.tickInterval,
  6453. minTickInterval,
  6454. tickPixelIntervalOption = options.tickPixelInterval,
  6455. categories = axis.categories,
  6456. threshold = axis.threshold,
  6457. softThreshold = axis.softThreshold,
  6458. thresholdMin,
  6459. thresholdMax,
  6460. hardMin,
  6461. hardMax;
  6462. if (!isDatetimeAxis && !categories && !isLinked) {
  6463. this.getTickAmount();
  6464. }
  6465. // Min or max set either by zooming/setExtremes or initial options
  6466. hardMin = pick(axis.userMin, options.min);
  6467. hardMax = pick(axis.userMax, options.max);
  6468. // Linked axis gets the extremes from the parent axis
  6469. if (isLinked) {
  6470. axis.linkedParent = chart[axis.coll][options.linkedTo];
  6471. linkedParentExtremes = axis.linkedParent.getExtremes();
  6472. axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin);
  6473. axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax);
  6474. if (options.type !== axis.linkedParent.options.type) {
  6475. error(11, 1); // Can't link axes of different type
  6476. }
  6477. // Initial min and max from the extreme data values
  6478. } else {
  6479. // Adjust to hard threshold
  6480. if (!softThreshold && defined(threshold)) {
  6481. if (axis.dataMin >= threshold) {
  6482. thresholdMin = threshold;
  6483. minPadding = 0;
  6484. } else if (axis.dataMax <= threshold) {
  6485. thresholdMax = threshold;
  6486. maxPadding = 0;
  6487. }
  6488. }
  6489. axis.min = pick(hardMin, thresholdMin, axis.dataMin);
  6490. axis.max = pick(hardMax, thresholdMax, axis.dataMax);
  6491. }
  6492. if (isLog) {
  6493. if (!secondPass && mathMin(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978
  6494. error(10, 1); // Can't plot negative values on log axis
  6495. }
  6496. // The correctFloat cures #934, float errors on full tens. But it
  6497. // was too aggressive for #4360 because of conversion back to lin,
  6498. // therefore use precision 15.
  6499. axis.min = correctFloat(log2lin(axis.min), 15);
  6500. axis.max = correctFloat(log2lin(axis.max), 15);
  6501. }
  6502. // handle zoomed range
  6503. if (axis.range && defined(axis.max)) {
  6504. axis.userMin = axis.min = hardMin = mathMax(axis.min, axis.minFromRange()); // #618
  6505. axis.userMax = hardMax = axis.max;
  6506. axis.range = null; // don't use it when running setExtremes
  6507. }
  6508. // Hook for adjusting this.min and this.max. Used by bubble series.
  6509. if (axis.beforePadding) {
  6510. axis.beforePadding();
  6511. }
  6512. // adjust min and max for the minimum range
  6513. axis.adjustForMinRange();
  6514. // Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding
  6515. // into account, we do this after computing tick interval (#1337).
  6516. if (!categories && !axis.axisPointRange && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) {
  6517. length = axis.max - axis.min;
  6518. if (length) {
  6519. if (!defined(hardMin) && minPadding) {
  6520. axis.min -= length * minPadding;
  6521. }
  6522. if (!defined(hardMax) && maxPadding) {
  6523. axis.max += length * maxPadding;
  6524. }
  6525. }
  6526. }
  6527. // Stay within floor and ceiling
  6528. if (isNumber(options.floor)) {
  6529. axis.min = mathMax(axis.min, options.floor);
  6530. }
  6531. if (isNumber(options.ceiling)) {
  6532. axis.max = mathMin(axis.max, options.ceiling);
  6533. }
  6534. // When the threshold is soft, adjust the extreme value only if
  6535. // the data extreme and the padded extreme land on either side of the threshold. For example,
  6536. // a series of [0, 1, 2, 3] would make the yAxis add a tick for -1 because of the
  6537. // default minPadding and startOnTick options. This is prevented by the softThreshold
  6538. // option.
  6539. if (softThreshold && defined(axis.dataMin)) {
  6540. threshold = threshold || 0;
  6541. if (!defined(hardMin) && axis.min < threshold && axis.dataMin >= threshold) {
  6542. axis.min = threshold;
  6543. } else if (!defined(hardMax) && axis.max > threshold && axis.dataMax <= threshold) {
  6544. axis.max = threshold;
  6545. }
  6546. }
  6547. // get tickInterval
  6548. if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) {
  6549. axis.tickInterval = 1;
  6550. } else if (isLinked && !tickIntervalOption &&
  6551. tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) {
  6552. axis.tickInterval = tickIntervalOption = axis.linkedParent.tickInterval;
  6553. } else {
  6554. axis.tickInterval = pick(
  6555. tickIntervalOption,
  6556. this.tickAmount ? ((axis.max - axis.min) / mathMax(this.tickAmount - 1, 1)) : undefined,
  6557. categories ? // for categoried axis, 1 is default, for linear axis use tickPix
  6558. 1 :
  6559. // don't let it be more than the data range
  6560. (axis.max - axis.min) * tickPixelIntervalOption / mathMax(axis.len, tickPixelIntervalOption)
  6561. );
  6562. }
  6563. // Now we're finished detecting min and max, crop and group series data. This
  6564. // is in turn needed in order to find tick positions in ordinal axes.
  6565. if (isXAxis && !secondPass) {
  6566. each(axis.series, function (series) {
  6567. series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax);
  6568. });
  6569. }
  6570. // set the translation factor used in translate function
  6571. axis.setAxisTranslation(true);
  6572. // hook for ordinal axes and radial axes
  6573. if (axis.beforeSetTickPositions) {
  6574. axis.beforeSetTickPositions();
  6575. }
  6576. // hook for extensions, used in Highstock ordinal axes
  6577. if (axis.postProcessTickInterval) {
  6578. axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval);
  6579. }
  6580. // In column-like charts, don't cramp in more ticks than there are points (#1943)
  6581. if (axis.pointRange) {
  6582. axis.tickInterval = mathMax(axis.pointRange, axis.tickInterval);
  6583. }
  6584. // Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined.
  6585. minTickInterval = pick(options.minTickInterval, axis.isDatetimeAxis && axis.closestPointRange);
  6586. if (!tickIntervalOption && axis.tickInterval < minTickInterval) {
  6587. axis.tickInterval = minTickInterval;
  6588. }
  6589. // for linear axes, get magnitude and normalize the interval
  6590. if (!isDatetimeAxis && !isLog && !tickIntervalOption) {
  6591. axis.tickInterval = normalizeTickInterval(
  6592. axis.tickInterval,
  6593. null,
  6594. getMagnitude(axis.tickInterval),
  6595. // If the tick interval is between 0.5 and 5 and the axis max is in the order of
  6596. // thousands, chances are we are dealing with years. Don't allow decimals. #3363.
  6597. pick(options.allowDecimals, !(axis.tickInterval > 0.5 && axis.tickInterval < 5 && axis.max > 1000 && axis.max < 9999)),
  6598. !!this.tickAmount
  6599. );
  6600. }
  6601. // Prevent ticks from getting so close that we can't draw the labels
  6602. if (!this.tickAmount && this.len) { // Color axis with disabled legend has no length
  6603. axis.tickInterval = axis.unsquish();
  6604. }
  6605. this.setTickPositions();
  6606. },
  6607. /**
  6608. * Now we have computed the normalized tickInterval, get the tick positions
  6609. */
  6610. setTickPositions: function () {
  6611. var options = this.options,
  6612. tickPositions,
  6613. tickPositionsOption = options.tickPositions,
  6614. tickPositioner = options.tickPositioner,
  6615. startOnTick = options.startOnTick,
  6616. endOnTick = options.endOnTick,
  6617. single;
  6618. // Set the tickmarkOffset
  6619. this.tickmarkOffset = (this.categories && options.tickmarkPlacement === 'between' &&
  6620. this.tickInterval === 1) ? 0.5 : 0; // #3202
  6621. // get minorTickInterval
  6622. this.minorTickInterval = options.minorTickInterval === 'auto' && this.tickInterval ?
  6623. this.tickInterval / 5 : options.minorTickInterval;
  6624. // Find the tick positions
  6625. this.tickPositions = tickPositions = tickPositionsOption && tickPositionsOption.slice(); // Work on a copy (#1565)
  6626. if (!tickPositions) {
  6627. if (this.isDatetimeAxis) {
  6628. tickPositions = this.getTimeTicks(
  6629. this.normalizeTimeTickInterval(this.tickInterval, options.units),
  6630. this.min,
  6631. this.max,
  6632. options.startOfWeek,
  6633. this.ordinalPositions,
  6634. this.closestPointRange,
  6635. true
  6636. );
  6637. } else if (this.isLog) {
  6638. tickPositions = this.getLogTickPositions(this.tickInterval, this.min, this.max);
  6639. } else {
  6640. tickPositions = this.getLinearTickPositions(this.tickInterval, this.min, this.max);
  6641. }
  6642. // Too dense ticks, keep only the first and last (#4477)
  6643. if (tickPositions.length > this.len) {
  6644. tickPositions = [tickPositions[0], tickPositions.pop()];
  6645. }
  6646. this.tickPositions = tickPositions;
  6647. // Run the tick positioner callback, that allows modifying auto tick positions.
  6648. if (tickPositioner) {
  6649. tickPositioner = tickPositioner.apply(this, [this.min, this.max]);
  6650. if (tickPositioner) {
  6651. this.tickPositions = tickPositions = tickPositioner;
  6652. }
  6653. }
  6654. }
  6655. if (!this.isLinked) {
  6656. // reset min/max or remove extremes based on start/end on tick
  6657. this.trimTicks(tickPositions, startOnTick, endOnTick);
  6658. // When there is only one point, or all points have the same value on this axis, then min
  6659. // and max are equal and tickPositions.length is 0 or 1. In this case, add some padding
  6660. // in order to center the point, but leave it with one tick. #1337.
  6661. if (this.min === this.max && defined(this.min) && !this.tickAmount) {
  6662. // Substract half a unit (#2619, #2846, #2515, #3390)
  6663. single = true;
  6664. this.min -= 0.5;
  6665. this.max += 0.5;
  6666. }
  6667. this.single = single;
  6668. if (!tickPositionsOption && !tickPositioner) {
  6669. this.adjustTickAmount();
  6670. }
  6671. }
  6672. },
  6673. /**
  6674. * Handle startOnTick and endOnTick by either adapting to padding min/max or rounded min/max
  6675. */
  6676. trimTicks: function (tickPositions, startOnTick, endOnTick) {
  6677. var roundedMin = tickPositions[0],
  6678. roundedMax = tickPositions[tickPositions.length - 1],
  6679. minPointOffset = this.minPointOffset || 0;
  6680. if (startOnTick) {
  6681. this.min = roundedMin;
  6682. } else if (this.min - minPointOffset > roundedMin) {
  6683. tickPositions.shift();
  6684. }
  6685. if (endOnTick) {
  6686. this.max = roundedMax;
  6687. } else if (this.max + minPointOffset < roundedMax) {
  6688. tickPositions.pop();
  6689. }
  6690. // If no tick are left, set one tick in the middle (#3195)
  6691. if (tickPositions.length === 0 && defined(roundedMin)) {
  6692. tickPositions.push((roundedMax + roundedMin) / 2);
  6693. }
  6694. },
  6695. /**
  6696. * Set the max ticks of either the x and y axis collection
  6697. */
  6698. getTickAmount: function () {
  6699. var others = {}, // Whether there is another axis to pair with this one
  6700. hasOther,
  6701. options = this.options,
  6702. tickAmount = options.tickAmount,
  6703. tickPixelInterval = options.tickPixelInterval;
  6704. if (!defined(options.tickInterval) && this.len < tickPixelInterval && !this.isRadial &&
  6705. !this.isLog && options.startOnTick && options.endOnTick) {
  6706. tickAmount = 2;
  6707. }
  6708. if (!tickAmount && this.chart.options.chart.alignTicks !== false && options.alignTicks !== false) {
  6709. // Check if there are multiple axes in the same pane
  6710. each(this.chart[this.coll], function (axis) {
  6711. var options = axis.options,
  6712. horiz = axis.horiz,
  6713. key = [horiz ? options.left : options.top, horiz ? options.width : options.height, options.pane].join(',');
  6714. if (axis.series.length) { // #4442
  6715. if (others[key]) {
  6716. hasOther = true; // #4201
  6717. } else {
  6718. others[key] = 1;
  6719. }
  6720. }
  6721. });
  6722. if (hasOther) {
  6723. // Add 1 because 4 tick intervals require 5 ticks (including first and last)
  6724. tickAmount = mathCeil(this.len / tickPixelInterval) + 1;
  6725. }
  6726. }
  6727. // For tick amounts of 2 and 3, compute five ticks and remove the intermediate ones. This
  6728. // prevents the axis from adding ticks that are too far away from the data extremes.
  6729. if (tickAmount < 4) {
  6730. this.finalTickAmt = tickAmount;
  6731. tickAmount = 5;
  6732. }
  6733. this.tickAmount = tickAmount;
  6734. },
  6735. /**
  6736. * When using multiple axes, adjust the number of ticks to match the highest
  6737. * number of ticks in that group
  6738. */
  6739. adjustTickAmount: function () {
  6740. var tickInterval = this.tickInterval,
  6741. tickPositions = this.tickPositions,
  6742. tickAmount = this.tickAmount,
  6743. finalTickAmt = this.finalTickAmt,
  6744. currentTickAmount = tickPositions && tickPositions.length,
  6745. i,
  6746. len;
  6747. if (currentTickAmount < tickAmount) { // TODO: Check #3411
  6748. while (tickPositions.length < tickAmount) {
  6749. tickPositions.push(correctFloat(
  6750. tickPositions[tickPositions.length - 1] + tickInterval
  6751. ));
  6752. }
  6753. this.transA *= (currentTickAmount - 1) / (tickAmount - 1);
  6754. this.max = tickPositions[tickPositions.length - 1];
  6755. // We have too many ticks, run second pass to try to reduce ticks
  6756. } else if (currentTickAmount > tickAmount) {
  6757. this.tickInterval *= 2;
  6758. this.setTickPositions();
  6759. }
  6760. // The finalTickAmt property is set in getTickAmount
  6761. if (defined(finalTickAmt)) {
  6762. i = len = tickPositions.length;
  6763. while (i--) {
  6764. if (
  6765. (finalTickAmt === 3 && i % 2 === 1) || // Remove every other tick
  6766. (finalTickAmt <= 2 && i > 0 && i < len - 1) // Remove all but first and last
  6767. ) {
  6768. tickPositions.splice(i, 1);
  6769. }
  6770. }
  6771. this.finalTickAmt = UNDEFINED;
  6772. }
  6773. },
  6774. /**
  6775. * Set the scale based on data min and max, user set min and max or options
  6776. *
  6777. */
  6778. setScale: function () {
  6779. var axis = this,
  6780. isDirtyData,
  6781. isDirtyAxisLength;
  6782. axis.oldMin = axis.min;
  6783. axis.oldMax = axis.max;
  6784. axis.oldAxisLength = axis.len;
  6785. // set the new axisLength
  6786. axis.setAxisSize();
  6787. //axisLength = horiz ? axisWidth : axisHeight;
  6788. isDirtyAxisLength = axis.len !== axis.oldAxisLength;
  6789. // is there new data?
  6790. each(axis.series, function (series) {
  6791. if (series.isDirtyData || series.isDirty ||
  6792. series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well
  6793. isDirtyData = true;
  6794. }
  6795. });
  6796. // do we really need to go through all this?
  6797. if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw ||
  6798. axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax) {
  6799. if (axis.resetStacks) {
  6800. axis.resetStacks();
  6801. }
  6802. axis.forceRedraw = false;
  6803. // get data extremes if needed
  6804. axis.getSeriesExtremes();
  6805. // get fixed positions based on tickInterval
  6806. axis.setTickInterval();
  6807. // record old values to decide whether a rescale is necessary later on (#540)
  6808. axis.oldUserMin = axis.userMin;
  6809. axis.oldUserMax = axis.userMax;
  6810. // Mark as dirty if it is not already set to dirty and extremes have changed. #595.
  6811. if (!axis.isDirty) {
  6812. axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax;
  6813. }
  6814. } else if (axis.cleanStacks) {
  6815. axis.cleanStacks();
  6816. }
  6817. },
  6818. /**
  6819. * Set the extremes and optionally redraw
  6820. * @param {Number} newMin
  6821. * @param {Number} newMax
  6822. * @param {Boolean} redraw
  6823. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  6824. * configuration
  6825. * @param {Object} eventArguments
  6826. *
  6827. */
  6828. setExtremes: function (newMin, newMax, redraw, animation, eventArguments) {
  6829. var axis = this,
  6830. chart = axis.chart;
  6831. redraw = pick(redraw, true); // defaults to true
  6832. each(axis.series, function (serie) {
  6833. delete serie.kdTree;
  6834. });
  6835. // Extend the arguments with min and max
  6836. eventArguments = extend(eventArguments, {
  6837. min: newMin,
  6838. max: newMax
  6839. });
  6840. // Fire the event
  6841. fireEvent(axis, 'setExtremes', eventArguments, function () { // the default event handler
  6842. axis.userMin = newMin;
  6843. axis.userMax = newMax;
  6844. axis.eventArgs = eventArguments;
  6845. if (redraw) {
  6846. chart.redraw(animation);
  6847. }
  6848. });
  6849. },
  6850. /**
  6851. * Overridable method for zooming chart. Pulled out in a separate method to allow overriding
  6852. * in stock charts.
  6853. */
  6854. zoom: function (newMin, newMax) {
  6855. var dataMin = this.dataMin,
  6856. dataMax = this.dataMax,
  6857. options = this.options,
  6858. min = mathMin(dataMin, pick(options.min, dataMin)),
  6859. max = mathMax(dataMax, pick(options.max, dataMax));
  6860. // Prevent pinch zooming out of range. Check for defined is for #1946. #1734.
  6861. if (!this.allowZoomOutside) {
  6862. if (defined(dataMin) && newMin <= min) {
  6863. newMin = min;
  6864. }
  6865. if (defined(dataMax) && newMax >= max) {
  6866. newMax = max;
  6867. }
  6868. }
  6869. // In full view, displaying the reset zoom button is not required
  6870. this.displayBtn = newMin !== UNDEFINED || newMax !== UNDEFINED;
  6871. // Do it
  6872. this.setExtremes(
  6873. newMin,
  6874. newMax,
  6875. false,
  6876. UNDEFINED,
  6877. { trigger: 'zoom' }
  6878. );
  6879. return true;
  6880. },
  6881. /**
  6882. * Update the axis metrics
  6883. */
  6884. setAxisSize: function () {
  6885. var chart = this.chart,
  6886. options = this.options,
  6887. offsetLeft = options.offsetLeft || 0,
  6888. offsetRight = options.offsetRight || 0,
  6889. horiz = this.horiz,
  6890. width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight),
  6891. height = pick(options.height, chart.plotHeight),
  6892. top = pick(options.top, chart.plotTop),
  6893. left = pick(options.left, chart.plotLeft + offsetLeft),
  6894. percentRegex = /%$/;
  6895. // Check for percentage based input values
  6896. if (percentRegex.test(height)) {
  6897. height = parseFloat(height) / 100 * chart.plotHeight;
  6898. }
  6899. if (percentRegex.test(top)) {
  6900. top = parseFloat(top) / 100 * chart.plotHeight + chart.plotTop;
  6901. }
  6902. // Expose basic values to use in Series object and navigator
  6903. this.left = left;
  6904. this.top = top;
  6905. this.width = width;
  6906. this.height = height;
  6907. this.bottom = chart.chartHeight - height - top;
  6908. this.right = chart.chartWidth - width - left;
  6909. // Direction agnostic properties
  6910. this.len = mathMax(horiz ? width : height, 0); // mathMax fixes #905
  6911. this.pos = horiz ? left : top; // distance from SVG origin
  6912. },
  6913. /**
  6914. * Get the actual axis extremes
  6915. */
  6916. getExtremes: function () {
  6917. var axis = this,
  6918. isLog = axis.isLog;
  6919. return {
  6920. min: isLog ? correctFloat(lin2log(axis.min)) : axis.min,
  6921. max: isLog ? correctFloat(lin2log(axis.max)) : axis.max,
  6922. dataMin: axis.dataMin,
  6923. dataMax: axis.dataMax,
  6924. userMin: axis.userMin,
  6925. userMax: axis.userMax
  6926. };
  6927. },
  6928. /**
  6929. * Get the zero plane either based on zero or on the min or max value.
  6930. * Used in bar and area plots
  6931. */
  6932. getThreshold: function (threshold) {
  6933. var axis = this,
  6934. isLog = axis.isLog,
  6935. realMin = isLog ? lin2log(axis.min) : axis.min,
  6936. realMax = isLog ? lin2log(axis.max) : axis.max;
  6937. // With a threshold of null, make the columns/areas rise from the top or bottom
  6938. // depending on the value, assuming an actual threshold of 0 (#4233).
  6939. if (threshold === null) {
  6940. threshold = realMax < 0 ? realMax : realMin;
  6941. } else if (realMin > threshold) {
  6942. threshold = realMin;
  6943. } else if (realMax < threshold) {
  6944. threshold = realMax;
  6945. }
  6946. return axis.translate(threshold, 0, 1, 0, 1);
  6947. },
  6948. /**
  6949. * Compute auto alignment for the axis label based on which side the axis is on
  6950. * and the given rotation for the label
  6951. */
  6952. autoLabelAlign: function (rotation) {
  6953. var ret,
  6954. angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360;
  6955. if (angle > 15 && angle < 165) {
  6956. ret = 'right';
  6957. } else if (angle > 195 && angle < 345) {
  6958. ret = 'left';
  6959. } else {
  6960. ret = 'center';
  6961. }
  6962. return ret;
  6963. },
  6964. /**
  6965. * Prevent the ticks from getting so close we can't draw the labels. On a horizontal
  6966. * axis, this is handled by rotating the labels, removing ticks and adding ellipsis.
  6967. * On a vertical axis remove ticks and add ellipsis.
  6968. */
  6969. unsquish: function () {
  6970. var chart = this.chart,
  6971. ticks = this.ticks,
  6972. labelOptions = this.options.labels,
  6973. horiz = this.horiz,
  6974. tickInterval = this.tickInterval,
  6975. newTickInterval = tickInterval,
  6976. slotSize = this.len / (((this.categories ? 1 : 0) + this.max - this.min) / tickInterval),
  6977. rotation,
  6978. rotationOption = labelOptions.rotation,
  6979. labelMetrics = chart.renderer.fontMetrics(labelOptions.style.fontSize, ticks[0] && ticks[0].label),
  6980. step,
  6981. bestScore = Number.MAX_VALUE,
  6982. autoRotation,
  6983. // Return the multiple of tickInterval that is needed to avoid collision
  6984. getStep = function (spaceNeeded) {
  6985. var step = spaceNeeded / (slotSize || 1);
  6986. step = step > 1 ? mathCeil(step) : 1;
  6987. return step * tickInterval;
  6988. };
  6989. if (horiz) {
  6990. autoRotation = !labelOptions.staggerLines && !labelOptions.step && ( // #3971
  6991. defined(rotationOption) ?
  6992. [rotationOption] :
  6993. slotSize < pick(labelOptions.autoRotationLimit, 80) && labelOptions.autoRotation
  6994. );
  6995. if (autoRotation) {
  6996. // Loop over the given autoRotation options, and determine which gives the best score. The
  6997. // best score is that with the lowest number of steps and a rotation closest to horizontal.
  6998. each(autoRotation, function (rot) {
  6999. var score;
  7000. if (rot === rotationOption || (rot && rot >= -90 && rot <= 90)) { // #3891
  7001. step = getStep(mathAbs(labelMetrics.h / mathSin(deg2rad * rot)));
  7002. score = step + mathAbs(rot / 360);
  7003. if (score < bestScore) {
  7004. bestScore = score;
  7005. rotation = rot;
  7006. newTickInterval = step;
  7007. }
  7008. }
  7009. });
  7010. }
  7011. } else if (!labelOptions.step) { // #4411
  7012. newTickInterval = getStep(labelMetrics.h);
  7013. }
  7014. this.autoRotation = autoRotation;
  7015. this.labelRotation = pick(rotation, rotationOption);
  7016. return newTickInterval;
  7017. },
  7018. renderUnsquish: function () {
  7019. var chart = this.chart,
  7020. renderer = chart.renderer,
  7021. tickPositions = this.tickPositions,
  7022. ticks = this.ticks,
  7023. labelOptions = this.options.labels,
  7024. horiz = this.horiz,
  7025. margin = chart.margin,
  7026. slotCount = this.categories ? tickPositions.length : tickPositions.length - 1,
  7027. slotWidth = this.slotWidth = (horiz && !labelOptions.step && !labelOptions.rotation &&
  7028. ((this.staggerLines || 1) * chart.plotWidth) / slotCount) ||
  7029. (!horiz && ((margin[3] && (margin[3] - chart.spacing[3])) || chart.chartWidth * 0.33)), // #1580, #1931,
  7030. innerWidth = mathMax(1, mathRound(slotWidth - 2 * (labelOptions.padding || 5))),
  7031. attr = {},
  7032. labelMetrics = renderer.fontMetrics(labelOptions.style.fontSize, ticks[0] && ticks[0].label),
  7033. textOverflowOption = labelOptions.style.textOverflow,
  7034. css,
  7035. labelLength = 0,
  7036. label,
  7037. i,
  7038. pos;
  7039. // Set rotation option unless it is "auto", like in gauges
  7040. if (!isString(labelOptions.rotation)) {
  7041. attr.rotation = labelOptions.rotation || 0; // #4443
  7042. }
  7043. // Handle auto rotation on horizontal axis
  7044. if (this.autoRotation) {
  7045. // Get the longest label length
  7046. each(tickPositions, function (tick) {
  7047. tick = ticks[tick];
  7048. if (tick && tick.labelLength > labelLength) {
  7049. labelLength = tick.labelLength;
  7050. }
  7051. });
  7052. // Apply rotation only if the label is too wide for the slot, and
  7053. // the label is wider than its height.
  7054. if (labelLength > innerWidth && labelLength > labelMetrics.h) {
  7055. attr.rotation = this.labelRotation;
  7056. } else {
  7057. this.labelRotation = 0;
  7058. }
  7059. // Handle word-wrap or ellipsis on vertical axis
  7060. } else if (slotWidth) {
  7061. // For word-wrap or ellipsis
  7062. css = { width: innerWidth + PX };
  7063. if (!textOverflowOption) {
  7064. css.textOverflow = 'clip';
  7065. // On vertical axis, only allow word wrap if there is room for more lines.
  7066. i = tickPositions.length;
  7067. while (!horiz && i--) {
  7068. pos = tickPositions[i];
  7069. label = ticks[pos].label;
  7070. if (label) {
  7071. // Reset ellipsis in order to get the correct bounding box (#4070)
  7072. if (label.styles.textOverflow === 'ellipsis') {
  7073. label.css({ textOverflow: 'clip' });
  7074. }
  7075. if (label.getBBox().height > this.len / tickPositions.length - (labelMetrics.h - labelMetrics.f)) {
  7076. label.specCss = { textOverflow: 'ellipsis' };
  7077. }
  7078. }
  7079. }
  7080. }
  7081. }
  7082. // Add ellipsis if the label length is significantly longer than ideal
  7083. if (attr.rotation) {
  7084. css = {
  7085. width: (labelLength > chart.chartHeight * 0.5 ? chart.chartHeight * 0.33 : chart.chartHeight) + PX
  7086. };
  7087. if (!textOverflowOption) {
  7088. css.textOverflow = 'ellipsis';
  7089. }
  7090. }
  7091. // Set the explicit or automatic label alignment
  7092. this.labelAlign = attr.align = labelOptions.align || this.autoLabelAlign(this.labelRotation);
  7093. // Apply general and specific CSS
  7094. each(tickPositions, function (pos) {
  7095. var tick = ticks[pos],
  7096. label = tick && tick.label;
  7097. if (label) {
  7098. label.attr(attr); // This needs to go before the CSS in old IE (#4502)
  7099. if (css) {
  7100. label.css(merge(css, label.specCss));
  7101. }
  7102. delete label.specCss;
  7103. tick.rotation = attr.rotation;
  7104. }
  7105. });
  7106. // TODO: Why not part of getLabelPosition?
  7107. this.tickRotCorr = renderer.rotCorr(labelMetrics.b, this.labelRotation || 0, this.side === 2);
  7108. },
  7109. /**
  7110. * Return true if the axis has associated data
  7111. */
  7112. hasData: function () {
  7113. return this.hasVisibleSeries || (defined(this.min) && defined(this.max) && !!this.tickPositions);
  7114. },
  7115. /**
  7116. * Render the tick labels to a preliminary position to get their sizes
  7117. */
  7118. getOffset: function () {
  7119. var axis = this,
  7120. chart = axis.chart,
  7121. renderer = chart.renderer,
  7122. options = axis.options,
  7123. tickPositions = axis.tickPositions,
  7124. ticks = axis.ticks,
  7125. horiz = axis.horiz,
  7126. side = axis.side,
  7127. invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side,
  7128. hasData,
  7129. showAxis,
  7130. titleOffset = 0,
  7131. titleOffsetOption,
  7132. titleMargin = 0,
  7133. axisTitleOptions = options.title,
  7134. labelOptions = options.labels,
  7135. labelOffset = 0, // reset
  7136. labelOffsetPadded,
  7137. axisOffset = chart.axisOffset,
  7138. clipOffset = chart.clipOffset,
  7139. clip,
  7140. directionFactor = [-1, 1, 1, -1][side],
  7141. n,
  7142. axisParent = axis.axisParent, // Used in color axis
  7143. lineHeightCorrection;
  7144. // For reuse in Axis.render
  7145. hasData = axis.hasData();
  7146. axis.showAxis = showAxis = hasData || pick(options.showEmpty, true);
  7147. // Set/reset staggerLines
  7148. axis.staggerLines = axis.horiz && labelOptions.staggerLines;
  7149. // Create the axisGroup and gridGroup elements on first iteration
  7150. if (!axis.axisGroup) {
  7151. axis.gridGroup = renderer.g('grid')
  7152. .attr({ zIndex: options.gridZIndex || 1 })
  7153. .add(axisParent);
  7154. axis.axisGroup = renderer.g('axis')
  7155. .attr({ zIndex: options.zIndex || 2 })
  7156. .add(axisParent);
  7157. axis.labelGroup = renderer.g('axis-labels')
  7158. .attr({ zIndex: labelOptions.zIndex || 7 })
  7159. .addClass(PREFIX + axis.coll.toLowerCase() + '-labels')
  7160. .add(axisParent);
  7161. }
  7162. if (hasData || axis.isLinked) {
  7163. // Generate ticks
  7164. each(tickPositions, function (pos) {
  7165. if (!ticks[pos]) {
  7166. ticks[pos] = new Tick(axis, pos);
  7167. } else {
  7168. ticks[pos].addLabel(); // update labels depending on tick interval
  7169. }
  7170. });
  7171. axis.renderUnsquish();
  7172. each(tickPositions, function (pos) {
  7173. // left side must be align: right and right side must have align: left for labels
  7174. if (side === 0 || side === 2 || { 1: 'left', 3: 'right' }[side] === axis.labelAlign) {
  7175. // get the highest offset
  7176. labelOffset = mathMax(
  7177. ticks[pos].getLabelSize(),
  7178. labelOffset
  7179. );
  7180. }
  7181. });
  7182. if (axis.staggerLines) {
  7183. labelOffset *= axis.staggerLines;
  7184. axis.labelOffset = labelOffset;
  7185. }
  7186. } else { // doesn't have data
  7187. for (n in ticks) {
  7188. ticks[n].destroy();
  7189. delete ticks[n];
  7190. }
  7191. }
  7192. if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) {
  7193. if (!axis.axisTitle) {
  7194. axis.axisTitle = renderer.text(
  7195. axisTitleOptions.text,
  7196. 0,
  7197. 0,
  7198. axisTitleOptions.useHTML
  7199. )
  7200. .attr({
  7201. zIndex: 7,
  7202. rotation: axisTitleOptions.rotation || 0,
  7203. align:
  7204. axisTitleOptions.textAlign ||
  7205. { low: 'left', middle: 'center', high: 'right' }[axisTitleOptions.align]
  7206. })
  7207. .addClass(PREFIX + this.coll.toLowerCase() + '-title')
  7208. .css(axisTitleOptions.style)
  7209. .add(axis.axisGroup);
  7210. axis.axisTitle.isNew = true;
  7211. }
  7212. if (showAxis) {
  7213. titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width'];
  7214. titleOffsetOption = axisTitleOptions.offset;
  7215. titleMargin = defined(titleOffsetOption) ? 0 : pick(axisTitleOptions.margin, horiz ? 5 : 10);
  7216. }
  7217. // hide or show the title depending on whether showEmpty is set
  7218. axis.axisTitle[showAxis ? 'show' : 'hide']();
  7219. }
  7220. // handle automatic or user set offset
  7221. axis.offset = directionFactor * pick(options.offset, axisOffset[side]);
  7222. axis.tickRotCorr = axis.tickRotCorr || { x: 0, y: 0 }; // polar
  7223. lineHeightCorrection = side === 2 ? axis.tickRotCorr.y : 0;
  7224. labelOffsetPadded = labelOffset + titleMargin +
  7225. (labelOffset && (directionFactor * (horiz ? pick(labelOptions.y, axis.tickRotCorr.y + 8) : labelOptions.x) - lineHeightCorrection));
  7226. axis.axisTitleMargin = pick(titleOffsetOption, labelOffsetPadded);
  7227. axisOffset[side] = mathMax(
  7228. axisOffset[side],
  7229. axis.axisTitleMargin + titleOffset + directionFactor * axis.offset,
  7230. labelOffsetPadded // #3027
  7231. );
  7232. // Decide the clipping needed to keep the graph inside the plot area and axis lines
  7233. clip = options.offset ? 0 : mathFloor(options.lineWidth / 2) * 2; // #4308, #4371
  7234. clipOffset[invertedSide] = mathMax(clipOffset[invertedSide], clip);
  7235. },
  7236. /**
  7237. * Get the path for the axis line
  7238. */
  7239. getLinePath: function (lineWidth) {
  7240. var chart = this.chart,
  7241. opposite = this.opposite,
  7242. offset = this.offset,
  7243. horiz = this.horiz,
  7244. lineLeft = this.left + (opposite ? this.width : 0) + offset,
  7245. lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset;
  7246. if (opposite) {
  7247. lineWidth *= -1; // crispify the other way - #1480, #1687
  7248. }
  7249. return chart.renderer.crispLine([
  7250. M,
  7251. horiz ?
  7252. this.left :
  7253. lineLeft,
  7254. horiz ?
  7255. lineTop :
  7256. this.top,
  7257. L,
  7258. horiz ?
  7259. chart.chartWidth - this.right :
  7260. lineLeft,
  7261. horiz ?
  7262. lineTop :
  7263. chart.chartHeight - this.bottom
  7264. ], lineWidth);
  7265. },
  7266. /**
  7267. * Position the title
  7268. */
  7269. getTitlePosition: function () {
  7270. // compute anchor points for each of the title align options
  7271. var horiz = this.horiz,
  7272. axisLeft = this.left,
  7273. axisTop = this.top,
  7274. axisLength = this.len,
  7275. axisTitleOptions = this.options.title,
  7276. margin = horiz ? axisLeft : axisTop,
  7277. opposite = this.opposite,
  7278. offset = this.offset,
  7279. xOption = axisTitleOptions.x || 0,
  7280. yOption = axisTitleOptions.y || 0,
  7281. fontSize = pInt(axisTitleOptions.style.fontSize || 12),
  7282. // the position in the length direction of the axis
  7283. alongAxis = {
  7284. low: margin + (horiz ? 0 : axisLength),
  7285. middle: margin + axisLength / 2,
  7286. high: margin + (horiz ? axisLength : 0)
  7287. }[axisTitleOptions.align],
  7288. // the position in the perpendicular direction of the axis
  7289. offAxis = (horiz ? axisTop + this.height : axisLeft) +
  7290. (horiz ? 1 : -1) * // horizontal axis reverses the margin
  7291. (opposite ? -1 : 1) * // so does opposite axes
  7292. this.axisTitleMargin +
  7293. (this.side === 2 ? fontSize : 0);
  7294. return {
  7295. x: horiz ?
  7296. alongAxis + xOption :
  7297. offAxis + (opposite ? this.width : 0) + offset + xOption,
  7298. y: horiz ?
  7299. offAxis + yOption - (opposite ? this.height : 0) + offset :
  7300. alongAxis + yOption
  7301. };
  7302. },
  7303. /**
  7304. * Render the axis
  7305. */
  7306. render: function () {
  7307. var axis = this,
  7308. chart = axis.chart,
  7309. renderer = chart.renderer,
  7310. options = axis.options,
  7311. isLog = axis.isLog,
  7312. isLinked = axis.isLinked,
  7313. tickPositions = axis.tickPositions,
  7314. axisTitle = axis.axisTitle,
  7315. ticks = axis.ticks,
  7316. minorTicks = axis.minorTicks,
  7317. alternateBands = axis.alternateBands,
  7318. stackLabelOptions = options.stackLabels,
  7319. alternateGridColor = options.alternateGridColor,
  7320. tickmarkOffset = axis.tickmarkOffset,
  7321. lineWidth = options.lineWidth,
  7322. linePath,
  7323. hasRendered = chart.hasRendered,
  7324. slideInTicks = hasRendered && defined(axis.oldMin) && !isNaN(axis.oldMin),
  7325. showAxis = axis.showAxis,
  7326. globalAnimation = renderer.globalAnimation,
  7327. from,
  7328. to;
  7329. // Reset
  7330. axis.labelEdge.length = 0;
  7331. //axis.justifyToPlot = overflow === 'justify';
  7332. axis.overlap = false;
  7333. // Mark all elements inActive before we go over and mark the active ones
  7334. each([ticks, minorTicks, alternateBands], function (coll) {
  7335. var pos;
  7336. for (pos in coll) {
  7337. coll[pos].isActive = false;
  7338. }
  7339. });
  7340. // If the series has data draw the ticks. Else only the line and title
  7341. if (axis.hasData() || isLinked) {
  7342. // minor ticks
  7343. if (axis.minorTickInterval && !axis.categories) {
  7344. each(axis.getMinorTickPositions(), function (pos) {
  7345. if (!minorTicks[pos]) {
  7346. minorTicks[pos] = new Tick(axis, pos, 'minor');
  7347. }
  7348. // render new ticks in old position
  7349. if (slideInTicks && minorTicks[pos].isNew) {
  7350. minorTicks[pos].render(null, true);
  7351. }
  7352. minorTicks[pos].render(null, false, 1);
  7353. });
  7354. }
  7355. // Major ticks. Pull out the first item and render it last so that
  7356. // we can get the position of the neighbour label. #808.
  7357. if (tickPositions.length) { // #1300
  7358. each(tickPositions, function (pos, i) {
  7359. // linked axes need an extra check to find out if
  7360. if (!isLinked || (pos >= axis.min && pos <= axis.max)) {
  7361. if (!ticks[pos]) {
  7362. ticks[pos] = new Tick(axis, pos);
  7363. }
  7364. // render new ticks in old position
  7365. if (slideInTicks && ticks[pos].isNew) {
  7366. ticks[pos].render(i, true, 0.1);
  7367. }
  7368. ticks[pos].render(i);
  7369. }
  7370. });
  7371. // In a categorized axis, the tick marks are displayed between labels. So
  7372. // we need to add a tick mark and grid line at the left edge of the X axis.
  7373. if (tickmarkOffset && (axis.min === 0 || axis.single)) {
  7374. if (!ticks[-1]) {
  7375. ticks[-1] = new Tick(axis, -1, null, true);
  7376. }
  7377. ticks[-1].render(-1);
  7378. }
  7379. }
  7380. // alternate grid color
  7381. if (alternateGridColor) {
  7382. each(tickPositions, function (pos, i) {
  7383. to = tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] + tickmarkOffset : axis.max - tickmarkOffset;
  7384. if (i % 2 === 0 && pos < axis.max && to <= axis.max - tickmarkOffset) { // #2248
  7385. if (!alternateBands[pos]) {
  7386. alternateBands[pos] = new Highcharts.PlotLineOrBand(axis);
  7387. }
  7388. from = pos + tickmarkOffset; // #949
  7389. alternateBands[pos].options = {
  7390. from: isLog ? lin2log(from) : from,
  7391. to: isLog ? lin2log(to) : to,
  7392. color: alternateGridColor
  7393. };
  7394. alternateBands[pos].render();
  7395. alternateBands[pos].isActive = true;
  7396. }
  7397. });
  7398. }
  7399. // custom plot lines and bands
  7400. if (!axis._addedPlotLB) { // only first time
  7401. each((options.plotLines || []).concat(options.plotBands || []), function (plotLineOptions) {
  7402. axis.addPlotBandOrLine(plotLineOptions);
  7403. });
  7404. axis._addedPlotLB = true;
  7405. }
  7406. } // end if hasData
  7407. // Remove inactive ticks
  7408. each([ticks, minorTicks, alternateBands], function (coll) {
  7409. var pos,
  7410. i,
  7411. forDestruction = [],
  7412. delay = globalAnimation ? globalAnimation.duration || 500 : 0,
  7413. destroyInactiveItems = function () {
  7414. i = forDestruction.length;
  7415. while (i--) {
  7416. // When resizing rapidly, the same items may be destroyed in different timeouts,
  7417. // or the may be reactivated
  7418. if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) {
  7419. coll[forDestruction[i]].destroy();
  7420. delete coll[forDestruction[i]];
  7421. }
  7422. }
  7423. };
  7424. for (pos in coll) {
  7425. if (!coll[pos].isActive) {
  7426. // Render to zero opacity
  7427. coll[pos].render(pos, false, 0);
  7428. coll[pos].isActive = false;
  7429. forDestruction.push(pos);
  7430. }
  7431. }
  7432. // When the objects are finished fading out, destroy them
  7433. if (coll === alternateBands || !chart.hasRendered || !delay) {
  7434. destroyInactiveItems();
  7435. } else if (delay) {
  7436. setTimeout(destroyInactiveItems, delay);
  7437. }
  7438. });
  7439. // Static items. As the axis group is cleared on subsequent calls
  7440. // to render, these items are added outside the group.
  7441. // axis line
  7442. if (lineWidth) {
  7443. linePath = axis.getLinePath(lineWidth);
  7444. if (!axis.axisLine) {
  7445. axis.axisLine = renderer.path(linePath)
  7446. .attr({
  7447. stroke: options.lineColor,
  7448. 'stroke-width': lineWidth,
  7449. zIndex: 7
  7450. })
  7451. .add(axis.axisGroup);
  7452. } else {
  7453. axis.axisLine.animate({ d: linePath });
  7454. }
  7455. // show or hide the line depending on options.showEmpty
  7456. axis.axisLine[showAxis ? 'show' : 'hide']();
  7457. }
  7458. if (axisTitle && showAxis) {
  7459. axisTitle[axisTitle.isNew ? 'attr' : 'animate'](
  7460. axis.getTitlePosition()
  7461. );
  7462. axisTitle.isNew = false;
  7463. }
  7464. // Stacked totals:
  7465. if (stackLabelOptions && stackLabelOptions.enabled) {
  7466. axis.renderStackTotals();
  7467. }
  7468. // End stacked totals
  7469. axis.isDirty = false;
  7470. },
  7471. /**
  7472. * Redraw the axis to reflect changes in the data or axis extremes
  7473. */
  7474. redraw: function () {
  7475. if (this.visible) {
  7476. // render the axis
  7477. this.render();
  7478. // move plot lines and bands
  7479. each(this.plotLinesAndBands, function (plotLine) {
  7480. plotLine.render();
  7481. });
  7482. }
  7483. // mark associated series as dirty and ready for redraw
  7484. each(this.series, function (series) {
  7485. series.isDirty = true;
  7486. });
  7487. },
  7488. /**
  7489. * Destroys an Axis instance.
  7490. */
  7491. destroy: function (keepEvents) {
  7492. var axis = this,
  7493. stacks = axis.stacks,
  7494. stackKey,
  7495. plotLinesAndBands = axis.plotLinesAndBands,
  7496. i;
  7497. // Remove the events
  7498. if (!keepEvents) {
  7499. removeEvent(axis);
  7500. }
  7501. // Destroy each stack total
  7502. for (stackKey in stacks) {
  7503. destroyObjectProperties(stacks[stackKey]);
  7504. stacks[stackKey] = null;
  7505. }
  7506. // Destroy collections
  7507. each([axis.ticks, axis.minorTicks, axis.alternateBands], function (coll) {
  7508. destroyObjectProperties(coll);
  7509. });
  7510. i = plotLinesAndBands.length;
  7511. while (i--) { // #1975
  7512. plotLinesAndBands[i].destroy();
  7513. }
  7514. // Destroy local variables
  7515. each(['stackTotalGroup', 'axisLine', 'axisTitle', 'axisGroup', 'cross', 'gridGroup', 'labelGroup'], function (prop) {
  7516. if (axis[prop]) {
  7517. axis[prop] = axis[prop].destroy();
  7518. }
  7519. });
  7520. // Destroy crosshair
  7521. if (this.cross) {
  7522. this.cross.destroy();
  7523. }
  7524. },
  7525. /**
  7526. * Draw the crosshair
  7527. */
  7528. drawCrosshair: function (e, point) { // docs: Missing docs for Axis.crosshair. Also for properties.
  7529. var path,
  7530. options = this.crosshair,
  7531. animation = options.animation,
  7532. pos,
  7533. attribs,
  7534. categorized;
  7535. if (
  7536. // Disabled in options
  7537. !this.crosshair ||
  7538. // Snap
  7539. ((defined(point) || !pick(this.crosshair.snap, true)) === false) ||
  7540. // Not on this axis (#4095, #2888)
  7541. (point && point.series && point.series[this.coll] !== this)
  7542. ) {
  7543. this.hideCrosshair();
  7544. } else {
  7545. // Get the path
  7546. if (!pick(options.snap, true)) {
  7547. pos = (this.horiz ? e.chartX - this.pos : this.len - e.chartY + this.pos);
  7548. } else if (defined(point)) {
  7549. /*jslint eqeq: true*/
  7550. pos = this.isXAxis ? point.plotX : this.len - point.plotY; // #3834
  7551. /*jslint eqeq: false*/
  7552. }
  7553. if (this.isRadial) {
  7554. path = this.getPlotLinePath(this.isXAxis ? point.x : pick(point.stackY, point.y)) || null; // #3189
  7555. } else {
  7556. path = this.getPlotLinePath(null, null, null, null, pos) || null; // #3189
  7557. }
  7558. if (path === null) {
  7559. this.hideCrosshair();
  7560. return;
  7561. }
  7562. // Draw the cross
  7563. if (this.cross) {
  7564. this.cross
  7565. .attr({ visibility: VISIBLE })[animation ? 'animate' : 'attr']({ d: path }, animation);
  7566. } else {
  7567. categorized = this.categories && !this.isRadial;
  7568. attribs = {
  7569. 'stroke-width': options.width || (categorized ? this.transA : 1),
  7570. stroke: options.color || (categorized ? 'rgba(155,200,255,0.2)' : '#C0C0C0'),
  7571. zIndex: options.zIndex || 2
  7572. };
  7573. if (options.dashStyle) {
  7574. attribs.dashstyle = options.dashStyle;
  7575. }
  7576. this.cross = this.chart.renderer.path(path).attr(attribs).add();
  7577. }
  7578. }
  7579. },
  7580. /**
  7581. * Hide the crosshair.
  7582. */
  7583. hideCrosshair: function () {
  7584. if (this.cross) {
  7585. this.cross.hide();
  7586. }
  7587. }
  7588. }; // end Axis
  7589. extend(Axis.prototype, AxisPlotLineOrBandExtension);
  7590. /**
  7591. * Set the tick positions to a time unit that makes sense, for example
  7592. * on the first of each month or on every Monday. Return an array
  7593. * with the time positions. Used in datetime axes as well as for grouping
  7594. * data on a datetime axis.
  7595. *
  7596. * @param {Object} normalizedInterval The interval in axis values (ms) and the count
  7597. * @param {Number} min The minimum in axis values
  7598. * @param {Number} max The maximum in axis values
  7599. * @param {Number} startOfWeek
  7600. */
  7601. Axis.prototype.getTimeTicks = function (normalizedInterval, min, max, startOfWeek) {
  7602. var tickPositions = [],
  7603. i,
  7604. higherRanks = {},
  7605. useUTC = defaultOptions.global.useUTC,
  7606. minYear, // used in months and years as a basis for Date.UTC()
  7607. minDate = new Date(min - getTZOffset(min)),
  7608. interval = normalizedInterval.unitRange,
  7609. count = normalizedInterval.count;
  7610. if (defined(min)) { // #1300
  7611. minDate[setMilliseconds](interval >= timeUnits.second ? 0 : // #3935
  7612. count * mathFloor(minDate.getMilliseconds() / count)); // #3652, #3654
  7613. if (interval >= timeUnits.second) { // second
  7614. minDate[setSeconds](interval >= timeUnits.minute ? 0 : // #3935
  7615. count * mathFloor(minDate.getSeconds() / count));
  7616. }
  7617. if (interval >= timeUnits.minute) { // minute
  7618. minDate[setMinutes](interval >= timeUnits.hour ? 0 :
  7619. count * mathFloor(minDate[getMinutes]() / count));
  7620. }
  7621. if (interval >= timeUnits.hour) { // hour
  7622. minDate[setHours](interval >= timeUnits.day ? 0 :
  7623. count * mathFloor(minDate[getHours]() / count));
  7624. }
  7625. if (interval >= timeUnits.day) { // day
  7626. minDate[setDate](interval >= timeUnits.month ? 1 :
  7627. count * mathFloor(minDate[getDate]() / count));
  7628. }
  7629. if (interval >= timeUnits.month) { // month
  7630. minDate[setMonth](interval >= timeUnits.year ? 0 :
  7631. count * mathFloor(minDate[getMonth]() / count));
  7632. minYear = minDate[getFullYear]();
  7633. }
  7634. if (interval >= timeUnits.year) { // year
  7635. minYear -= minYear % count;
  7636. minDate[setFullYear](minYear);
  7637. }
  7638. // week is a special case that runs outside the hierarchy
  7639. if (interval === timeUnits.week) {
  7640. // get start of current week, independent of count
  7641. minDate[setDate](minDate[getDate]() - minDate[getDay]() +
  7642. pick(startOfWeek, 1));
  7643. }
  7644. // get tick positions
  7645. i = 1;
  7646. if (timezoneOffset || getTimezoneOffset) {
  7647. minDate = minDate.getTime();
  7648. minDate = new Date(minDate + getTZOffset(minDate));
  7649. }
  7650. minYear = minDate[getFullYear]();
  7651. var time = minDate.getTime(),
  7652. minMonth = minDate[getMonth](),
  7653. minDateDate = minDate[getDate](),
  7654. localTimezoneOffset = (timeUnits.day +
  7655. (useUTC ? getTZOffset(minDate) : minDate.getTimezoneOffset() * 60 * 1000)
  7656. ) % timeUnits.day; // #950, #3359
  7657. // iterate and add tick positions at appropriate values
  7658. while (time < max) {
  7659. tickPositions.push(time);
  7660. // if the interval is years, use Date.UTC to increase years
  7661. if (interval === timeUnits.year) {
  7662. time = makeTime(minYear + i * count, 0);
  7663. // if the interval is months, use Date.UTC to increase months
  7664. } else if (interval === timeUnits.month) {
  7665. time = makeTime(minYear, minMonth + i * count);
  7666. // if we're using global time, the interval is not fixed as it jumps
  7667. // one hour at the DST crossover
  7668. } else if (!useUTC && (interval === timeUnits.day || interval === timeUnits.week)) {
  7669. time = makeTime(minYear, minMonth, minDateDate +
  7670. i * count * (interval === timeUnits.day ? 1 : 7));
  7671. // else, the interval is fixed and we use simple addition
  7672. } else {
  7673. time += interval * count;
  7674. }
  7675. i++;
  7676. }
  7677. // push the last time
  7678. tickPositions.push(time);
  7679. // mark new days if the time is dividible by day (#1649, #1760)
  7680. each(grep(tickPositions, function (time) {
  7681. return interval <= timeUnits.hour && time % timeUnits.day === localTimezoneOffset;
  7682. }), function (time) {
  7683. higherRanks[time] = 'day';
  7684. });
  7685. }
  7686. // record information on the chosen unit - for dynamic label formatter
  7687. tickPositions.info = extend(normalizedInterval, {
  7688. higherRanks: higherRanks,
  7689. totalRange: interval * count
  7690. });
  7691. return tickPositions;
  7692. };
  7693. /**
  7694. * Get a normalized tick interval for dates. Returns a configuration object with
  7695. * unit range (interval), count and name. Used to prepare data for getTimeTicks.
  7696. * Previously this logic was part of getTimeTicks, but as getTimeTicks now runs
  7697. * of segments in stock charts, the normalizing logic was extracted in order to
  7698. * prevent it for running over again for each segment having the same interval.
  7699. * #662, #697.
  7700. */
  7701. Axis.prototype.normalizeTimeTickInterval = function (tickInterval, unitsOption) {
  7702. var units = unitsOption || [[
  7703. 'millisecond', // unit name
  7704. [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples
  7705. ], [
  7706. 'second',
  7707. [1, 2, 5, 10, 15, 30]
  7708. ], [
  7709. 'minute',
  7710. [1, 2, 5, 10, 15, 30]
  7711. ], [
  7712. 'hour',
  7713. [1, 2, 3, 4, 6, 8, 12]
  7714. ], [
  7715. 'day',
  7716. [1, 2]
  7717. ], [
  7718. 'week',
  7719. [1, 2]
  7720. ], [
  7721. 'month',
  7722. [1, 2, 3, 4, 6]
  7723. ], [
  7724. 'year',
  7725. null
  7726. ]],
  7727. unit = units[units.length - 1], // default unit is years
  7728. interval = timeUnits[unit[0]],
  7729. multiples = unit[1],
  7730. count,
  7731. i;
  7732. // loop through the units to find the one that best fits the tickInterval
  7733. for (i = 0; i < units.length; i++) {
  7734. unit = units[i];
  7735. interval = timeUnits[unit[0]];
  7736. multiples = unit[1];
  7737. if (units[i + 1]) {
  7738. // lessThan is in the middle between the highest multiple and the next unit.
  7739. var lessThan = (interval * multiples[multiples.length - 1] +
  7740. timeUnits[units[i + 1][0]]) / 2;
  7741. // break and keep the current unit
  7742. if (tickInterval <= lessThan) {
  7743. break;
  7744. }
  7745. }
  7746. }
  7747. // prevent 2.5 years intervals, though 25, 250 etc. are allowed
  7748. if (interval === timeUnits.year && tickInterval < 5 * interval) {
  7749. multiples = [1, 2, 5];
  7750. }
  7751. // get the count
  7752. count = normalizeTickInterval(
  7753. tickInterval / interval,
  7754. multiples,
  7755. unit[0] === 'year' ? mathMax(getMagnitude(tickInterval / interval), 1) : 1 // #1913, #2360
  7756. );
  7757. return {
  7758. unitRange: interval,
  7759. count: count,
  7760. unitName: unit[0]
  7761. };
  7762. };/**
  7763. * Methods defined on the Axis prototype
  7764. */
  7765. /**
  7766. * Set the tick positions of a logarithmic axis
  7767. */
  7768. Axis.prototype.getLogTickPositions = function (interval, min, max, minor) {
  7769. var axis = this,
  7770. options = axis.options,
  7771. axisLength = axis.len,
  7772. // Since we use this method for both major and minor ticks,
  7773. // use a local variable and return the result
  7774. positions = [];
  7775. // Reset
  7776. if (!minor) {
  7777. axis._minorAutoInterval = null;
  7778. }
  7779. // First case: All ticks fall on whole logarithms: 1, 10, 100 etc.
  7780. if (interval >= 0.5) {
  7781. interval = mathRound(interval);
  7782. positions = axis.getLinearTickPositions(interval, min, max);
  7783. // Second case: We need intermediary ticks. For example
  7784. // 1, 2, 4, 6, 8, 10, 20, 40 etc.
  7785. } else if (interval >= 0.08) {
  7786. var roundedMin = mathFloor(min),
  7787. intermediate,
  7788. i,
  7789. j,
  7790. len,
  7791. pos,
  7792. lastPos,
  7793. break2;
  7794. if (interval > 0.3) {
  7795. intermediate = [1, 2, 4];
  7796. } else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc
  7797. intermediate = [1, 2, 4, 6, 8];
  7798. } else { // 0.1 equals ten minor ticks per 1, 10, 100 etc
  7799. intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  7800. }
  7801. for (i = roundedMin; i < max + 1 && !break2; i++) {
  7802. len = intermediate.length;
  7803. for (j = 0; j < len && !break2; j++) {
  7804. pos = log2lin(lin2log(i) * intermediate[j]);
  7805. if (pos > min && (!minor || lastPos <= max) && lastPos !== UNDEFINED) { // #1670, lastPos is #3113
  7806. positions.push(lastPos);
  7807. }
  7808. if (lastPos > max) {
  7809. break2 = true;
  7810. }
  7811. lastPos = pos;
  7812. }
  7813. }
  7814. // Third case: We are so deep in between whole logarithmic values that
  7815. // we might as well handle the tick positions like a linear axis. For
  7816. // example 1.01, 1.02, 1.03, 1.04.
  7817. } else {
  7818. var realMin = lin2log(min),
  7819. realMax = lin2log(max),
  7820. tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'],
  7821. filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption,
  7822. tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1),
  7823. totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength;
  7824. interval = pick(
  7825. filteredTickIntervalOption,
  7826. axis._minorAutoInterval,
  7827. (realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1)
  7828. );
  7829. interval = normalizeTickInterval(
  7830. interval,
  7831. null,
  7832. getMagnitude(interval)
  7833. );
  7834. positions = map(axis.getLinearTickPositions(
  7835. interval,
  7836. realMin,
  7837. realMax
  7838. ), log2lin);
  7839. if (!minor) {
  7840. axis._minorAutoInterval = interval / 5;
  7841. }
  7842. }
  7843. // Set the axis-level tickInterval variable
  7844. if (!minor) {
  7845. axis.tickInterval = interval;
  7846. }
  7847. return positions;
  7848. };/**
  7849. * The tooltip object
  7850. * @param {Object} chart The chart instance
  7851. * @param {Object} options Tooltip options
  7852. */
  7853. var Tooltip = Highcharts.Tooltip = function () {
  7854. this.init.apply(this, arguments);
  7855. };
  7856. Tooltip.prototype = {
  7857. init: function (chart, options) {
  7858. var borderWidth = options.borderWidth,
  7859. style = options.style,
  7860. padding = pInt(style.padding);
  7861. // Save the chart and options
  7862. this.chart = chart;
  7863. this.options = options;
  7864. // Keep track of the current series
  7865. //this.currentSeries = UNDEFINED;
  7866. // List of crosshairs
  7867. this.crosshairs = [];
  7868. // Current values of x and y when animating
  7869. this.now = { x: 0, y: 0 };
  7870. // The tooltip is initially hidden
  7871. this.isHidden = true;
  7872. // create the label
  7873. this.label = chart.renderer.label('', 0, 0, options.shape || 'callout', null, null, options.useHTML, null, 'tooltip')
  7874. .attr({
  7875. padding: padding,
  7876. fill: options.backgroundColor,
  7877. 'stroke-width': borderWidth,
  7878. r: options.borderRadius,
  7879. zIndex: 8
  7880. })
  7881. .css(style)
  7882. .css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117)
  7883. .add()
  7884. .attr({ y: -9999 }); // #2301, #2657
  7885. // When using canVG the shadow shows up as a gray circle
  7886. // even if the tooltip is hidden.
  7887. if (!useCanVG) {
  7888. this.label.shadow(options.shadow);
  7889. }
  7890. // Public property for getting the shared state.
  7891. this.shared = options.shared;
  7892. },
  7893. /**
  7894. * Destroy the tooltip and its elements.
  7895. */
  7896. destroy: function () {
  7897. // Destroy and clear local variables
  7898. if (this.label) {
  7899. this.label = this.label.destroy();
  7900. }
  7901. clearTimeout(this.hideTimer);
  7902. clearTimeout(this.tooltipTimeout);
  7903. },
  7904. /**
  7905. * Provide a soft movement for the tooltip
  7906. *
  7907. * @param {Number} x
  7908. * @param {Number} y
  7909. * @private
  7910. */
  7911. move: function (x, y, anchorX, anchorY) {
  7912. var tooltip = this,
  7913. now = tooltip.now,
  7914. animate = tooltip.options.animation !== false && !tooltip.isHidden &&
  7915. // When we get close to the target position, abort animation and land on the right place (#3056)
  7916. (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1),
  7917. skipAnchor = tooltip.followPointer || tooltip.len > 1;
  7918. // Get intermediate values for animation
  7919. extend(now, {
  7920. x: animate ? (2 * now.x + x) / 3 : x,
  7921. y: animate ? (now.y + y) / 2 : y,
  7922. anchorX: skipAnchor ? UNDEFINED : animate ? (2 * now.anchorX + anchorX) / 3 : anchorX,
  7923. anchorY: skipAnchor ? UNDEFINED : animate ? (now.anchorY + anchorY) / 2 : anchorY
  7924. });
  7925. // Move to the intermediate value
  7926. tooltip.label.attr(now);
  7927. // Run on next tick of the mouse tracker
  7928. if (animate) {
  7929. // Never allow two timeouts
  7930. clearTimeout(this.tooltipTimeout);
  7931. // Set the fixed interval ticking for the smooth tooltip
  7932. this.tooltipTimeout = setTimeout(function () {
  7933. // The interval function may still be running during destroy, so check that the chart is really there before calling.
  7934. if (tooltip) {
  7935. tooltip.move(x, y, anchorX, anchorY);
  7936. }
  7937. }, 32);
  7938. }
  7939. },
  7940. /**
  7941. * Hide the tooltip
  7942. */
  7943. hide: function (delay) {
  7944. var tooltip = this,
  7945. hoverPoints;
  7946. clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766)
  7947. if (!this.isHidden) {
  7948. hoverPoints = this.chart.hoverPoints;
  7949. this.hideTimer = setTimeout(function () {
  7950. tooltip.label.fadeOut();
  7951. tooltip.isHidden = true;
  7952. }, pick(delay, this.options.hideDelay, 500));
  7953. }
  7954. },
  7955. /**
  7956. * Extendable method to get the anchor position of the tooltip
  7957. * from a point or set of points
  7958. */
  7959. getAnchor: function (points, mouseEvent) {
  7960. var ret,
  7961. chart = this.chart,
  7962. inverted = chart.inverted,
  7963. plotTop = chart.plotTop,
  7964. plotLeft = chart.plotLeft,
  7965. plotX = 0,
  7966. plotY = 0,
  7967. yAxis,
  7968. xAxis;
  7969. points = splat(points);
  7970. // Pie uses a special tooltipPos
  7971. ret = points[0].tooltipPos;
  7972. // When tooltip follows mouse, relate the position to the mouse
  7973. if (this.followPointer && mouseEvent) {
  7974. if (mouseEvent.chartX === UNDEFINED) {
  7975. mouseEvent = chart.pointer.normalize(mouseEvent);
  7976. }
  7977. ret = [
  7978. mouseEvent.chartX - chart.plotLeft,
  7979. mouseEvent.chartY - plotTop
  7980. ];
  7981. }
  7982. // When shared, use the average position
  7983. if (!ret) {
  7984. each(points, function (point) {
  7985. yAxis = point.series.yAxis;
  7986. xAxis = point.series.xAxis;
  7987. plotX += point.plotX + (!inverted && xAxis ? xAxis.left - plotLeft : 0);
  7988. plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) +
  7989. (!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151
  7990. });
  7991. plotX /= points.length;
  7992. plotY /= points.length;
  7993. ret = [
  7994. inverted ? chart.plotWidth - plotY : plotX,
  7995. this.shared && !inverted && points.length > 1 && mouseEvent ?
  7996. mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424)
  7997. inverted ? chart.plotHeight - plotX : plotY
  7998. ];
  7999. }
  8000. return map(ret, mathRound);
  8001. },
  8002. /**
  8003. * Place the tooltip in a chart without spilling over
  8004. * and not covering the point it self.
  8005. */
  8006. getPosition: function (boxWidth, boxHeight, point) {
  8007. var chart = this.chart,
  8008. distance = this.distance,
  8009. ret = {},
  8010. h = point.h || 0, // #4117
  8011. swapped,
  8012. first = ['y', chart.chartHeight, boxHeight, point.plotY + chart.plotTop, chart.plotTop, chart.plotTop + chart.plotHeight],
  8013. second = ['x', chart.chartWidth, boxWidth, point.plotX + chart.plotLeft, chart.plotLeft, chart.plotLeft + chart.plotWidth],
  8014. // The far side is right or bottom
  8015. preferFarSide = pick(point.ttBelow, (chart.inverted && !point.negative) || (!chart.inverted && point.negative)),
  8016. /**
  8017. * Handle the preferred dimension. When the preferred dimension is tooltip
  8018. * on top or bottom of the point, it will look for space there.
  8019. */
  8020. firstDimension = function (dim, outerSize, innerSize, point, min, max) {
  8021. var roomLeft = innerSize < point - distance,
  8022. roomRight = point + distance + innerSize < outerSize,
  8023. alignedLeft = point - distance - innerSize,
  8024. alignedRight = point + distance;
  8025. if (preferFarSide && roomRight) {
  8026. ret[dim] = alignedRight;
  8027. } else if (!preferFarSide && roomLeft) {
  8028. ret[dim] = alignedLeft;
  8029. } else if (roomLeft) {
  8030. ret[dim] = mathMin(max - innerSize, alignedLeft - h < 0 ? alignedLeft : alignedLeft - h);
  8031. } else if (roomRight) {
  8032. ret[dim] = mathMax(min, alignedRight + h + innerSize > outerSize ? alignedRight : alignedRight + h);
  8033. } else {
  8034. return false;
  8035. }
  8036. },
  8037. /**
  8038. * Handle the secondary dimension. If the preferred dimension is tooltip
  8039. * on top or bottom of the point, the second dimension is to align the tooltip
  8040. * above the point, trying to align center but allowing left or right
  8041. * align within the chart box.
  8042. */
  8043. secondDimension = function (dim, outerSize, innerSize, point) {
  8044. // Too close to the edge, return false and swap dimensions
  8045. if (point < distance || point > outerSize - distance) {
  8046. return false;
  8047. // Align left/top
  8048. } else if (point < innerSize / 2) {
  8049. ret[dim] = 1;
  8050. // Align right/bottom
  8051. } else if (point > outerSize - innerSize / 2) {
  8052. ret[dim] = outerSize - innerSize - 2;
  8053. // Align center
  8054. } else {
  8055. ret[dim] = point - innerSize / 2;
  8056. }
  8057. },
  8058. /**
  8059. * Swap the dimensions
  8060. */
  8061. swap = function (count) {
  8062. var temp = first;
  8063. first = second;
  8064. second = temp;
  8065. swapped = count;
  8066. },
  8067. run = function () {
  8068. if (firstDimension.apply(0, first) !== false) {
  8069. if (secondDimension.apply(0, second) === false && !swapped) {
  8070. swap(true);
  8071. run();
  8072. }
  8073. } else if (!swapped) {
  8074. swap(true);
  8075. run();
  8076. } else {
  8077. ret.x = ret.y = 0;
  8078. }
  8079. };
  8080. // Under these conditions, prefer the tooltip on the side of the point
  8081. if (chart.inverted || this.len > 1) {
  8082. swap();
  8083. }
  8084. run();
  8085. return ret;
  8086. },
  8087. /**
  8088. * In case no user defined formatter is given, this will be used. Note that the context
  8089. * here is an object holding point, series, x, y etc.
  8090. */
  8091. defaultFormatter: function (tooltip) {
  8092. var items = this.points || splat(this),
  8093. s;
  8094. // build the header
  8095. s = [tooltip.tooltipFooterHeaderFormatter(items[0])]; //#3397: abstraction to enable formatting of footer and header
  8096. // build the values
  8097. s = s.concat(tooltip.bodyFormatter(items));
  8098. // footer
  8099. s.push(tooltip.tooltipFooterHeaderFormatter(items[0], true)); //#3397: abstraction to enable formatting of footer and header
  8100. return s.join('');
  8101. },
  8102. /**
  8103. * Refresh the tooltip's text and position.
  8104. * @param {Object} point
  8105. */
  8106. refresh: function (point, mouseEvent) {
  8107. var tooltip = this,
  8108. chart = tooltip.chart,
  8109. label = tooltip.label,
  8110. options = tooltip.options,
  8111. x,
  8112. y,
  8113. anchor,
  8114. textConfig = {},
  8115. text,
  8116. pointConfig = [],
  8117. formatter = options.formatter || tooltip.defaultFormatter,
  8118. hoverPoints = chart.hoverPoints,
  8119. borderColor,
  8120. shared = tooltip.shared,
  8121. currentSeries;
  8122. clearTimeout(this.hideTimer);
  8123. // get the reference point coordinates (pie charts use tooltipPos)
  8124. tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer;
  8125. anchor = tooltip.getAnchor(point, mouseEvent);
  8126. x = anchor[0];
  8127. y = anchor[1];
  8128. // shared tooltip, array is sent over
  8129. if (shared && !(point.series && point.series.noSharedTooltip)) {
  8130. // hide previous hoverPoints and set new
  8131. chart.hoverPoints = point;
  8132. if (hoverPoints) {
  8133. each(hoverPoints, function (point) {
  8134. point.setState();
  8135. });
  8136. }
  8137. each(point, function (item) {
  8138. item.setState(HOVER_STATE);
  8139. pointConfig.push(item.getLabelConfig());
  8140. });
  8141. textConfig = {
  8142. x: point[0].category,
  8143. y: point[0].y
  8144. };
  8145. textConfig.points = pointConfig;
  8146. this.len = pointConfig.length;
  8147. point = point[0];
  8148. // single point tooltip
  8149. } else {
  8150. textConfig = point.getLabelConfig();
  8151. }
  8152. text = formatter.call(textConfig, tooltip);
  8153. // register the current series
  8154. currentSeries = point.series;
  8155. this.distance = pick(currentSeries.tooltipOptions.distance, 16);
  8156. // update the inner HTML
  8157. if (text === false) {
  8158. this.hide();
  8159. } else {
  8160. // show it
  8161. if (tooltip.isHidden) {
  8162. stop(label);
  8163. label.attr('opacity', 1).show();
  8164. }
  8165. // update text
  8166. label.attr({
  8167. text: text
  8168. });
  8169. // set the stroke color of the box
  8170. borderColor = options.borderColor || point.color || currentSeries.color || '#606060';
  8171. label.attr({
  8172. stroke: borderColor
  8173. });
  8174. tooltip.updatePosition({
  8175. plotX: x,
  8176. plotY: y,
  8177. negative: point.negative,
  8178. ttBelow: point.ttBelow,
  8179. h: anchor[2] || 0
  8180. });
  8181. this.isHidden = false;
  8182. }
  8183. fireEvent(chart, 'tooltipRefresh', {
  8184. text: text,
  8185. x: x + chart.plotLeft,
  8186. y: y + chart.plotTop,
  8187. borderColor: borderColor
  8188. });
  8189. },
  8190. /**
  8191. * Find the new position and perform the move
  8192. */
  8193. updatePosition: function (point) {
  8194. var chart = this.chart,
  8195. label = this.label,
  8196. pos = (this.options.positioner || this.getPosition).call(
  8197. this,
  8198. label.width,
  8199. label.height,
  8200. point
  8201. );
  8202. // do the move
  8203. this.move(
  8204. mathRound(pos.x),
  8205. mathRound(pos.y || 0), // can be undefined (#3977)
  8206. point.plotX + chart.plotLeft,
  8207. point.plotY + chart.plotTop
  8208. );
  8209. },
  8210. /**
  8211. * Get the best X date format based on the closest point range on the axis.
  8212. */
  8213. getXDateFormat: function (point, options, xAxis) {
  8214. var xDateFormat,
  8215. dateTimeLabelFormats = options.dateTimeLabelFormats,
  8216. closestPointRange = xAxis && xAxis.closestPointRange,
  8217. n,
  8218. blank = '01-01 00:00:00.000',
  8219. strpos = {
  8220. millisecond: 15,
  8221. second: 12,
  8222. minute: 9,
  8223. hour: 6,
  8224. day: 3
  8225. },
  8226. date,
  8227. lastN = 'millisecond'; // for sub-millisecond data, #4223
  8228. if (closestPointRange) {
  8229. date = dateFormat('%m-%d %H:%M:%S.%L', point.x);
  8230. for (n in timeUnits) {
  8231. // If the range is exactly one week and we're looking at a Sunday/Monday, go for the week format
  8232. if (closestPointRange === timeUnits.week && +dateFormat('%w', point.x) === xAxis.options.startOfWeek &&
  8233. date.substr(6) === blank.substr(6)) {
  8234. n = 'week';
  8235. break;
  8236. // The first format that is too great for the range
  8237. } else if (timeUnits[n] > closestPointRange) {
  8238. n = lastN;
  8239. break;
  8240. // If the point is placed every day at 23:59, we need to show
  8241. // the minutes as well. #2637.
  8242. } else if (strpos[n] && date.substr(strpos[n]) !== blank.substr(strpos[n])) {
  8243. break;
  8244. }
  8245. // Weeks are outside the hierarchy, only apply them on Mondays/Sundays like in the first condition
  8246. if (n !== 'week') {
  8247. lastN = n;
  8248. }
  8249. }
  8250. if (n) {
  8251. xDateFormat = dateTimeLabelFormats[n];
  8252. }
  8253. } else {
  8254. xDateFormat = dateTimeLabelFormats.day;
  8255. }
  8256. return xDateFormat || dateTimeLabelFormats.year; // #2546, 2581
  8257. },
  8258. /**
  8259. * Format the footer/header of the tooltip
  8260. * #3397: abstraction to enable formatting of footer and header
  8261. */
  8262. tooltipFooterHeaderFormatter: function (point, isFooter) {
  8263. var footOrHead = isFooter ? 'footer' : 'header',
  8264. series = point.series,
  8265. tooltipOptions = series.tooltipOptions,
  8266. xDateFormat = tooltipOptions.xDateFormat,
  8267. xAxis = series.xAxis,
  8268. isDateTime = xAxis && xAxis.options.type === 'datetime' && isNumber(point.key),
  8269. formatString = tooltipOptions[footOrHead+'Format'];
  8270. // Guess the best date format based on the closest point distance (#568, #3418)
  8271. if (isDateTime && !xDateFormat) {
  8272. xDateFormat = this.getXDateFormat(point, tooltipOptions, xAxis);
  8273. }
  8274. // Insert the footer date format if any
  8275. if (isDateTime && xDateFormat) {
  8276. formatString = formatString.replace('{point.key}', '{point.key:' + xDateFormat + '}');
  8277. }
  8278. return format(formatString, {
  8279. point: point,
  8280. series: series
  8281. });
  8282. },
  8283. /**
  8284. * Build the body (lines) of the tooltip by iterating over the items and returning one entry for each item,
  8285. * abstracting this functionality allows to easily overwrite and extend it.
  8286. */
  8287. bodyFormatter: function (items) {
  8288. return map(items, function (item) {
  8289. var tooltipOptions = item.series.tooltipOptions;
  8290. return (tooltipOptions.pointFormatter || item.point.tooltipFormatter).call(item.point, tooltipOptions.pointFormat);
  8291. });
  8292. }
  8293. };
  8294. var hoverChartIndex;
  8295. // Global flag for touch support
  8296. hasTouch = doc.documentElement.ontouchstart !== UNDEFINED;
  8297. /**
  8298. * The mouse tracker object. All methods starting with "on" are primary DOM event handlers.
  8299. * Subsequent methods should be named differently from what they are doing.
  8300. * @param {Object} chart The Chart instance
  8301. * @param {Object} options The root options object
  8302. */
  8303. var Pointer = Highcharts.Pointer = function (chart, options) {
  8304. this.init(chart, options);
  8305. };
  8306. Pointer.prototype = {
  8307. /**
  8308. * Initialize Pointer
  8309. */
  8310. init: function (chart, options) {
  8311. var chartOptions = options.chart,
  8312. chartEvents = chartOptions.events,
  8313. zoomType = useCanVG ? '' : chartOptions.zoomType,
  8314. inverted = chart.inverted,
  8315. zoomX,
  8316. zoomY;
  8317. // Store references
  8318. this.options = options;
  8319. this.chart = chart;
  8320. // Zoom status
  8321. this.zoomX = zoomX = /x/.test(zoomType);
  8322. this.zoomY = zoomY = /y/.test(zoomType);
  8323. this.zoomHor = (zoomX && !inverted) || (zoomY && inverted);
  8324. this.zoomVert = (zoomY && !inverted) || (zoomX && inverted);
  8325. this.hasZoom = zoomX || zoomY;
  8326. // Do we need to handle click on a touch device?
  8327. this.runChartClick = chartEvents && !!chartEvents.click;
  8328. this.pinchDown = [];
  8329. this.lastValidTouch = {};
  8330. if (Highcharts.Tooltip && options.tooltip.enabled) {
  8331. chart.tooltip = new Tooltip(chart, options.tooltip);
  8332. this.followTouchMove = pick(options.tooltip.followTouchMove, true);
  8333. }
  8334. this.setDOMEvents();
  8335. },
  8336. /**
  8337. * Add crossbrowser support for chartX and chartY
  8338. * @param {Object} e The event object in standard browsers
  8339. */
  8340. normalize: function (e, chartPosition) {
  8341. var chartX,
  8342. chartY,
  8343. ePos;
  8344. // common IE normalizing
  8345. e = e || window.event;
  8346. // Framework specific normalizing (#1165)
  8347. e = washMouseEvent(e);
  8348. // More IE normalizing, needs to go after washMouseEvent
  8349. if (!e.target) {
  8350. e.target = e.srcElement;
  8351. }
  8352. // iOS (#2757)
  8353. ePos = e.touches ? (e.touches.length ? e.touches.item(0) : e.changedTouches[0]) : e;
  8354. // Get mouse position
  8355. if (!chartPosition) {
  8356. this.chartPosition = chartPosition = offset(this.chart.container);
  8357. }
  8358. // chartX and chartY
  8359. if (ePos.pageX === UNDEFINED) { // IE < 9. #886.
  8360. chartX = mathMax(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is
  8361. // for IE10 quirks mode within framesets
  8362. chartY = e.y;
  8363. } else {
  8364. chartX = ePos.pageX - chartPosition.left;
  8365. chartY = ePos.pageY - chartPosition.top;
  8366. }
  8367. return extend(e, {
  8368. chartX: mathRound(chartX),
  8369. chartY: mathRound(chartY)
  8370. });
  8371. },
  8372. /**
  8373. * Get the click position in terms of axis values.
  8374. *
  8375. * @param {Object} e A pointer event
  8376. */
  8377. getCoordinates: function (e) {
  8378. var coordinates = {
  8379. xAxis: [],
  8380. yAxis: []
  8381. };
  8382. each(this.chart.axes, function (axis) {
  8383. coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({
  8384. axis: axis,
  8385. value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY'])
  8386. });
  8387. });
  8388. return coordinates;
  8389. },
  8390. /**
  8391. * With line type charts with a single tracker, get the point closest to the mouse.
  8392. * Run Point.onMouseOver and display tooltip for the point or points.
  8393. */
  8394. runPointActions: function (e) {
  8395. var pointer = this,
  8396. chart = pointer.chart,
  8397. series = chart.series,
  8398. tooltip = chart.tooltip,
  8399. shared = tooltip ? tooltip.shared : false,
  8400. followPointer,
  8401. hoverPoint = chart.hoverPoint,
  8402. hoverSeries = chart.hoverSeries,
  8403. i,
  8404. distance = Number.MAX_VALUE, // #4511
  8405. anchor,
  8406. noSharedTooltip,
  8407. stickToHoverSeries,
  8408. directTouch,
  8409. kdpoints = [],
  8410. kdpoint,
  8411. kdpointT;
  8412. // For hovering over the empty parts of the plot area (hoverSeries is undefined).
  8413. // If there is one series with point tracking (combo chart), don't go to nearest neighbour.
  8414. if (!shared && !hoverSeries) {
  8415. for (i = 0; i < series.length; i++) {
  8416. if (series[i].directTouch || !series[i].options.stickyTracking) {
  8417. series = [];
  8418. }
  8419. }
  8420. }
  8421. // If it has a hoverPoint and that series requires direct touch (like columns, #3899), or we're on
  8422. // a noSharedTooltip series among shared tooltip series (#4546), use the hoverPoint . Otherwise,
  8423. // search the k-d tree.
  8424. stickToHoverSeries = hoverSeries && (shared ? hoverSeries.noSharedTooltip : hoverSeries.directTouch);
  8425. if (stickToHoverSeries && hoverPoint) {
  8426. kdpoint = hoverPoint;
  8427. // Handle shared tooltip or cases where a series is not yet hovered
  8428. } else {
  8429. // Find nearest points on all series
  8430. each(series, function (s) {
  8431. // Skip hidden series
  8432. noSharedTooltip = s.noSharedTooltip && shared;
  8433. directTouch = !shared && s.directTouch;
  8434. if (s.visible && !noSharedTooltip && !directTouch && pick(s.options.enableMouseTracking, true)) { // #3821
  8435. kdpointT = s.searchPoint(e, !noSharedTooltip && s.kdDimensions === 1); // #3828
  8436. if (kdpointT) {
  8437. kdpoints.push(kdpointT);
  8438. }
  8439. }
  8440. });
  8441. // Find absolute nearest point
  8442. each(kdpoints, function (p) {
  8443. if (p && typeof p.dist === 'number' && p.dist < distance) {
  8444. distance = p.dist;
  8445. kdpoint = p;
  8446. }
  8447. });
  8448. }
  8449. // Refresh tooltip for kdpoint if new hover point or tooltip was hidden // #3926, #4200
  8450. if (kdpoint && (kdpoint !== this.prevKDPoint || (tooltip && tooltip.isHidden))) {
  8451. // Draw tooltip if necessary
  8452. if (shared && !kdpoint.series.noSharedTooltip) {
  8453. i = kdpoints.length;
  8454. while (i--) {
  8455. if (kdpoints[i].clientX !== kdpoint.clientX || kdpoints[i].series.noSharedTooltip) {
  8456. kdpoints.splice(i, 1);
  8457. }
  8458. }
  8459. if (kdpoints.length && tooltip) {
  8460. tooltip.refresh(kdpoints, e);
  8461. }
  8462. // Do mouseover on all points (#3919, #3985, #4410)
  8463. each(kdpoints, function (point) {
  8464. point.onMouseOver(e, point !== ((hoverSeries && hoverSeries.directTouch && hoverPoint) || kdpoint));
  8465. });
  8466. } else {
  8467. if (tooltip) {
  8468. tooltip.refresh(kdpoint, e);
  8469. }
  8470. if(!hoverSeries || !hoverSeries.directTouch) { // #4448
  8471. kdpoint.onMouseOver(e);
  8472. }
  8473. }
  8474. this.prevKDPoint = kdpoint;
  8475. // Update positions (regardless of kdpoint or hoverPoint)
  8476. } else {
  8477. followPointer = hoverSeries && hoverSeries.tooltipOptions.followPointer;
  8478. if (tooltip && followPointer && !tooltip.isHidden) {
  8479. anchor = tooltip.getAnchor([{}], e);
  8480. tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] });
  8481. }
  8482. }
  8483. // Start the event listener to pick up the tooltip
  8484. if (tooltip && !pointer._onDocumentMouseMove) {
  8485. pointer._onDocumentMouseMove = function (e) {
  8486. if (charts[hoverChartIndex]) {
  8487. charts[hoverChartIndex].pointer.onDocumentMouseMove(e);
  8488. }
  8489. };
  8490. addEvent(doc, 'mousemove', pointer._onDocumentMouseMove);
  8491. }
  8492. // Crosshair
  8493. each(chart.axes, function (axis) {
  8494. axis.drawCrosshair(e, pick(kdpoint, hoverPoint));
  8495. });
  8496. },
  8497. /**
  8498. * Reset the tracking by hiding the tooltip, the hover series state and the hover point
  8499. *
  8500. * @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible
  8501. */
  8502. reset: function (allowMove, delay) {
  8503. var pointer = this,
  8504. chart = pointer.chart,
  8505. hoverSeries = chart.hoverSeries,
  8506. hoverPoint = chart.hoverPoint,
  8507. hoverPoints = chart.hoverPoints,
  8508. tooltip = chart.tooltip,
  8509. tooltipPoints = tooltip && tooltip.shared ? hoverPoints : hoverPoint;
  8510. // Narrow in allowMove
  8511. allowMove = allowMove && tooltip && tooltipPoints;
  8512. // Check if the points have moved outside the plot area, #1003
  8513. if (allowMove && splat(tooltipPoints)[0].plotX === UNDEFINED) {
  8514. allowMove = false;
  8515. }
  8516. // Just move the tooltip, #349
  8517. if (allowMove) {
  8518. tooltip.refresh(tooltipPoints);
  8519. if (hoverPoint) { // #2500
  8520. hoverPoint.setState(hoverPoint.state, true);
  8521. each(chart.axes, function (axis) {
  8522. if (pick(axis.options.crosshair && axis.options.crosshair.snap, true)) {
  8523. axis.drawCrosshair(null, hoverPoint);
  8524. } else {
  8525. axis.hideCrosshair();
  8526. }
  8527. });
  8528. }
  8529. // Full reset
  8530. } else {
  8531. if (hoverPoint) {
  8532. hoverPoint.onMouseOut();
  8533. }
  8534. if (hoverPoints) {
  8535. each(hoverPoints, function (point) {
  8536. point.setState();
  8537. });
  8538. }
  8539. if (hoverSeries) {
  8540. hoverSeries.onMouseOut();
  8541. }
  8542. if (tooltip) {
  8543. tooltip.hide(delay);
  8544. }
  8545. if (pointer._onDocumentMouseMove) {
  8546. removeEvent(doc, 'mousemove', pointer._onDocumentMouseMove);
  8547. pointer._onDocumentMouseMove = null;
  8548. }
  8549. // Remove crosshairs
  8550. each(chart.axes, function (axis) {
  8551. axis.hideCrosshair();
  8552. });
  8553. pointer.hoverX = chart.hoverPoints = chart.hoverPoint = null;
  8554. }
  8555. },
  8556. /**
  8557. * Scale series groups to a certain scale and translation
  8558. */
  8559. scaleGroups: function (attribs, clip) {
  8560. var chart = this.chart,
  8561. seriesAttribs;
  8562. // Scale each series
  8563. each(chart.series, function (series) {
  8564. seriesAttribs = attribs || series.getPlotBox(); // #1701
  8565. if (series.xAxis && series.xAxis.zoomEnabled) {
  8566. series.group.attr(seriesAttribs);
  8567. if (series.markerGroup) {
  8568. series.markerGroup.attr(seriesAttribs);
  8569. series.markerGroup.clip(clip ? chart.clipRect : null);
  8570. }
  8571. if (series.dataLabelsGroup) {
  8572. series.dataLabelsGroup.attr(seriesAttribs);
  8573. }
  8574. }
  8575. });
  8576. // Clip
  8577. chart.clipRect.attr(clip || chart.clipBox);
  8578. },
  8579. /**
  8580. * Start a drag operation
  8581. */
  8582. dragStart: function (e) {
  8583. var chart = this.chart;
  8584. // Record the start position
  8585. chart.mouseIsDown = e.type;
  8586. chart.cancelClick = false;
  8587. chart.mouseDownX = this.mouseDownX = e.chartX;
  8588. chart.mouseDownY = this.mouseDownY = e.chartY;
  8589. },
  8590. /**
  8591. * Perform a drag operation in response to a mousemove event while the mouse is down
  8592. */
  8593. drag: function (e) {
  8594. var chart = this.chart,
  8595. chartOptions = chart.options.chart,
  8596. chartX = e.chartX,
  8597. chartY = e.chartY,
  8598. zoomHor = this.zoomHor,
  8599. zoomVert = this.zoomVert,
  8600. plotLeft = chart.plotLeft,
  8601. plotTop = chart.plotTop,
  8602. plotWidth = chart.plotWidth,
  8603. plotHeight = chart.plotHeight,
  8604. clickedInside,
  8605. size,
  8606. selectionMarker = this.selectionMarker,
  8607. mouseDownX = this.mouseDownX,
  8608. mouseDownY = this.mouseDownY,
  8609. panKey = chartOptions.panKey && e[chartOptions.panKey + 'Key'];
  8610. // If the device supports both touch and mouse (like IE11), and we are touch-dragging
  8611. // inside the plot area, don't handle the mouse event. #4339.
  8612. if (selectionMarker && selectionMarker.touch) {
  8613. return;
  8614. }
  8615. // If the mouse is outside the plot area, adjust to cooordinates
  8616. // inside to prevent the selection marker from going outside
  8617. if (chartX < plotLeft) {
  8618. chartX = plotLeft;
  8619. } else if (chartX > plotLeft + plotWidth) {
  8620. chartX = plotLeft + plotWidth;
  8621. }
  8622. if (chartY < plotTop) {
  8623. chartY = plotTop;
  8624. } else if (chartY > plotTop + plotHeight) {
  8625. chartY = plotTop + plotHeight;
  8626. }
  8627. // determine if the mouse has moved more than 10px
  8628. this.hasDragged = Math.sqrt(
  8629. Math.pow(mouseDownX - chartX, 2) +
  8630. Math.pow(mouseDownY - chartY, 2)
  8631. );
  8632. if (this.hasDragged > 10) {
  8633. clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop);
  8634. // make a selection
  8635. if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside && !panKey) {
  8636. if (!selectionMarker) {
  8637. this.selectionMarker = selectionMarker = chart.renderer.rect(
  8638. plotLeft,
  8639. plotTop,
  8640. zoomHor ? 1 : plotWidth,
  8641. zoomVert ? 1 : plotHeight,
  8642. 0
  8643. )
  8644. .attr({
  8645. fill: chartOptions.selectionMarkerFill || 'rgba(69,114,167,0.25)',
  8646. zIndex: 7
  8647. })
  8648. .add();
  8649. }
  8650. }
  8651. // adjust the width of the selection marker
  8652. if (selectionMarker && zoomHor) {
  8653. size = chartX - mouseDownX;
  8654. selectionMarker.attr({
  8655. width: mathAbs(size),
  8656. x: (size > 0 ? 0 : size) + mouseDownX
  8657. });
  8658. }
  8659. // adjust the height of the selection marker
  8660. if (selectionMarker && zoomVert) {
  8661. size = chartY - mouseDownY;
  8662. selectionMarker.attr({
  8663. height: mathAbs(size),
  8664. y: (size > 0 ? 0 : size) + mouseDownY
  8665. });
  8666. }
  8667. // panning
  8668. if (clickedInside && !selectionMarker && chartOptions.panning) {
  8669. chart.pan(e, chartOptions.panning);
  8670. }
  8671. }
  8672. },
  8673. /**
  8674. * On mouse up or touch end across the entire document, drop the selection.
  8675. */
  8676. drop: function (e) {
  8677. var pointer = this,
  8678. chart = this.chart,
  8679. hasPinched = this.hasPinched;
  8680. if (this.selectionMarker) {
  8681. var selectionData = {
  8682. xAxis: [],
  8683. yAxis: [],
  8684. originalEvent: e.originalEvent || e
  8685. },
  8686. selectionBox = this.selectionMarker,
  8687. selectionLeft = selectionBox.attr ? selectionBox.attr('x') : selectionBox.x,
  8688. selectionTop = selectionBox.attr ? selectionBox.attr('y') : selectionBox.y,
  8689. selectionWidth = selectionBox.attr ? selectionBox.attr('width') : selectionBox.width,
  8690. selectionHeight = selectionBox.attr ? selectionBox.attr('height') : selectionBox.height,
  8691. runZoom;
  8692. // a selection has been made
  8693. if (this.hasDragged || hasPinched) {
  8694. // record each axis' min and max
  8695. each(chart.axes, function (axis) {
  8696. if (axis.zoomEnabled && defined(axis.min) && (hasPinched || pointer[{ xAxis: 'zoomX', yAxis: 'zoomY' }[axis.coll]])) { // #859, #3569
  8697. var horiz = axis.horiz,
  8698. minPixelPadding = e.type === 'touchend' ? axis.minPixelPadding: 0, // #1207, #3075
  8699. selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop) + minPixelPadding),
  8700. selectionMax = axis.toValue((horiz ? selectionLeft + selectionWidth : selectionTop + selectionHeight) - minPixelPadding);
  8701. selectionData[axis.coll].push({
  8702. axis: axis,
  8703. min: mathMin(selectionMin, selectionMax), // for reversed axes
  8704. max: mathMax(selectionMin, selectionMax)
  8705. });
  8706. runZoom = true;
  8707. }
  8708. });
  8709. if (runZoom) {
  8710. fireEvent(chart, 'selection', selectionData, function (args) {
  8711. chart.zoom(extend(args, hasPinched ? { animation: false } : null));
  8712. });
  8713. }
  8714. }
  8715. this.selectionMarker = this.selectionMarker.destroy();
  8716. // Reset scaling preview
  8717. if (hasPinched) {
  8718. this.scaleGroups();
  8719. }
  8720. }
  8721. // Reset all
  8722. if (chart) { // it may be destroyed on mouse up - #877
  8723. css(chart.container, { cursor: chart._cursor });
  8724. chart.cancelClick = this.hasDragged > 10; // #370
  8725. chart.mouseIsDown = this.hasDragged = this.hasPinched = false;
  8726. this.pinchDown = [];
  8727. }
  8728. },
  8729. onContainerMouseDown: function (e) {
  8730. e = this.normalize(e);
  8731. // issue #295, dragging not always working in Firefox
  8732. if (e.preventDefault) {
  8733. e.preventDefault();
  8734. }
  8735. this.dragStart(e);
  8736. },
  8737. onDocumentMouseUp: function (e) {
  8738. if (charts[hoverChartIndex]) {
  8739. charts[hoverChartIndex].pointer.drop(e);
  8740. }
  8741. },
  8742. /**
  8743. * Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea.
  8744. * Issue #149 workaround. The mouseleave event does not always fire.
  8745. */
  8746. onDocumentMouseMove: function (e) {
  8747. var chart = this.chart,
  8748. chartPosition = this.chartPosition;
  8749. e = this.normalize(e, chartPosition);
  8750. // If we're outside, hide the tooltip
  8751. if (chartPosition && !this.inClass(e.target, 'highcharts-tracker') &&
  8752. !chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
  8753. this.reset();
  8754. }
  8755. },
  8756. /**
  8757. * When mouse leaves the container, hide the tooltip.
  8758. */
  8759. onContainerMouseLeave: function () {
  8760. var chart = charts[hoverChartIndex];
  8761. if (chart) {
  8762. chart.pointer.reset();
  8763. chart.pointer.chartPosition = null; // also reset the chart position, used in #149 fix
  8764. }
  8765. },
  8766. // The mousemove, touchmove and touchstart event handler
  8767. onContainerMouseMove: function (e) {
  8768. var chart = this.chart;
  8769. hoverChartIndex = chart.index;
  8770. e = this.normalize(e);
  8771. e.returnValue = false; // #2251, #3224
  8772. if (chart.mouseIsDown === 'mousedown') {
  8773. this.drag(e);
  8774. }
  8775. // Show the tooltip and run mouse over events (#977)
  8776. if ((this.inClass(e.target, 'highcharts-tracker') ||
  8777. chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) {
  8778. this.runPointActions(e);
  8779. }
  8780. },
  8781. /**
  8782. * Utility to detect whether an element has, or has a parent with, a specific
  8783. * class name. Used on detection of tracker objects and on deciding whether
  8784. * hovering the tooltip should cause the active series to mouse out.
  8785. */
  8786. inClass: function (element, className) {
  8787. var elemClassName;
  8788. while (element) {
  8789. elemClassName = attr(element, 'class');
  8790. if (elemClassName) {
  8791. if (elemClassName.indexOf(className) !== -1) {
  8792. return true;
  8793. } else if (elemClassName.indexOf(PREFIX + 'container') !== -1) {
  8794. return false;
  8795. }
  8796. }
  8797. element = element.parentNode;
  8798. }
  8799. },
  8800. onTrackerMouseOut: function (e) {
  8801. var series = this.chart.hoverSeries,
  8802. relatedTarget = e.relatedTarget || e.toElement;
  8803. if (series && !series.options.stickyTracking &&
  8804. !this.inClass(relatedTarget, PREFIX + 'tooltip') &&
  8805. !this.inClass(relatedTarget, PREFIX + 'series-' + series.index)) { // #2499, #4465
  8806. series.onMouseOut();
  8807. }
  8808. },
  8809. onContainerClick: function (e) {
  8810. var chart = this.chart,
  8811. hoverPoint = chart.hoverPoint,
  8812. plotLeft = chart.plotLeft,
  8813. plotTop = chart.plotTop;
  8814. e = this.normalize(e);
  8815. e.originalEvent = e; // #3913
  8816. if (!chart.cancelClick) {
  8817. // On tracker click, fire the series and point events. #783, #1583
  8818. if (hoverPoint && this.inClass(e.target, PREFIX + 'tracker')) {
  8819. // the series click event
  8820. fireEvent(hoverPoint.series, 'click', extend(e, {
  8821. point: hoverPoint
  8822. }));
  8823. // the point click event
  8824. if (chart.hoverPoint) { // it may be destroyed (#1844)
  8825. hoverPoint.firePointEvent('click', e);
  8826. }
  8827. // When clicking outside a tracker, fire a chart event
  8828. } else {
  8829. extend(e, this.getCoordinates(e));
  8830. // fire a click event in the chart
  8831. if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) {
  8832. fireEvent(chart, 'click', e);
  8833. }
  8834. }
  8835. }
  8836. },
  8837. /**
  8838. * Set the JS DOM events on the container and document. This method should contain
  8839. * a one-to-one assignment between methods and their handlers. Any advanced logic should
  8840. * be moved to the handler reflecting the event's name.
  8841. */
  8842. setDOMEvents: function () {
  8843. var pointer = this,
  8844. container = pointer.chart.container;
  8845. container.onmousedown = function (e) {
  8846. pointer.onContainerMouseDown(e);
  8847. };
  8848. container.onmousemove = function (e) {
  8849. pointer.onContainerMouseMove(e);
  8850. };
  8851. container.onclick = function (e) {
  8852. pointer.onContainerClick(e);
  8853. };
  8854. addEvent(container, 'mouseleave', pointer.onContainerMouseLeave);
  8855. if (chartCount === 1) {
  8856. addEvent(doc, 'mouseup', pointer.onDocumentMouseUp);
  8857. }
  8858. if (hasTouch) {
  8859. container.ontouchstart = function (e) {
  8860. pointer.onContainerTouchStart(e);
  8861. };
  8862. container.ontouchmove = function (e) {
  8863. pointer.onContainerTouchMove(e);
  8864. };
  8865. if (chartCount === 1) {
  8866. addEvent(doc, 'touchend', pointer.onDocumentTouchEnd);
  8867. }
  8868. }
  8869. },
  8870. /**
  8871. * Destroys the Pointer object and disconnects DOM events.
  8872. */
  8873. destroy: function () {
  8874. var prop;
  8875. removeEvent(this.chart.container, 'mouseleave', this.onContainerMouseLeave);
  8876. if (!chartCount) {
  8877. removeEvent(doc, 'mouseup', this.onDocumentMouseUp);
  8878. removeEvent(doc, 'touchend', this.onDocumentTouchEnd);
  8879. }
  8880. // memory and CPU leak
  8881. clearInterval(this.tooltipTimeout);
  8882. for (prop in this) {
  8883. this[prop] = null;
  8884. }
  8885. }
  8886. };
  8887. /* Support for touch devices */
  8888. extend(Highcharts.Pointer.prototype, {
  8889. /**
  8890. * Run translation operations
  8891. */
  8892. pinchTranslate: function (pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) {
  8893. if (this.zoomHor || this.pinchHor) {
  8894. this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
  8895. }
  8896. if (this.zoomVert || this.pinchVert) {
  8897. this.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
  8898. }
  8899. },
  8900. /**
  8901. * Run translation operations for each direction (horizontal and vertical) independently
  8902. */
  8903. pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch, forcedScale) {
  8904. var chart = this.chart,
  8905. xy = horiz ? 'x' : 'y',
  8906. XY = horiz ? 'X' : 'Y',
  8907. sChartXY = 'chart' + XY,
  8908. wh = horiz ? 'width' : 'height',
  8909. plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')],
  8910. selectionWH,
  8911. selectionXY,
  8912. clipXY,
  8913. scale = forcedScale || 1,
  8914. inverted = chart.inverted,
  8915. bounds = chart.bounds[horiz ? 'h' : 'v'],
  8916. singleTouch = pinchDown.length === 1,
  8917. touch0Start = pinchDown[0][sChartXY],
  8918. touch0Now = touches[0][sChartXY],
  8919. touch1Start = !singleTouch && pinchDown[1][sChartXY],
  8920. touch1Now = !singleTouch && touches[1][sChartXY],
  8921. outOfBounds,
  8922. transformScale,
  8923. scaleKey,
  8924. setScale = function () {
  8925. if (!singleTouch && mathAbs(touch0Start - touch1Start) > 20) { // Don't zoom if fingers are too close on this axis
  8926. scale = forcedScale || mathAbs(touch0Now - touch1Now) / mathAbs(touch0Start - touch1Start);
  8927. }
  8928. clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start;
  8929. selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale;
  8930. };
  8931. // Set the scale, first pass
  8932. setScale();
  8933. selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not
  8934. // Out of bounds
  8935. if (selectionXY < bounds.min) {
  8936. selectionXY = bounds.min;
  8937. outOfBounds = true;
  8938. } else if (selectionXY + selectionWH > bounds.max) {
  8939. selectionXY = bounds.max - selectionWH;
  8940. outOfBounds = true;
  8941. }
  8942. // Is the chart dragged off its bounds, determined by dataMin and dataMax?
  8943. if (outOfBounds) {
  8944. // Modify the touchNow position in order to create an elastic drag movement. This indicates
  8945. // to the user that the chart is responsive but can't be dragged further.
  8946. touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]);
  8947. if (!singleTouch) {
  8948. touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]);
  8949. }
  8950. // Set the scale, second pass to adapt to the modified touchNow positions
  8951. setScale();
  8952. } else {
  8953. lastValidTouch[xy] = [touch0Now, touch1Now];
  8954. }
  8955. // Set geometry for clipping, selection and transformation
  8956. if (!inverted) { // TODO: implement clipping for inverted charts
  8957. clip[xy] = clipXY - plotLeftTop;
  8958. clip[wh] = selectionWH;
  8959. }
  8960. scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY;
  8961. transformScale = inverted ? 1 / scale : scale;
  8962. selectionMarker[wh] = selectionWH;
  8963. selectionMarker[xy] = selectionXY;
  8964. transform[scaleKey] = scale;
  8965. transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start));
  8966. },
  8967. /**
  8968. * Handle touch events with two touches
  8969. */
  8970. pinch: function (e) {
  8971. var self = this,
  8972. chart = self.chart,
  8973. pinchDown = self.pinchDown,
  8974. touches = e.touches,
  8975. touchesLength = touches.length,
  8976. lastValidTouch = self.lastValidTouch,
  8977. hasZoom = self.hasZoom,
  8978. selectionMarker = self.selectionMarker,
  8979. transform = {},
  8980. fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, PREFIX + 'tracker') &&
  8981. chart.runTrackerClick) || self.runChartClick),
  8982. clip = {};
  8983. // Don't initiate panning until the user has pinched. This prevents us from
  8984. // blocking page scrolling as users scroll down a long page (#4210).
  8985. if (touchesLength > 1) {
  8986. self.initiated = true;
  8987. }
  8988. // On touch devices, only proceed to trigger click if a handler is defined
  8989. if (hasZoom && self.initiated && !fireClickEvent) {
  8990. e.preventDefault();
  8991. }
  8992. // Normalize each touch
  8993. map(touches, function (e) {
  8994. return self.normalize(e);
  8995. });
  8996. // Register the touch start position
  8997. if (e.type === 'touchstart') {
  8998. each(touches, function (e, i) {
  8999. pinchDown[i] = { chartX: e.chartX, chartY: e.chartY };
  9000. });
  9001. lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX];
  9002. lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY];
  9003. // Identify the data bounds in pixels
  9004. each(chart.axes, function (axis) {
  9005. if (axis.zoomEnabled) {
  9006. var bounds = chart.bounds[axis.horiz ? 'h' : 'v'],
  9007. minPixelPadding = axis.minPixelPadding,
  9008. min = axis.toPixels(pick(axis.options.min, axis.dataMin)),
  9009. max = axis.toPixels(pick(axis.options.max, axis.dataMax)),
  9010. absMin = mathMin(min, max),
  9011. absMax = mathMax(min, max);
  9012. // Store the bounds for use in the touchmove handler
  9013. bounds.min = mathMin(axis.pos, absMin - minPixelPadding);
  9014. bounds.max = mathMax(axis.pos + axis.len, absMax + minPixelPadding);
  9015. }
  9016. });
  9017. self.res = true; // reset on next move
  9018. // Event type is touchmove, handle panning and pinching
  9019. } else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first
  9020. // Set the marker
  9021. if (!selectionMarker) {
  9022. self.selectionMarker = selectionMarker = extend({
  9023. destroy: noop,
  9024. touch: true
  9025. }, chart.plotBox);
  9026. }
  9027. self.pinchTranslate(pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
  9028. self.hasPinched = hasZoom;
  9029. // Scale and translate the groups to provide visual feedback during pinching
  9030. self.scaleGroups(transform, clip);
  9031. // Optionally move the tooltip on touchmove
  9032. if (!hasZoom && self.followTouchMove && touchesLength === 1) {
  9033. this.runPointActions(self.normalize(e));
  9034. } else if (self.res) {
  9035. self.res = false;
  9036. this.reset(false, 0);
  9037. }
  9038. }
  9039. },
  9040. /**
  9041. * General touch handler shared by touchstart and touchmove.
  9042. */
  9043. touch: function (e, start) {
  9044. var chart = this.chart;
  9045. hoverChartIndex = chart.index;
  9046. if (e.touches.length === 1) {
  9047. e = this.normalize(e);
  9048. if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop) && !chart.openMenu) {
  9049. // Run mouse events and display tooltip etc
  9050. if (start) {
  9051. this.runPointActions(e);
  9052. }
  9053. this.pinch(e);
  9054. } else if (start) {
  9055. // Hide the tooltip on touching outside the plot area (#1203)
  9056. this.reset();
  9057. }
  9058. } else if (e.touches.length === 2) {
  9059. this.pinch(e);
  9060. }
  9061. },
  9062. onContainerTouchStart: function (e) {
  9063. this.touch(e, true);
  9064. },
  9065. onContainerTouchMove: function (e) {
  9066. this.touch(e);
  9067. },
  9068. onDocumentTouchEnd: function (e) {
  9069. if (charts[hoverChartIndex]) {
  9070. charts[hoverChartIndex].pointer.drop(e);
  9071. }
  9072. }
  9073. });
  9074. if (win.PointerEvent || win.MSPointerEvent) {
  9075. // The touches object keeps track of the points being touched at all times
  9076. var touches = {},
  9077. hasPointerEvent = !!win.PointerEvent,
  9078. getWebkitTouches = function () {
  9079. var key, fake = [];
  9080. fake.item = function (i) { return this[i]; };
  9081. for (key in touches) {
  9082. if (touches.hasOwnProperty(key)) {
  9083. fake.push({
  9084. pageX: touches[key].pageX,
  9085. pageY: touches[key].pageY,
  9086. target: touches[key].target
  9087. });
  9088. }
  9089. }
  9090. return fake;
  9091. },
  9092. translateMSPointer = function (e, method, wktype, callback) {
  9093. var p;
  9094. e = e.originalEvent || e;
  9095. if ((e.pointerType === 'touch' || e.pointerType === e.MSPOINTER_TYPE_TOUCH) && charts[hoverChartIndex]) {
  9096. callback(e);
  9097. p = charts[hoverChartIndex].pointer;
  9098. p[method]({
  9099. type: wktype,
  9100. target: e.currentTarget,
  9101. preventDefault: noop,
  9102. touches: getWebkitTouches()
  9103. });
  9104. }
  9105. };
  9106. /**
  9107. * Extend the Pointer prototype with methods for each event handler and more
  9108. */
  9109. extend(Pointer.prototype, {
  9110. onContainerPointerDown: function (e) {
  9111. translateMSPointer(e, 'onContainerTouchStart', 'touchstart', function (e) {
  9112. touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY, target: e.currentTarget };
  9113. });
  9114. },
  9115. onContainerPointerMove: function (e) {
  9116. translateMSPointer(e, 'onContainerTouchMove', 'touchmove', function (e) {
  9117. touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY };
  9118. if (!touches[e.pointerId].target) {
  9119. touches[e.pointerId].target = e.currentTarget;
  9120. }
  9121. });
  9122. },
  9123. onDocumentPointerUp: function (e) {
  9124. translateMSPointer(e, 'onDocumentTouchEnd', 'touchend', function (e) {
  9125. delete touches[e.pointerId];
  9126. });
  9127. },
  9128. /**
  9129. * Add or remove the MS Pointer specific events
  9130. */
  9131. batchMSEvents: function (fn) {
  9132. fn(this.chart.container, hasPointerEvent ? 'pointerdown' : 'MSPointerDown', this.onContainerPointerDown);
  9133. fn(this.chart.container, hasPointerEvent ? 'pointermove' : 'MSPointerMove', this.onContainerPointerMove);
  9134. fn(doc, hasPointerEvent ? 'pointerup' : 'MSPointerUp', this.onDocumentPointerUp);
  9135. }
  9136. });
  9137. // Disable default IE actions for pinch and such on chart element
  9138. wrap(Pointer.prototype, 'init', function (proceed, chart, options) {
  9139. proceed.call(this, chart, options);
  9140. if (this.hasZoom) { // #4014
  9141. css(chart.container, {
  9142. '-ms-touch-action': NONE,
  9143. 'touch-action': NONE
  9144. });
  9145. }
  9146. });
  9147. // Add IE specific touch events to chart
  9148. wrap(Pointer.prototype, 'setDOMEvents', function (proceed) {
  9149. proceed.apply(this);
  9150. if (this.hasZoom || this.followTouchMove) {
  9151. this.batchMSEvents(addEvent);
  9152. }
  9153. });
  9154. // Destroy MS events also
  9155. wrap(Pointer.prototype, 'destroy', function (proceed) {
  9156. this.batchMSEvents(removeEvent);
  9157. proceed.call(this);
  9158. });
  9159. }
  9160. /**
  9161. * The overview of the chart's series
  9162. */
  9163. var Legend = Highcharts.Legend = function (chart, options) {
  9164. this.init(chart, options);
  9165. };
  9166. Legend.prototype = {
  9167. /**
  9168. * Initialize the legend
  9169. */
  9170. init: function (chart, options) {
  9171. var legend = this,
  9172. itemStyle = options.itemStyle,
  9173. padding,
  9174. itemMarginTop = options.itemMarginTop || 0;
  9175. this.options = options;
  9176. if (!options.enabled) {
  9177. return;
  9178. }
  9179. legend.itemStyle = itemStyle;
  9180. legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle);
  9181. legend.itemMarginTop = itemMarginTop;
  9182. legend.padding = padding = pick(options.padding, 8);
  9183. legend.initialItemX = padding;
  9184. legend.initialItemY = padding - 5; // 5 is the number of pixels above the text
  9185. legend.maxItemWidth = 0;
  9186. legend.chart = chart;
  9187. legend.itemHeight = 0;
  9188. legend.symbolWidth = pick(options.symbolWidth, 16);
  9189. legend.pages = [];
  9190. // Render it
  9191. legend.render();
  9192. // move checkboxes
  9193. addEvent(legend.chart, 'endResize', function () {
  9194. legend.positionCheckboxes();
  9195. });
  9196. },
  9197. /**
  9198. * Set the colors for the legend item
  9199. * @param {Object} item A Series or Point instance
  9200. * @param {Object} visible Dimmed or colored
  9201. */
  9202. colorizeItem: function (item, visible) {
  9203. var legend = this,
  9204. options = legend.options,
  9205. legendItem = item.legendItem,
  9206. legendLine = item.legendLine,
  9207. legendSymbol = item.legendSymbol,
  9208. hiddenColor = legend.itemHiddenStyle.color,
  9209. textColor = visible ? options.itemStyle.color : hiddenColor,
  9210. symbolColor = visible ? (item.legendColor || item.color || '#CCC') : hiddenColor,
  9211. markerOptions = item.options && item.options.marker,
  9212. symbolAttr = { fill: symbolColor },
  9213. key,
  9214. val;
  9215. if (legendItem) {
  9216. legendItem.css({ fill: textColor, color: textColor }); // color for #1553, oldIE
  9217. }
  9218. if (legendLine) {
  9219. legendLine.attr({ stroke: symbolColor });
  9220. }
  9221. if (legendSymbol) {
  9222. // Apply marker options
  9223. if (markerOptions && legendSymbol.isMarker) { // #585
  9224. symbolAttr.stroke = symbolColor;
  9225. markerOptions = item.convertAttribs(markerOptions);
  9226. for (key in markerOptions) {
  9227. val = markerOptions[key];
  9228. if (val !== UNDEFINED) {
  9229. symbolAttr[key] = val;
  9230. }
  9231. }
  9232. }
  9233. legendSymbol.attr(symbolAttr);
  9234. }
  9235. },
  9236. /**
  9237. * Position the legend item
  9238. * @param {Object} item A Series or Point instance
  9239. */
  9240. positionItem: function (item) {
  9241. var legend = this,
  9242. options = legend.options,
  9243. symbolPadding = options.symbolPadding,
  9244. ltr = !options.rtl,
  9245. legendItemPos = item._legendItemPos,
  9246. itemX = legendItemPos[0],
  9247. itemY = legendItemPos[1],
  9248. checkbox = item.checkbox,
  9249. legendGroup = item.legendGroup;
  9250. if (legendGroup && legendGroup.element) {
  9251. legendGroup.translate(
  9252. ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4,
  9253. itemY
  9254. );
  9255. }
  9256. if (checkbox) {
  9257. checkbox.x = itemX;
  9258. checkbox.y = itemY;
  9259. }
  9260. },
  9261. /**
  9262. * Destroy a single legend item
  9263. * @param {Object} item The series or point
  9264. */
  9265. destroyItem: function (item) {
  9266. var checkbox = item.checkbox;
  9267. // destroy SVG elements
  9268. each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) {
  9269. if (item[key]) {
  9270. item[key] = item[key].destroy();
  9271. }
  9272. });
  9273. if (checkbox) {
  9274. discardElement(item.checkbox);
  9275. }
  9276. },
  9277. /**
  9278. * Destroys the legend.
  9279. */
  9280. destroy: function () {
  9281. var legend = this,
  9282. legendGroup = legend.group,
  9283. box = legend.box;
  9284. if (box) {
  9285. legend.box = box.destroy();
  9286. }
  9287. if (legendGroup) {
  9288. legend.group = legendGroup.destroy();
  9289. }
  9290. },
  9291. /**
  9292. * Position the checkboxes after the width is determined
  9293. */
  9294. positionCheckboxes: function (scrollOffset) {
  9295. var alignAttr = this.group.alignAttr,
  9296. translateY,
  9297. clipHeight = this.clipHeight || this.legendHeight;
  9298. if (alignAttr) {
  9299. translateY = alignAttr.translateY;
  9300. each(this.allItems, function (item) {
  9301. var checkbox = item.checkbox,
  9302. top;
  9303. if (checkbox) {
  9304. top = (translateY + checkbox.y + (scrollOffset || 0) + 3);
  9305. css(checkbox, {
  9306. left: (alignAttr.translateX + item.checkboxOffset + checkbox.x - 20) + PX,
  9307. top: top + PX,
  9308. display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE
  9309. });
  9310. }
  9311. });
  9312. }
  9313. },
  9314. /**
  9315. * Render the legend title on top of the legend
  9316. */
  9317. renderTitle: function () {
  9318. var options = this.options,
  9319. padding = this.padding,
  9320. titleOptions = options.title,
  9321. titleHeight = 0,
  9322. bBox;
  9323. if (titleOptions.text) {
  9324. if (!this.title) {
  9325. this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title')
  9326. .attr({ zIndex: 1 })
  9327. .css(titleOptions.style)
  9328. .add(this.group);
  9329. }
  9330. bBox = this.title.getBBox();
  9331. titleHeight = bBox.height;
  9332. this.offsetWidth = bBox.width; // #1717
  9333. this.contentGroup.attr({ translateY: titleHeight });
  9334. }
  9335. this.titleHeight = titleHeight;
  9336. },
  9337. /**
  9338. * Set the legend item text
  9339. */
  9340. setText: function (item) {
  9341. var options = this.options;
  9342. item.legendItem.attr({
  9343. text: options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item)
  9344. });
  9345. },
  9346. /**
  9347. * Render a single specific legend item
  9348. * @param {Object} item A series or point
  9349. */
  9350. renderItem: function (item) {
  9351. var legend = this,
  9352. chart = legend.chart,
  9353. renderer = chart.renderer,
  9354. options = legend.options,
  9355. horizontal = options.layout === 'horizontal',
  9356. symbolWidth = legend.symbolWidth,
  9357. symbolPadding = options.symbolPadding,
  9358. itemStyle = legend.itemStyle,
  9359. itemHiddenStyle = legend.itemHiddenStyle,
  9360. padding = legend.padding,
  9361. itemDistance = horizontal ? pick(options.itemDistance, 20) : 0,
  9362. ltr = !options.rtl,
  9363. itemHeight,
  9364. widthOption = options.width,
  9365. itemMarginBottom = options.itemMarginBottom || 0,
  9366. itemMarginTop = legend.itemMarginTop,
  9367. initialItemX = legend.initialItemX,
  9368. bBox,
  9369. itemWidth,
  9370. li = item.legendItem,
  9371. series = item.series && item.series.drawLegendSymbol ? item.series : item,
  9372. seriesOptions = series.options,
  9373. showCheckbox = legend.createCheckboxForItem && seriesOptions && seriesOptions.showCheckbox,
  9374. useHTML = options.useHTML;
  9375. if (!li) { // generate it once, later move it
  9376. // Generate the group box
  9377. // A group to hold the symbol and text. Text is to be appended in Legend class.
  9378. item.legendGroup = renderer.g('legend-item')
  9379. .attr({ zIndex: 1 })
  9380. .add(legend.scrollGroup);
  9381. // Generate the list item text and add it to the group
  9382. item.legendItem = li = renderer.text(
  9383. '',
  9384. ltr ? symbolWidth + symbolPadding : -symbolPadding,
  9385. legend.baseline || 0,
  9386. useHTML
  9387. )
  9388. .css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021)
  9389. .attr({
  9390. align: ltr ? 'left' : 'right',
  9391. zIndex: 2
  9392. })
  9393. .add(item.legendGroup);
  9394. // Get the baseline for the first item - the font size is equal for all
  9395. if (!legend.baseline) {
  9396. legend.fontMetrics = renderer.fontMetrics(itemStyle.fontSize, li);
  9397. legend.baseline = legend.fontMetrics.f + 3 + itemMarginTop;
  9398. li.attr('y', legend.baseline);
  9399. }
  9400. // Draw the legend symbol inside the group box
  9401. series.drawLegendSymbol(legend, item);
  9402. if (legend.setItemEvents) {
  9403. legend.setItemEvents(item, li, useHTML, itemStyle, itemHiddenStyle);
  9404. }
  9405. // Colorize the items
  9406. legend.colorizeItem(item, item.visible);
  9407. // add the HTML checkbox on top
  9408. if (showCheckbox) {
  9409. legend.createCheckboxForItem(item);
  9410. }
  9411. }
  9412. // Always update the text
  9413. legend.setText(item);
  9414. // calculate the positions for the next line
  9415. bBox = li.getBBox();
  9416. itemWidth = item.checkboxOffset =
  9417. options.itemWidth ||
  9418. item.legendItemWidth ||
  9419. symbolWidth + symbolPadding + bBox.width + itemDistance + (showCheckbox ? 20 : 0);
  9420. legend.itemHeight = itemHeight = mathRound(item.legendItemHeight || bBox.height);
  9421. // if the item exceeds the width, start a new line
  9422. if (horizontal && legend.itemX - initialItemX + itemWidth >
  9423. (widthOption || (chart.chartWidth - 2 * padding - initialItemX - options.x))) {
  9424. legend.itemX = initialItemX;
  9425. legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom;
  9426. legend.lastLineHeight = 0; // reset for next line (#915, #3976)
  9427. }
  9428. // If the item exceeds the height, start a new column
  9429. /*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) {
  9430. legend.itemY = legend.initialItemY;
  9431. legend.itemX += legend.maxItemWidth;
  9432. legend.maxItemWidth = 0;
  9433. }*/
  9434. // Set the edge positions
  9435. legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth);
  9436. legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom;
  9437. legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915
  9438. // cache the position of the newly generated or reordered items
  9439. item._legendItemPos = [legend.itemX, legend.itemY];
  9440. // advance
  9441. if (horizontal) {
  9442. legend.itemX += itemWidth;
  9443. } else {
  9444. legend.itemY += itemMarginTop + itemHeight + itemMarginBottom;
  9445. legend.lastLineHeight = itemHeight;
  9446. }
  9447. // the width of the widest item
  9448. legend.offsetWidth = widthOption || mathMax(
  9449. (horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding,
  9450. legend.offsetWidth
  9451. );
  9452. },
  9453. /**
  9454. * Get all items, which is one item per series for normal series and one item per point
  9455. * for pie series.
  9456. */
  9457. getAllItems: function () {
  9458. var allItems = [];
  9459. each(this.chart.series, function (series) {
  9460. var seriesOptions = series.options;
  9461. // Handle showInLegend. If the series is linked to another series, defaults to false.
  9462. if (!pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? UNDEFINED : false, true)) {
  9463. return;
  9464. }
  9465. // use points or series for the legend item depending on legendType
  9466. allItems = allItems.concat(
  9467. series.legendItems ||
  9468. (seriesOptions.legendType === 'point' ?
  9469. series.data :
  9470. series)
  9471. );
  9472. });
  9473. return allItems;
  9474. },
  9475. /**
  9476. * Adjust the chart margins by reserving space for the legend on only one side
  9477. * of the chart. If the position is set to a corner, top or bottom is reserved
  9478. * for horizontal legends and left or right for vertical ones.
  9479. */
  9480. adjustMargins: function (margin, spacing) {
  9481. var chart = this.chart,
  9482. options = this.options,
  9483. // Use the first letter of each alignment option in order to detect the side
  9484. alignment = options.align.charAt(0) + options.verticalAlign.charAt(0) + options.layout.charAt(0); // #4189 - use charAt(x) notation instead of [x] for IE7
  9485. if (this.display && !options.floating) {
  9486. each([
  9487. /(lth|ct|rth)/,
  9488. /(rtv|rm|rbv)/,
  9489. /(rbh|cb|lbh)/,
  9490. /(lbv|lm|ltv)/
  9491. ], function (alignments, side) {
  9492. if (alignments.test(alignment) && !defined(margin[side])) {
  9493. // Now we have detected on which side of the chart we should reserve space for the legend
  9494. chart[marginNames[side]] = mathMax(
  9495. chart[marginNames[side]],
  9496. chart.legend[(side + 1) % 2 ? 'legendHeight' : 'legendWidth'] +
  9497. [1, -1, -1, 1][side] * options[(side % 2) ? 'x' : 'y'] +
  9498. pick(options.margin, 12) +
  9499. spacing[side]
  9500. );
  9501. }
  9502. });
  9503. }
  9504. },
  9505. /**
  9506. * Render the legend. This method can be called both before and after
  9507. * chart.render. If called after, it will only rearrange items instead
  9508. * of creating new ones.
  9509. */
  9510. render: function () {
  9511. var legend = this,
  9512. chart = legend.chart,
  9513. renderer = chart.renderer,
  9514. legendGroup = legend.group,
  9515. allItems,
  9516. display,
  9517. legendWidth,
  9518. legendHeight,
  9519. box = legend.box,
  9520. options = legend.options,
  9521. padding = legend.padding,
  9522. legendBorderWidth = options.borderWidth,
  9523. legendBackgroundColor = options.backgroundColor;
  9524. legend.itemX = legend.initialItemX;
  9525. legend.itemY = legend.initialItemY;
  9526. legend.offsetWidth = 0;
  9527. legend.lastItemY = 0;
  9528. if (!legendGroup) {
  9529. legend.group = legendGroup = renderer.g('legend')
  9530. .attr({ zIndex: 7 })
  9531. .add();
  9532. legend.contentGroup = renderer.g()
  9533. .attr({ zIndex: 1 }) // above background
  9534. .add(legendGroup);
  9535. legend.scrollGroup = renderer.g()
  9536. .add(legend.contentGroup);
  9537. }
  9538. legend.renderTitle();
  9539. // add each series or point
  9540. allItems = legend.getAllItems();
  9541. // sort by legendIndex
  9542. stableSort(allItems, function (a, b) {
  9543. return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0);
  9544. });
  9545. // reversed legend
  9546. if (options.reversed) {
  9547. allItems.reverse();
  9548. }
  9549. legend.allItems = allItems;
  9550. legend.display = display = !!allItems.length;
  9551. // render the items
  9552. legend.lastLineHeight = 0;
  9553. each(allItems, function (item) {
  9554. legend.renderItem(item);
  9555. });
  9556. // Get the box
  9557. legendWidth = (options.width || legend.offsetWidth) + padding;
  9558. legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight;
  9559. legendHeight = legend.handleOverflow(legendHeight);
  9560. legendHeight += padding;
  9561. // Draw the border and/or background
  9562. if (legendBorderWidth || legendBackgroundColor) {
  9563. if (!box) {
  9564. legend.box = box = renderer.rect(
  9565. 0,
  9566. 0,
  9567. legendWidth,
  9568. legendHeight,
  9569. options.borderRadius,
  9570. legendBorderWidth || 0
  9571. ).attr({
  9572. stroke: options.borderColor,
  9573. 'stroke-width': legendBorderWidth || 0,
  9574. fill: legendBackgroundColor || NONE
  9575. })
  9576. .add(legendGroup)
  9577. .shadow(options.shadow);
  9578. box.isNew = true;
  9579. } else if (legendWidth > 0 && legendHeight > 0) {
  9580. box[box.isNew ? 'attr' : 'animate'](
  9581. box.crisp({ width: legendWidth, height: legendHeight })
  9582. );
  9583. box.isNew = false;
  9584. }
  9585. // hide the border if no items
  9586. box[display ? 'show' : 'hide']();
  9587. }
  9588. legend.legendWidth = legendWidth;
  9589. legend.legendHeight = legendHeight;
  9590. // Now that the legend width and height are established, put the items in the
  9591. // final position
  9592. each(allItems, function (item) {
  9593. legend.positionItem(item);
  9594. });
  9595. // 1.x compatibility: positioning based on style
  9596. /*var props = ['left', 'right', 'top', 'bottom'],
  9597. prop,
  9598. i = 4;
  9599. while (i--) {
  9600. prop = props[i];
  9601. if (options.style[prop] && options.style[prop] !== 'auto') {
  9602. options[i < 2 ? 'align' : 'verticalAlign'] = prop;
  9603. options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1);
  9604. }
  9605. }*/
  9606. if (display) {
  9607. legendGroup.align(extend({
  9608. width: legendWidth,
  9609. height: legendHeight
  9610. }, options), true, 'spacingBox');
  9611. }
  9612. if (!chart.isResizing) {
  9613. this.positionCheckboxes();
  9614. }
  9615. },
  9616. /**
  9617. * Set up the overflow handling by adding navigation with up and down arrows below the
  9618. * legend.
  9619. */
  9620. handleOverflow: function (legendHeight) {
  9621. var legend = this,
  9622. chart = this.chart,
  9623. renderer = chart.renderer,
  9624. options = this.options,
  9625. optionsY = options.y,
  9626. alignTop = options.verticalAlign === 'top',
  9627. spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding,
  9628. maxHeight = options.maxHeight,
  9629. clipHeight,
  9630. clipRect = this.clipRect,
  9631. navOptions = options.navigation,
  9632. animation = pick(navOptions.animation, true),
  9633. arrowSize = navOptions.arrowSize || 12,
  9634. nav = this.nav,
  9635. pages = this.pages,
  9636. padding = this.padding,
  9637. lastY,
  9638. allItems = this.allItems,
  9639. clipToHeight = function (height) {
  9640. clipRect.attr({
  9641. height: height
  9642. });
  9643. // useHTML
  9644. if (legend.contentGroup.div) {
  9645. legend.contentGroup.div.style.clip = 'rect(' + padding + 'px,9999px,' + (padding + height) + 'px,0)';
  9646. }
  9647. };
  9648. // Adjust the height
  9649. if (options.layout === 'horizontal') {
  9650. spaceHeight /= 2;
  9651. }
  9652. if (maxHeight) {
  9653. spaceHeight = mathMin(spaceHeight, maxHeight);
  9654. }
  9655. // Reset the legend height and adjust the clipping rectangle
  9656. pages.length = 0;
  9657. if (legendHeight > spaceHeight) {
  9658. this.clipHeight = clipHeight = mathMax(spaceHeight - 20 - this.titleHeight - padding, 0);
  9659. this.currentPage = pick(this.currentPage, 1);
  9660. this.fullHeight = legendHeight;
  9661. // Fill pages with Y positions so that the top of each a legend item defines
  9662. // the scroll top for each page (#2098)
  9663. each(allItems, function (item, i) {
  9664. var y = item._legendItemPos[1],
  9665. h = mathRound(item.legendItem.getBBox().height),
  9666. len = pages.length;
  9667. if (!len || (y - pages[len - 1] > clipHeight && (lastY || y) !== pages[len - 1])) {
  9668. pages.push(lastY || y);
  9669. len++;
  9670. }
  9671. if (i === allItems.length - 1 && y + h - pages[len - 1] > clipHeight) {
  9672. pages.push(y);
  9673. }
  9674. if (y !== lastY) {
  9675. lastY = y;
  9676. }
  9677. });
  9678. // Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787)
  9679. if (!clipRect) {
  9680. clipRect = legend.clipRect = renderer.clipRect(0, padding, 9999, 0);
  9681. legend.contentGroup.clip(clipRect);
  9682. }
  9683. clipToHeight(clipHeight);
  9684. // Add navigation elements
  9685. if (!nav) {
  9686. this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group);
  9687. this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize)
  9688. .on('click', function () {
  9689. legend.scroll(-1, animation);
  9690. })
  9691. .add(nav);
  9692. this.pager = renderer.text('', 15, 10)
  9693. .css(navOptions.style)
  9694. .add(nav);
  9695. this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize)
  9696. .on('click', function () {
  9697. legend.scroll(1, animation);
  9698. })
  9699. .add(nav);
  9700. }
  9701. // Set initial position
  9702. legend.scroll(0);
  9703. legendHeight = spaceHeight;
  9704. } else if (nav) {
  9705. clipToHeight(chart.chartHeight);
  9706. nav.hide();
  9707. this.scrollGroup.attr({
  9708. translateY: 1
  9709. });
  9710. this.clipHeight = 0; // #1379
  9711. }
  9712. return legendHeight;
  9713. },
  9714. /**
  9715. * Scroll the legend by a number of pages
  9716. * @param {Object} scrollBy
  9717. * @param {Object} animation
  9718. */
  9719. scroll: function (scrollBy, animation) {
  9720. var pages = this.pages,
  9721. pageCount = pages.length,
  9722. currentPage = this.currentPage + scrollBy,
  9723. clipHeight = this.clipHeight,
  9724. navOptions = this.options.navigation,
  9725. activeColor = navOptions.activeColor,
  9726. inactiveColor = navOptions.inactiveColor,
  9727. pager = this.pager,
  9728. padding = this.padding,
  9729. scrollOffset;
  9730. // When resizing while looking at the last page
  9731. if (currentPage > pageCount) {
  9732. currentPage = pageCount;
  9733. }
  9734. if (currentPage > 0) {
  9735. if (animation !== UNDEFINED) {
  9736. setAnimation(animation, this.chart);
  9737. }
  9738. this.nav.attr({
  9739. translateX: padding,
  9740. translateY: clipHeight + this.padding + 7 + this.titleHeight,
  9741. visibility: VISIBLE
  9742. });
  9743. this.up.attr({
  9744. fill: currentPage === 1 ? inactiveColor : activeColor
  9745. })
  9746. .css({
  9747. cursor: currentPage === 1 ? 'default' : 'pointer'
  9748. });
  9749. pager.attr({
  9750. text: currentPage + '/' + pageCount
  9751. });
  9752. this.down.attr({
  9753. x: 18 + this.pager.getBBox().width, // adjust to text width
  9754. fill: currentPage === pageCount ? inactiveColor : activeColor
  9755. })
  9756. .css({
  9757. cursor: currentPage === pageCount ? 'default' : 'pointer'
  9758. });
  9759. scrollOffset = -pages[currentPage - 1] + this.initialItemY;
  9760. this.scrollGroup.animate({
  9761. translateY: scrollOffset
  9762. });
  9763. this.currentPage = currentPage;
  9764. this.positionCheckboxes(scrollOffset);
  9765. }
  9766. }
  9767. };
  9768. /*
  9769. * LegendSymbolMixin
  9770. */
  9771. var LegendSymbolMixin = Highcharts.LegendSymbolMixin = {
  9772. /**
  9773. * Get the series' symbol in the legend
  9774. *
  9775. * @param {Object} legend The legend object
  9776. * @param {Object} item The series (this) or point
  9777. */
  9778. drawRectangle: function (legend, item) {
  9779. var symbolHeight = legend.options.symbolHeight || legend.fontMetrics.f;
  9780. item.legendSymbol = this.chart.renderer.rect(
  9781. 0,
  9782. legend.baseline - symbolHeight + 1, // #3988
  9783. legend.symbolWidth,
  9784. symbolHeight,
  9785. legend.options.symbolRadius || 0
  9786. ).attr({
  9787. zIndex: 3
  9788. }).add(item.legendGroup);
  9789. },
  9790. /**
  9791. * Get the series' symbol in the legend. This method should be overridable to create custom
  9792. * symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols.
  9793. *
  9794. * @param {Object} legend The legend object
  9795. */
  9796. drawLineMarker: function (legend) {
  9797. var options = this.options,
  9798. markerOptions = options.marker,
  9799. radius,
  9800. legendSymbol,
  9801. symbolWidth = legend.symbolWidth,
  9802. renderer = this.chart.renderer,
  9803. legendItemGroup = this.legendGroup,
  9804. verticalCenter = legend.baseline - mathRound(legend.fontMetrics.b * 0.3),
  9805. attr;
  9806. // Draw the line
  9807. if (options.lineWidth) {
  9808. attr = {
  9809. 'stroke-width': options.lineWidth
  9810. };
  9811. if (options.dashStyle) {
  9812. attr.dashstyle = options.dashStyle;
  9813. }
  9814. this.legendLine = renderer.path([
  9815. M,
  9816. 0,
  9817. verticalCenter,
  9818. L,
  9819. symbolWidth,
  9820. verticalCenter
  9821. ])
  9822. .attr(attr)
  9823. .add(legendItemGroup);
  9824. }
  9825. // Draw the marker
  9826. if (markerOptions && markerOptions.enabled !== false) {
  9827. radius = markerOptions.radius;
  9828. this.legendSymbol = legendSymbol = renderer.symbol(
  9829. this.symbol,
  9830. (symbolWidth / 2) - radius,
  9831. verticalCenter - radius,
  9832. 2 * radius,
  9833. 2 * radius
  9834. )
  9835. .add(legendItemGroup);
  9836. legendSymbol.isMarker = true;
  9837. }
  9838. }
  9839. };
  9840. // Workaround for #2030, horizontal legend items not displaying in IE11 Preview,
  9841. // and for #2580, a similar drawing flaw in Firefox 26.
  9842. // TODO: Explore if there's a general cause for this. The problem may be related
  9843. // to nested group elements, as the legend item texts are within 4 group elements.
  9844. if (/Trident\/7\.0/.test(userAgent) || isFirefox) {
  9845. wrap(Legend.prototype, 'positionItem', function (proceed, item) {
  9846. var legend = this,
  9847. runPositionItem = function () { // If chart destroyed in sync, this is undefined (#2030)
  9848. if (item._legendItemPos) {
  9849. proceed.call(legend, item);
  9850. }
  9851. };
  9852. // Do it now, for export and to get checkbox placement
  9853. runPositionItem();
  9854. // Do it after to work around the core issue
  9855. setTimeout(runPositionItem);
  9856. });
  9857. }
  9858. /**
  9859. * The chart class
  9860. * @param {Object} options
  9861. * @param {Function} callback Function to run when the chart has loaded
  9862. */
  9863. var Chart = Highcharts.Chart = function () {
  9864. this.init.apply(this, arguments);
  9865. };
  9866. Chart.prototype = {
  9867. /**
  9868. * Hook for modules
  9869. */
  9870. callbacks: [],
  9871. /**
  9872. * Initialize the chart
  9873. */
  9874. init: function (userOptions, callback) {
  9875. // Handle regular options
  9876. var options,
  9877. seriesOptions = userOptions.series; // skip merging data points to increase performance
  9878. userOptions.series = null;
  9879. options = merge(defaultOptions, userOptions); // do the merge
  9880. options.series = userOptions.series = seriesOptions; // set back the series data
  9881. this.userOptions = userOptions;
  9882. var optionsChart = options.chart;
  9883. // Create margin & spacing array
  9884. this.margin = this.splashArray('margin', optionsChart);
  9885. this.spacing = this.splashArray('spacing', optionsChart);
  9886. var chartEvents = optionsChart.events;
  9887. //this.runChartClick = chartEvents && !!chartEvents.click;
  9888. this.bounds = { h: {}, v: {} }; // Pixel data bounds for touch zoom
  9889. this.callback = callback;
  9890. this.isResizing = 0;
  9891. this.options = options;
  9892. //chartTitleOptions = UNDEFINED;
  9893. //chartSubtitleOptions = UNDEFINED;
  9894. this.axes = [];
  9895. this.series = [];
  9896. this.hasCartesianSeries = optionsChart.showAxes;
  9897. //this.axisOffset = UNDEFINED;
  9898. //this.maxTicks = UNDEFINED; // handle the greatest amount of ticks on grouped axes
  9899. //this.inverted = UNDEFINED;
  9900. //this.loadingShown = UNDEFINED;
  9901. //this.container = UNDEFINED;
  9902. //this.chartWidth = UNDEFINED;
  9903. //this.chartHeight = UNDEFINED;
  9904. //this.marginRight = UNDEFINED;
  9905. //this.marginBottom = UNDEFINED;
  9906. //this.containerWidth = UNDEFINED;
  9907. //this.containerHeight = UNDEFINED;
  9908. //this.oldChartWidth = UNDEFINED;
  9909. //this.oldChartHeight = UNDEFINED;
  9910. //this.renderTo = UNDEFINED;
  9911. //this.renderToClone = UNDEFINED;
  9912. //this.spacingBox = UNDEFINED
  9913. //this.legend = UNDEFINED;
  9914. // Elements
  9915. //this.chartBackground = UNDEFINED;
  9916. //this.plotBackground = UNDEFINED;
  9917. //this.plotBGImage = UNDEFINED;
  9918. //this.plotBorder = UNDEFINED;
  9919. //this.loadingDiv = UNDEFINED;
  9920. //this.loadingSpan = UNDEFINED;
  9921. var chart = this,
  9922. eventType;
  9923. // Add the chart to the global lookup
  9924. chart.index = charts.length;
  9925. charts.push(chart);
  9926. chartCount++;
  9927. // Set up auto resize
  9928. if (optionsChart.reflow !== false) {
  9929. addEvent(chart, 'load', function () {
  9930. chart.initReflow();
  9931. });
  9932. }
  9933. // Chart event handlers
  9934. if (chartEvents) {
  9935. for (eventType in chartEvents) {
  9936. addEvent(chart, eventType, chartEvents[eventType]);
  9937. }
  9938. }
  9939. chart.xAxis = [];
  9940. chart.yAxis = [];
  9941. // Expose methods and variables
  9942. chart.animation = useCanVG ? false : pick(optionsChart.animation, true);
  9943. chart.pointCount = chart.colorCounter = chart.symbolCounter = 0;
  9944. chart.firstRender();
  9945. },
  9946. /**
  9947. * Initialize an individual series, called internally before render time
  9948. */
  9949. initSeries: function (options) {
  9950. var chart = this,
  9951. optionsChart = chart.options.chart,
  9952. type = options.type || optionsChart.type || optionsChart.defaultSeriesType,
  9953. series,
  9954. constr = seriesTypes[type];
  9955. // No such series type
  9956. if (!constr) {
  9957. error(17, true);
  9958. }
  9959. series = new constr();
  9960. series.init(this, options);
  9961. return series;
  9962. },
  9963. /**
  9964. * Check whether a given point is within the plot area
  9965. *
  9966. * @param {Number} plotX Pixel x relative to the plot area
  9967. * @param {Number} plotY Pixel y relative to the plot area
  9968. * @param {Boolean} inverted Whether the chart is inverted
  9969. */
  9970. isInsidePlot: function (plotX, plotY, inverted) {
  9971. var x = inverted ? plotY : plotX,
  9972. y = inverted ? plotX : plotY;
  9973. return x >= 0 &&
  9974. x <= this.plotWidth &&
  9975. y >= 0 &&
  9976. y <= this.plotHeight;
  9977. },
  9978. /**
  9979. * Redraw legend, axes or series based on updated data
  9980. *
  9981. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  9982. * configuration
  9983. */
  9984. redraw: function (animation) {
  9985. var chart = this,
  9986. axes = chart.axes,
  9987. series = chart.series,
  9988. pointer = chart.pointer,
  9989. legend = chart.legend,
  9990. redrawLegend = chart.isDirtyLegend,
  9991. hasStackedSeries,
  9992. hasDirtyStacks,
  9993. hasCartesianSeries = chart.hasCartesianSeries,
  9994. isDirtyBox = chart.isDirtyBox, // todo: check if it has actually changed?
  9995. seriesLength = series.length,
  9996. i = seriesLength,
  9997. serie,
  9998. renderer = chart.renderer,
  9999. isHiddenChart = renderer.isHidden(),
  10000. afterRedraw = [];
  10001. setAnimation(animation, chart);
  10002. if (isHiddenChart) {
  10003. chart.cloneRenderTo();
  10004. }
  10005. // Adjust title layout (reflow multiline text)
  10006. chart.layOutTitles();
  10007. // link stacked series
  10008. while (i--) {
  10009. serie = series[i];
  10010. if (serie.options.stacking) {
  10011. hasStackedSeries = true;
  10012. if (serie.isDirty) {
  10013. hasDirtyStacks = true;
  10014. break;
  10015. }
  10016. }
  10017. }
  10018. if (hasDirtyStacks) { // mark others as dirty
  10019. i = seriesLength;
  10020. while (i--) {
  10021. serie = series[i];
  10022. if (serie.options.stacking) {
  10023. serie.isDirty = true;
  10024. }
  10025. }
  10026. }
  10027. // Handle updated data in the series
  10028. each(series, function (serie) {
  10029. if (serie.isDirty) {
  10030. if (serie.options.legendType === 'point') {
  10031. if (serie.updateTotals) {
  10032. serie.updateTotals();
  10033. }
  10034. redrawLegend = true;
  10035. }
  10036. }
  10037. });
  10038. // handle added or removed series
  10039. if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed
  10040. // draw legend graphics
  10041. legend.render();
  10042. chart.isDirtyLegend = false;
  10043. }
  10044. // reset stacks
  10045. if (hasStackedSeries) {
  10046. chart.getStacks();
  10047. }
  10048. if (hasCartesianSeries) {
  10049. if (!chart.isResizing) {
  10050. // reset maxTicks
  10051. chart.maxTicks = null;
  10052. // set axes scales
  10053. each(axes, function (axis) {
  10054. axis.setScale();
  10055. });
  10056. }
  10057. }
  10058. chart.getMargins(); // #3098
  10059. if (hasCartesianSeries) {
  10060. // If one axis is dirty, all axes must be redrawn (#792, #2169)
  10061. each(axes, function (axis) {
  10062. if (axis.isDirty) {
  10063. isDirtyBox = true;
  10064. }
  10065. });
  10066. // redraw axes
  10067. each(axes, function (axis) {
  10068. // Fire 'afterSetExtremes' only if extremes are set
  10069. var key = axis.min + ',' + axis.max;
  10070. if (axis.extKey !== key) { // #821, #4452
  10071. axis.extKey = key;
  10072. afterRedraw.push(function () { // prevent a recursive call to chart.redraw() (#1119)
  10073. fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751
  10074. delete axis.eventArgs;
  10075. });
  10076. }
  10077. if (isDirtyBox || hasStackedSeries) {
  10078. axis.redraw();
  10079. }
  10080. });
  10081. }
  10082. // the plot areas size has changed
  10083. if (isDirtyBox) {
  10084. chart.drawChartBox();
  10085. }
  10086. // redraw affected series
  10087. each(series, function (serie) {
  10088. if (serie.isDirty && serie.visible &&
  10089. (!serie.isCartesian || serie.xAxis)) { // issue #153
  10090. serie.redraw();
  10091. }
  10092. });
  10093. // move tooltip or reset
  10094. if (pointer) {
  10095. pointer.reset(true);
  10096. }
  10097. // redraw if canvas
  10098. renderer.draw();
  10099. // fire the event
  10100. fireEvent(chart, 'redraw'); // jQuery breaks this when calling it from addEvent. Overwrites chart.redraw
  10101. if (isHiddenChart) {
  10102. chart.cloneRenderTo(true);
  10103. }
  10104. // Fire callbacks that are put on hold until after the redraw
  10105. each(afterRedraw, function (callback) {
  10106. callback.call();
  10107. });
  10108. },
  10109. /**
  10110. * Get an axis, series or point object by id.
  10111. * @param id {String} The id as given in the configuration options
  10112. */
  10113. get: function (id) {
  10114. var chart = this,
  10115. axes = chart.axes,
  10116. series = chart.series;
  10117. var i,
  10118. j,
  10119. points;
  10120. // search axes
  10121. for (i = 0; i < axes.length; i++) {
  10122. if (axes[i].options.id === id) {
  10123. return axes[i];
  10124. }
  10125. }
  10126. // search series
  10127. for (i = 0; i < series.length; i++) {
  10128. if (series[i].options.id === id) {
  10129. return series[i];
  10130. }
  10131. }
  10132. // search points
  10133. for (i = 0; i < series.length; i++) {
  10134. points = series[i].points || [];
  10135. for (j = 0; j < points.length; j++) {
  10136. if (points[j].id === id) {
  10137. return points[j];
  10138. }
  10139. }
  10140. }
  10141. return null;
  10142. },
  10143. /**
  10144. * Create the Axis instances based on the config options
  10145. */
  10146. getAxes: function () {
  10147. var chart = this,
  10148. options = this.options,
  10149. xAxisOptions = options.xAxis = splat(options.xAxis || {}),
  10150. yAxisOptions = options.yAxis = splat(options.yAxis || {}),
  10151. optionsArray,
  10152. axis;
  10153. // make sure the options are arrays and add some members
  10154. each(xAxisOptions, function (axis, i) {
  10155. axis.index = i;
  10156. axis.isX = true;
  10157. });
  10158. each(yAxisOptions, function (axis, i) {
  10159. axis.index = i;
  10160. });
  10161. // concatenate all axis options into one array
  10162. optionsArray = xAxisOptions.concat(yAxisOptions);
  10163. each(optionsArray, function (axisOptions) {
  10164. axis = new Axis(chart, axisOptions);
  10165. });
  10166. },
  10167. /**
  10168. * Get the currently selected points from all series
  10169. */
  10170. getSelectedPoints: function () {
  10171. var points = [];
  10172. each(this.series, function (serie) {
  10173. points = points.concat(grep(serie.points || [], function (point) {
  10174. return point.selected;
  10175. }));
  10176. });
  10177. return points;
  10178. },
  10179. /**
  10180. * Get the currently selected series
  10181. */
  10182. getSelectedSeries: function () {
  10183. return grep(this.series, function (serie) {
  10184. return serie.selected;
  10185. });
  10186. },
  10187. /**
  10188. * Show the title and subtitle of the chart
  10189. *
  10190. * @param titleOptions {Object} New title options
  10191. * @param subtitleOptions {Object} New subtitle options
  10192. *
  10193. */
  10194. setTitle: function (titleOptions, subtitleOptions, redraw) {
  10195. var chart = this,
  10196. options = chart.options,
  10197. chartTitleOptions,
  10198. chartSubtitleOptions;
  10199. chartTitleOptions = options.title = merge(options.title, titleOptions);
  10200. chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions);
  10201. // add title and subtitle
  10202. each([
  10203. ['title', titleOptions, chartTitleOptions],
  10204. ['subtitle', subtitleOptions, chartSubtitleOptions]
  10205. ], function (arr) {
  10206. var name = arr[0],
  10207. title = chart[name],
  10208. titleOptions = arr[1],
  10209. chartTitleOptions = arr[2];
  10210. if (title && titleOptions) {
  10211. chart[name] = title = title.destroy(); // remove old
  10212. }
  10213. if (chartTitleOptions && chartTitleOptions.text && !title) {
  10214. chart[name] = chart.renderer.text(
  10215. chartTitleOptions.text,
  10216. 0,
  10217. 0,
  10218. chartTitleOptions.useHTML
  10219. )
  10220. .attr({
  10221. align: chartTitleOptions.align,
  10222. 'class': PREFIX + name,
  10223. zIndex: chartTitleOptions.zIndex || 4
  10224. })
  10225. .css(chartTitleOptions.style)
  10226. .add();
  10227. }
  10228. });
  10229. chart.layOutTitles(redraw);
  10230. },
  10231. /**
  10232. * Lay out the chart titles and cache the full offset height for use in getMargins
  10233. */
  10234. layOutTitles: function (redraw) {
  10235. var titleOffset = 0,
  10236. title = this.title,
  10237. subtitle = this.subtitle,
  10238. options = this.options,
  10239. titleOptions = options.title,
  10240. subtitleOptions = options.subtitle,
  10241. requiresDirtyBox,
  10242. renderer = this.renderer,
  10243. autoWidth = this.spacingBox.width - 44; // 44 makes room for default context button
  10244. if (title) {
  10245. title
  10246. .css({ width: (titleOptions.width || autoWidth) + PX })
  10247. .align(extend({
  10248. y: renderer.fontMetrics(titleOptions.style.fontSize, title).b - 3
  10249. }, titleOptions), false, 'spacingBox');
  10250. if (!titleOptions.floating && !titleOptions.verticalAlign) {
  10251. titleOffset = title.getBBox().height;
  10252. }
  10253. }
  10254. if (subtitle) {
  10255. subtitle
  10256. .css({ width: (subtitleOptions.width || autoWidth) + PX })
  10257. .align(extend({
  10258. y: titleOffset + (titleOptions.margin - 13) + renderer.fontMetrics(subtitleOptions.style.fontSize, title).b
  10259. }, subtitleOptions), false, 'spacingBox');
  10260. if (!subtitleOptions.floating && !subtitleOptions.verticalAlign) {
  10261. titleOffset = mathCeil(titleOffset + subtitle.getBBox().height);
  10262. }
  10263. }
  10264. requiresDirtyBox = this.titleOffset !== titleOffset;
  10265. this.titleOffset = titleOffset; // used in getMargins
  10266. if (!this.isDirtyBox && requiresDirtyBox) {
  10267. this.isDirtyBox = requiresDirtyBox;
  10268. // Redraw if necessary (#2719, #2744)
  10269. if (this.hasRendered && pick(redraw, true) && this.isDirtyBox) {
  10270. this.redraw();
  10271. }
  10272. }
  10273. },
  10274. /**
  10275. * Get chart width and height according to options and container size
  10276. */
  10277. getChartSize: function () {
  10278. var chart = this,
  10279. optionsChart = chart.options.chart,
  10280. widthOption = optionsChart.width,
  10281. heightOption = optionsChart.height,
  10282. renderTo = chart.renderToClone || chart.renderTo;
  10283. // get inner width and height from jQuery (#824)
  10284. if (!defined(widthOption)) {
  10285. chart.containerWidth = adapterRun(renderTo, 'width');
  10286. }
  10287. if (!defined(heightOption)) {
  10288. chart.containerHeight = adapterRun(renderTo, 'height');
  10289. }
  10290. chart.chartWidth = mathMax(0, widthOption || chart.containerWidth || 600); // #1393, 1460
  10291. chart.chartHeight = mathMax(0, pick(heightOption,
  10292. // the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7:
  10293. chart.containerHeight > 19 ? chart.containerHeight : 400));
  10294. },
  10295. /**
  10296. * Create a clone of the chart's renderTo div and place it outside the viewport to allow
  10297. * size computation on chart.render and chart.redraw
  10298. */
  10299. cloneRenderTo: function (revert) {
  10300. var clone = this.renderToClone,
  10301. container = this.container;
  10302. // Destroy the clone and bring the container back to the real renderTo div
  10303. if (revert) {
  10304. if (clone) {
  10305. this.renderTo.appendChild(container);
  10306. discardElement(clone);
  10307. delete this.renderToClone;
  10308. }
  10309. // Set up the clone
  10310. } else {
  10311. if (container && container.parentNode === this.renderTo) {
  10312. this.renderTo.removeChild(container); // do not clone this
  10313. }
  10314. this.renderToClone = clone = this.renderTo.cloneNode(0);
  10315. css(clone, {
  10316. position: ABSOLUTE,
  10317. top: '-9999px',
  10318. display: 'block' // #833
  10319. });
  10320. if (clone.style.setProperty) { // #2631
  10321. clone.style.setProperty('display', 'block', 'important');
  10322. }
  10323. doc.body.appendChild(clone);
  10324. if (container) {
  10325. clone.appendChild(container);
  10326. }
  10327. }
  10328. },
  10329. /**
  10330. * Get the containing element, determine the size and create the inner container
  10331. * div to hold the chart
  10332. */
  10333. getContainer: function () {
  10334. var chart = this,
  10335. container,
  10336. options = chart.options,
  10337. optionsChart = options.chart,
  10338. chartWidth,
  10339. chartHeight,
  10340. renderTo,
  10341. indexAttrName = 'data-highcharts-chart',
  10342. oldChartIndex,
  10343. Ren,
  10344. containerId;
  10345. chart.renderTo = renderTo = optionsChart.renderTo;
  10346. containerId = PREFIX + idCounter++;
  10347. if (isString(renderTo)) {
  10348. chart.renderTo = renderTo = doc.getElementById(renderTo);
  10349. }
  10350. // Display an error if the renderTo is wrong
  10351. if (!renderTo) {
  10352. error(13, true);
  10353. }
  10354. // If the container already holds a chart, destroy it. The check for hasRendered is there
  10355. // because web pages that are saved to disk from the browser, will preserve the data-highcharts-chart
  10356. // attribute and the SVG contents, but not an interactive chart. So in this case,
  10357. // charts[oldChartIndex] will point to the wrong chart if any (#2609).
  10358. oldChartIndex = pInt(attr(renderTo, indexAttrName));
  10359. if (!isNaN(oldChartIndex) && charts[oldChartIndex] && charts[oldChartIndex].hasRendered) {
  10360. charts[oldChartIndex].destroy();
  10361. }
  10362. // Make a reference to the chart from the div
  10363. attr(renderTo, indexAttrName, chart.index);
  10364. // remove previous chart
  10365. renderTo.innerHTML = '';
  10366. // If the container doesn't have an offsetWidth, it has or is a child of a node
  10367. // that has display:none. We need to temporarily move it out to a visible
  10368. // state to determine the size, else the legend and tooltips won't render
  10369. // properly. The allowClone option is used in sparklines as a micro optimization,
  10370. // saving about 1-2 ms each chart.
  10371. if (!optionsChart.skipClone && !renderTo.offsetWidth) {
  10372. chart.cloneRenderTo();
  10373. }
  10374. // get the width and height
  10375. chart.getChartSize();
  10376. chartWidth = chart.chartWidth;
  10377. chartHeight = chart.chartHeight;
  10378. // create the inner container
  10379. chart.container = container = createElement(DIV, {
  10380. className: PREFIX + 'container' +
  10381. (optionsChart.className ? ' ' + optionsChart.className : ''),
  10382. id: containerId
  10383. }, extend({
  10384. position: RELATIVE,
  10385. overflow: HIDDEN, // needed for context menu (avoid scrollbars) and
  10386. // content overflow in IE
  10387. width: chartWidth + PX,
  10388. height: chartHeight + PX,
  10389. textAlign: 'left',
  10390. lineHeight: 'normal', // #427
  10391. zIndex: 0, // #1072
  10392. '-webkit-tap-highlight-color': 'rgba(0,0,0,0)'
  10393. }, optionsChart.style),
  10394. chart.renderToClone || renderTo
  10395. );
  10396. // cache the cursor (#1650)
  10397. chart._cursor = container.style.cursor;
  10398. // Initialize the renderer
  10399. Ren = Highcharts[optionsChart.renderer] || Renderer;
  10400. chart.renderer = new Ren(
  10401. container,
  10402. chartWidth,
  10403. chartHeight,
  10404. optionsChart.style,
  10405. optionsChart.forExport,
  10406. options.exporting && options.exporting.allowHTML
  10407. );
  10408. if (useCanVG) {
  10409. // If we need canvg library, extend and configure the renderer
  10410. // to get the tracker for translating mouse events
  10411. chart.renderer.create(chart, container, chartWidth, chartHeight);
  10412. }
  10413. // Add a reference to the charts index
  10414. chart.renderer.chartIndex = chart.index;
  10415. },
  10416. /**
  10417. * Calculate margins by rendering axis labels in a preliminary position. Title,
  10418. * subtitle and legend have already been rendered at this stage, but will be
  10419. * moved into their final positions
  10420. */
  10421. getMargins: function (skipAxes) {
  10422. var chart = this,
  10423. spacing = chart.spacing,
  10424. margin = chart.margin,
  10425. titleOffset = chart.titleOffset;
  10426. chart.resetMargins();
  10427. // Adjust for title and subtitle
  10428. if (titleOffset && !defined(margin[0])) {
  10429. chart.plotTop = mathMax(chart.plotTop, titleOffset + chart.options.title.margin + spacing[0]);
  10430. }
  10431. // Adjust for legend
  10432. chart.legend.adjustMargins(margin, spacing);
  10433. // adjust for scroller
  10434. if (chart.extraBottomMargin) {
  10435. chart.marginBottom += chart.extraBottomMargin;
  10436. }
  10437. if (chart.extraTopMargin) {
  10438. chart.plotTop += chart.extraTopMargin;
  10439. }
  10440. if (!skipAxes) {
  10441. this.getAxisMargins();
  10442. }
  10443. },
  10444. getAxisMargins: function () {
  10445. var chart = this,
  10446. axisOffset = chart.axisOffset = [0, 0, 0, 0], // top, right, bottom, left
  10447. margin = chart.margin;
  10448. // pre-render axes to get labels offset width
  10449. if (chart.hasCartesianSeries) {
  10450. each(chart.axes, function (axis) {
  10451. if (axis.visible) {
  10452. axis.getOffset();
  10453. }
  10454. });
  10455. }
  10456. // Add the axis offsets
  10457. each(marginNames, function (m, side) {
  10458. if (!defined(margin[side])) {
  10459. chart[m] += axisOffset[side];
  10460. }
  10461. });
  10462. chart.setChartSize();
  10463. },
  10464. /**
  10465. * Resize the chart to its container if size is not explicitly set
  10466. */
  10467. reflow: function (e) {
  10468. var chart = this,
  10469. optionsChart = chart.options.chart,
  10470. renderTo = chart.renderTo,
  10471. width = optionsChart.width || adapterRun(renderTo, 'width'),
  10472. height = optionsChart.height || adapterRun(renderTo, 'height'),
  10473. target = e ? e.target : win, // #805 - MooTools doesn't supply e
  10474. doReflow = function () {
  10475. if (chart.container) { // It may have been destroyed in the meantime (#1257)
  10476. chart.setSize(width, height, false);
  10477. chart.hasUserSize = null;
  10478. }
  10479. };
  10480. // Width and height checks for display:none. Target is doc in IE8 and Opera,
  10481. // win in Firefox, Chrome and IE9.
  10482. if (!chart.hasUserSize && !chart.isPrinting && width && height && (target === win || target === doc)) { // #1093
  10483. if (width !== chart.containerWidth || height !== chart.containerHeight) {
  10484. clearTimeout(chart.reflowTimeout);
  10485. if (e) { // Called from window.resize
  10486. chart.reflowTimeout = setTimeout(doReflow, 100);
  10487. } else { // Called directly (#2224)
  10488. doReflow();
  10489. }
  10490. }
  10491. chart.containerWidth = width;
  10492. chart.containerHeight = height;
  10493. }
  10494. },
  10495. /**
  10496. * Add the event handlers necessary for auto resizing
  10497. */
  10498. initReflow: function () {
  10499. var chart = this,
  10500. reflow = function (e) {
  10501. chart.reflow(e);
  10502. };
  10503. addEvent(win, 'resize', reflow);
  10504. addEvent(chart, 'destroy', function () {
  10505. removeEvent(win, 'resize', reflow);
  10506. });
  10507. },
  10508. /**
  10509. * Resize the chart to a given width and height
  10510. * @param {Number} width
  10511. * @param {Number} height
  10512. * @param {Object|Boolean} animation
  10513. */
  10514. setSize: function (width, height, animation) {
  10515. var chart = this,
  10516. chartWidth,
  10517. chartHeight,
  10518. fireEndResize,
  10519. renderer = chart.renderer,
  10520. globalAnimation;
  10521. // Handle the isResizing counter
  10522. chart.isResizing += 1;
  10523. fireEndResize = function () {
  10524. if (chart) {
  10525. fireEvent(chart, 'endResize', null, function () {
  10526. chart.isResizing -= 1;
  10527. });
  10528. }
  10529. };
  10530. // set the animation for the current process
  10531. setAnimation(animation, chart);
  10532. chart.oldChartHeight = chart.chartHeight;
  10533. chart.oldChartWidth = chart.chartWidth;
  10534. if (defined(width)) {
  10535. chart.chartWidth = chartWidth = mathMax(0, mathRound(width));
  10536. chart.hasUserSize = !!chartWidth;
  10537. }
  10538. if (defined(height)) {
  10539. chart.chartHeight = chartHeight = mathMax(0, mathRound(height));
  10540. }
  10541. // Resize the container with the global animation applied if enabled (#2503)
  10542. globalAnimation = renderer.globalAnimation;
  10543. (globalAnimation ? animate : css)(chart.container, {
  10544. width: chartWidth + PX,
  10545. height: chartHeight + PX
  10546. }, globalAnimation);
  10547. chart.setChartSize(true);
  10548. renderer.setSize(chartWidth, chartHeight, animation);
  10549. // handle axes
  10550. chart.maxTicks = null;
  10551. each(chart.axes, function (axis) {
  10552. axis.isDirty = true;
  10553. axis.setScale();
  10554. });
  10555. // make sure non-cartesian series are also handled
  10556. each(chart.series, function (serie) {
  10557. serie.isDirty = true;
  10558. });
  10559. chart.isDirtyLegend = true; // force legend redraw
  10560. chart.isDirtyBox = true; // force redraw of plot and chart border
  10561. chart.layOutTitles(); // #2857
  10562. chart.getMargins();
  10563. chart.redraw(animation);
  10564. chart.oldChartHeight = null;
  10565. fireEvent(chart, 'resize');
  10566. // Fire endResize and set isResizing back. If animation is disabled, fire without delay
  10567. globalAnimation = renderer.globalAnimation; // Reassign it before using it, it may have changed since the top of this function.
  10568. if (globalAnimation === false) {
  10569. fireEndResize();
  10570. } else { // else set a timeout with the animation duration
  10571. setTimeout(fireEndResize, (globalAnimation && globalAnimation.duration) || 500);
  10572. }
  10573. },
  10574. /**
  10575. * Set the public chart properties. This is done before and after the pre-render
  10576. * to determine margin sizes
  10577. */
  10578. setChartSize: function (skipAxes) {
  10579. var chart = this,
  10580. inverted = chart.inverted,
  10581. renderer = chart.renderer,
  10582. chartWidth = chart.chartWidth,
  10583. chartHeight = chart.chartHeight,
  10584. optionsChart = chart.options.chart,
  10585. spacing = chart.spacing,
  10586. clipOffset = chart.clipOffset,
  10587. clipX,
  10588. clipY,
  10589. plotLeft,
  10590. plotTop,
  10591. plotWidth,
  10592. plotHeight,
  10593. plotBorderWidth;
  10594. chart.plotLeft = plotLeft = mathRound(chart.plotLeft);
  10595. chart.plotTop = plotTop = mathRound(chart.plotTop);
  10596. chart.plotWidth = plotWidth = mathMax(0, mathRound(chartWidth - plotLeft - chart.marginRight));
  10597. chart.plotHeight = plotHeight = mathMax(0, mathRound(chartHeight - plotTop - chart.marginBottom));
  10598. chart.plotSizeX = inverted ? plotHeight : plotWidth;
  10599. chart.plotSizeY = inverted ? plotWidth : plotHeight;
  10600. chart.plotBorderWidth = optionsChart.plotBorderWidth || 0;
  10601. // Set boxes used for alignment
  10602. chart.spacingBox = renderer.spacingBox = {
  10603. x: spacing[3],
  10604. y: spacing[0],
  10605. width: chartWidth - spacing[3] - spacing[1],
  10606. height: chartHeight - spacing[0] - spacing[2]
  10607. };
  10608. chart.plotBox = renderer.plotBox = {
  10609. x: plotLeft,
  10610. y: plotTop,
  10611. width: plotWidth,
  10612. height: plotHeight
  10613. };
  10614. plotBorderWidth = 2 * mathFloor(chart.plotBorderWidth / 2);
  10615. clipX = mathCeil(mathMax(plotBorderWidth, clipOffset[3]) / 2);
  10616. clipY = mathCeil(mathMax(plotBorderWidth, clipOffset[0]) / 2);
  10617. chart.clipBox = {
  10618. x: clipX,
  10619. y: clipY,
  10620. width: mathFloor(chart.plotSizeX - mathMax(plotBorderWidth, clipOffset[1]) / 2 - clipX),
  10621. height: mathMax(0, mathFloor(chart.plotSizeY - mathMax(plotBorderWidth, clipOffset[2]) / 2 - clipY))
  10622. };
  10623. if (!skipAxes) {
  10624. each(chart.axes, function (axis) {
  10625. axis.setAxisSize();
  10626. axis.setAxisTranslation();
  10627. });
  10628. }
  10629. },
  10630. /**
  10631. * Initial margins before auto size margins are applied
  10632. */
  10633. resetMargins: function () {
  10634. var chart = this;
  10635. each(marginNames, function (m, side) {
  10636. chart[m] = pick(chart.margin[side], chart.spacing[side]);
  10637. });
  10638. chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left
  10639. chart.clipOffset = [0, 0, 0, 0];
  10640. },
  10641. /**
  10642. * Draw the borders and backgrounds for chart and plot area
  10643. */
  10644. drawChartBox: function () {
  10645. var chart = this,
  10646. optionsChart = chart.options.chart,
  10647. renderer = chart.renderer,
  10648. chartWidth = chart.chartWidth,
  10649. chartHeight = chart.chartHeight,
  10650. chartBackground = chart.chartBackground,
  10651. plotBackground = chart.plotBackground,
  10652. plotBorder = chart.plotBorder,
  10653. plotBGImage = chart.plotBGImage,
  10654. chartBorderWidth = optionsChart.borderWidth || 0,
  10655. chartBackgroundColor = optionsChart.backgroundColor,
  10656. plotBackgroundColor = optionsChart.plotBackgroundColor,
  10657. plotBackgroundImage = optionsChart.plotBackgroundImage,
  10658. plotBorderWidth = optionsChart.plotBorderWidth || 0,
  10659. mgn,
  10660. bgAttr,
  10661. plotLeft = chart.plotLeft,
  10662. plotTop = chart.plotTop,
  10663. plotWidth = chart.plotWidth,
  10664. plotHeight = chart.plotHeight,
  10665. plotBox = chart.plotBox,
  10666. clipRect = chart.clipRect,
  10667. clipBox = chart.clipBox;
  10668. // Chart area
  10669. mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0);
  10670. if (chartBorderWidth || chartBackgroundColor) {
  10671. if (!chartBackground) {
  10672. bgAttr = {
  10673. fill: chartBackgroundColor || NONE
  10674. };
  10675. if (chartBorderWidth) { // #980
  10676. bgAttr.stroke = optionsChart.borderColor;
  10677. bgAttr['stroke-width'] = chartBorderWidth;
  10678. }
  10679. chart.chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn,
  10680. optionsChart.borderRadius, chartBorderWidth)
  10681. .attr(bgAttr)
  10682. .addClass(PREFIX + 'background')
  10683. .add()
  10684. .shadow(optionsChart.shadow);
  10685. } else { // resize
  10686. chartBackground.animate(
  10687. chartBackground.crisp({ width: chartWidth - mgn, height: chartHeight - mgn })
  10688. );
  10689. }
  10690. }
  10691. // Plot background
  10692. if (plotBackgroundColor) {
  10693. if (!plotBackground) {
  10694. chart.plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0)
  10695. .attr({
  10696. fill: plotBackgroundColor
  10697. })
  10698. .add()
  10699. .shadow(optionsChart.plotShadow);
  10700. } else {
  10701. plotBackground.animate(plotBox);
  10702. }
  10703. }
  10704. if (plotBackgroundImage) {
  10705. if (!plotBGImage) {
  10706. chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight)
  10707. .add();
  10708. } else {
  10709. plotBGImage.animate(plotBox);
  10710. }
  10711. }
  10712. // Plot clip
  10713. if (!clipRect) {
  10714. chart.clipRect = renderer.clipRect(clipBox);
  10715. } else {
  10716. clipRect.animate({
  10717. width: clipBox.width,
  10718. height: clipBox.height
  10719. });
  10720. }
  10721. // Plot area border
  10722. if (plotBorderWidth) {
  10723. if (!plotBorder) {
  10724. chart.plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, -plotBorderWidth)
  10725. .attr({
  10726. stroke: optionsChart.plotBorderColor,
  10727. 'stroke-width': plotBorderWidth,
  10728. fill: NONE,
  10729. zIndex: 1
  10730. })
  10731. .add();
  10732. } else {
  10733. plotBorder.animate(
  10734. plotBorder.crisp({ x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight, strokeWidth: -plotBorderWidth }) //#3282 plotBorder should be negative
  10735. );
  10736. }
  10737. }
  10738. // reset
  10739. chart.isDirtyBox = false;
  10740. },
  10741. /**
  10742. * Detect whether a certain chart property is needed based on inspecting its options
  10743. * and series. This mainly applies to the chart.invert property, and in extensions to
  10744. * the chart.angular and chart.polar properties.
  10745. */
  10746. propFromSeries: function () {
  10747. var chart = this,
  10748. optionsChart = chart.options.chart,
  10749. klass,
  10750. seriesOptions = chart.options.series,
  10751. i,
  10752. value;
  10753. each(['inverted', 'angular', 'polar'], function (key) {
  10754. // The default series type's class
  10755. klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType];
  10756. // Get the value from available chart-wide properties
  10757. value = (
  10758. chart[key] || // 1. it is set before
  10759. optionsChart[key] || // 2. it is set in the options
  10760. (klass && klass.prototype[key]) // 3. it's default series class requires it
  10761. );
  10762. // 4. Check if any the chart's series require it
  10763. i = seriesOptions && seriesOptions.length;
  10764. while (!value && i--) {
  10765. klass = seriesTypes[seriesOptions[i].type];
  10766. if (klass && klass.prototype[key]) {
  10767. value = true;
  10768. }
  10769. }
  10770. // Set the chart property
  10771. chart[key] = value;
  10772. });
  10773. },
  10774. /**
  10775. * Link two or more series together. This is done initially from Chart.render,
  10776. * and after Chart.addSeries and Series.remove.
  10777. */
  10778. linkSeries: function () {
  10779. var chart = this,
  10780. chartSeries = chart.series;
  10781. // Reset links
  10782. each(chartSeries, function (series) {
  10783. series.linkedSeries.length = 0;
  10784. });
  10785. // Apply new links
  10786. each(chartSeries, function (series) {
  10787. var linkedTo = series.options.linkedTo;
  10788. if (isString(linkedTo)) {
  10789. if (linkedTo === ':previous') {
  10790. linkedTo = chart.series[series.index - 1];
  10791. } else {
  10792. linkedTo = chart.get(linkedTo);
  10793. }
  10794. if (linkedTo) {
  10795. linkedTo.linkedSeries.push(series);
  10796. series.linkedParent = linkedTo;
  10797. series.visible = pick(series.options.visible, linkedTo.options.visible, series.visible); // #3879
  10798. }
  10799. }
  10800. });
  10801. },
  10802. /**
  10803. * Render series for the chart
  10804. */
  10805. renderSeries: function () {
  10806. each(this.series, function (serie) {
  10807. serie.translate();
  10808. serie.render();
  10809. });
  10810. },
  10811. /**
  10812. * Render labels for the chart
  10813. */
  10814. renderLabels: function () {
  10815. var chart = this,
  10816. labels = chart.options.labels;
  10817. if (labels.items) {
  10818. each(labels.items, function (label) {
  10819. var style = extend(labels.style, label.style),
  10820. x = pInt(style.left) + chart.plotLeft,
  10821. y = pInt(style.top) + chart.plotTop + 12;
  10822. // delete to prevent rewriting in IE
  10823. delete style.left;
  10824. delete style.top;
  10825. chart.renderer.text(
  10826. label.html,
  10827. x,
  10828. y
  10829. )
  10830. .attr({ zIndex: 2 })
  10831. .css(style)
  10832. .add();
  10833. });
  10834. }
  10835. },
  10836. /**
  10837. * Render all graphics for the chart
  10838. */
  10839. render: function () {
  10840. var chart = this,
  10841. axes = chart.axes,
  10842. renderer = chart.renderer,
  10843. options = chart.options,
  10844. tempWidth,
  10845. tempHeight,
  10846. redoHorizontal,
  10847. redoVertical;
  10848. // Title
  10849. chart.setTitle();
  10850. // Legend
  10851. chart.legend = new Legend(chart, options.legend);
  10852. // Get stacks
  10853. if (chart.getStacks) {
  10854. chart.getStacks();
  10855. }
  10856. // Get chart margins
  10857. chart.getMargins(true);
  10858. chart.setChartSize();
  10859. // Record preliminary dimensions for later comparison
  10860. tempWidth = chart.plotWidth;
  10861. tempHeight = chart.plotHeight = chart.plotHeight - 13; // 13 is the most common height of X axis labels
  10862. // Get margins by pre-rendering axes
  10863. each(axes, function (axis) {
  10864. axis.setScale();
  10865. });
  10866. chart.getAxisMargins();
  10867. // If the plot area size has changed significantly, calculate tick positions again
  10868. redoHorizontal = tempWidth / chart.plotWidth > 1.1;
  10869. redoVertical = tempHeight / chart.plotHeight > 1.1;
  10870. if (redoHorizontal || redoVertical) {
  10871. chart.maxTicks = null; // reset for second pass
  10872. each(axes, function (axis) {
  10873. if ((axis.horiz && redoHorizontal) || (!axis.horiz && redoVertical)) {
  10874. axis.setTickInterval(true); // update to reflect the new margins
  10875. }
  10876. });
  10877. chart.getMargins(); // second pass to check for new labels
  10878. }
  10879. // Draw the borders and backgrounds
  10880. chart.drawChartBox();
  10881. // Axes
  10882. if (chart.hasCartesianSeries) {
  10883. each(axes, function (axis) {
  10884. if (axis.visible) {
  10885. axis.render();
  10886. }
  10887. });
  10888. }
  10889. // The series
  10890. if (!chart.seriesGroup) {
  10891. chart.seriesGroup = renderer.g('series-group')
  10892. .attr({ zIndex: 3 })
  10893. .add();
  10894. }
  10895. chart.renderSeries();
  10896. // Labels
  10897. chart.renderLabels();
  10898. // Credits
  10899. chart.showCredits(options.credits);
  10900. // Set flag
  10901. chart.hasRendered = true;
  10902. },
  10903. /**
  10904. * Show chart credits based on config options
  10905. */
  10906. showCredits: function (credits) {
  10907. if (credits.enabled && !this.credits) {
  10908. this.credits = this.renderer.text(
  10909. credits.text,
  10910. 0,
  10911. 0
  10912. )
  10913. .on('click', function () {
  10914. if (credits.href) {
  10915. location.href = credits.href;
  10916. }
  10917. })
  10918. .attr({
  10919. align: credits.position.align,
  10920. zIndex: 8
  10921. })
  10922. .css(credits.style)
  10923. .add()
  10924. .align(credits.position);
  10925. }
  10926. },
  10927. /**
  10928. * Clean up memory usage
  10929. */
  10930. destroy: function () {
  10931. var chart = this,
  10932. axes = chart.axes,
  10933. series = chart.series,
  10934. container = chart.container,
  10935. i,
  10936. parentNode = container && container.parentNode;
  10937. // fire the chart.destoy event
  10938. fireEvent(chart, 'destroy');
  10939. // Delete the chart from charts lookup array
  10940. charts[chart.index] = UNDEFINED;
  10941. chartCount--;
  10942. chart.renderTo.removeAttribute('data-highcharts-chart');
  10943. // remove events
  10944. removeEvent(chart);
  10945. // ==== Destroy collections:
  10946. // Destroy axes
  10947. i = axes.length;
  10948. while (i--) {
  10949. axes[i] = axes[i].destroy();
  10950. }
  10951. // Destroy each series
  10952. i = series.length;
  10953. while (i--) {
  10954. series[i] = series[i].destroy();
  10955. }
  10956. // ==== Destroy chart properties:
  10957. each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage',
  10958. 'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer', 'scroller',
  10959. 'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'], function (name) {
  10960. var prop = chart[name];
  10961. if (prop && prop.destroy) {
  10962. chart[name] = prop.destroy();
  10963. }
  10964. });
  10965. // remove container and all SVG
  10966. if (container) { // can break in IE when destroyed before finished loading
  10967. container.innerHTML = '';
  10968. removeEvent(container);
  10969. if (parentNode) {
  10970. discardElement(container);
  10971. }
  10972. }
  10973. // clean it all up
  10974. for (i in chart) {
  10975. delete chart[i];
  10976. }
  10977. },
  10978. /**
  10979. * VML namespaces can't be added until after complete. Listening
  10980. * for Perini's doScroll hack is not enough.
  10981. */
  10982. isReadyToRender: function () {
  10983. var chart = this;
  10984. // Note: in spite of JSLint's complaints, win == win.top is required
  10985. /*jslint eqeq: true*/
  10986. if ((!hasSVG && (win == win.top && doc.readyState !== 'complete')) || (useCanVG && !win.canvg)) {
  10987. /*jslint eqeq: false*/
  10988. if (useCanVG) {
  10989. // Delay rendering until canvg library is downloaded and ready
  10990. CanVGController.push(function () { chart.firstRender(); }, chart.options.global.canvasToolsURL);
  10991. } else {
  10992. doc.attachEvent('onreadystatechange', function () {
  10993. doc.detachEvent('onreadystatechange', chart.firstRender);
  10994. if (doc.readyState === 'complete') {
  10995. chart.firstRender();
  10996. }
  10997. });
  10998. }
  10999. return false;
  11000. }
  11001. return true;
  11002. },
  11003. /**
  11004. * Prepare for first rendering after all data are loaded
  11005. */
  11006. firstRender: function () {
  11007. var chart = this,
  11008. options = chart.options,
  11009. callback = chart.callback;
  11010. // Check whether the chart is ready to render
  11011. if (!chart.isReadyToRender()) {
  11012. return;
  11013. }
  11014. // Create the container
  11015. chart.getContainer();
  11016. // Run an early event after the container and renderer are established
  11017. fireEvent(chart, 'init');
  11018. chart.resetMargins();
  11019. chart.setChartSize();
  11020. // Set the common chart properties (mainly invert) from the given series
  11021. chart.propFromSeries();
  11022. // get axes
  11023. chart.getAxes();
  11024. // Initialize the series
  11025. each(options.series || [], function (serieOptions) {
  11026. chart.initSeries(serieOptions);
  11027. });
  11028. chart.linkSeries();
  11029. // Run an event after axes and series are initialized, but before render. At this stage,
  11030. // the series data is indexed and cached in the xData and yData arrays, so we can access
  11031. // those before rendering. Used in Highstock.
  11032. fireEvent(chart, 'beforeRender');
  11033. // depends on inverted and on margins being set
  11034. if (Highcharts.Pointer) {
  11035. chart.pointer = new Pointer(chart, options);
  11036. }
  11037. chart.render();
  11038. // add canvas
  11039. chart.renderer.draw();
  11040. // run callbacks
  11041. if (callback) {
  11042. callback.apply(chart, [chart]);
  11043. }
  11044. each(chart.callbacks, function (fn) {
  11045. if (chart.index !== UNDEFINED) { // Chart destroyed in its own callback (#3600)
  11046. fn.apply(chart, [chart]);
  11047. }
  11048. });
  11049. // Fire the load event
  11050. fireEvent(chart, 'load');
  11051. // If the chart was rendered outside the top container, put it back in (#3679)
  11052. chart.cloneRenderTo(true);
  11053. },
  11054. /**
  11055. * Creates arrays for spacing and margin from given options.
  11056. */
  11057. splashArray: function (target, options) {
  11058. var oVar = options[target],
  11059. tArray = isObject(oVar) ? oVar : [oVar, oVar, oVar, oVar];
  11060. return [pick(options[target + 'Top'], tArray[0]),
  11061. pick(options[target + 'Right'], tArray[1]),
  11062. pick(options[target + 'Bottom'], tArray[2]),
  11063. pick(options[target + 'Left'], tArray[3])];
  11064. }
  11065. }; // end Chart
  11066. var CenteredSeriesMixin = Highcharts.CenteredSeriesMixin = {
  11067. /**
  11068. * Get the center of the pie based on the size and center options relative to the
  11069. * plot area. Borrowed by the polar and gauge series types.
  11070. */
  11071. getCenter: function () {
  11072. var options = this.options,
  11073. chart = this.chart,
  11074. slicingRoom = 2 * (options.slicedOffset || 0),
  11075. handleSlicingRoom,
  11076. plotWidth = chart.plotWidth - 2 * slicingRoom,
  11077. plotHeight = chart.plotHeight - 2 * slicingRoom,
  11078. centerOption = options.center,
  11079. positions = [pick(centerOption[0], '50%'), pick(centerOption[1], '50%'), options.size || '100%', options.innerSize || 0],
  11080. smallestSize = mathMin(plotWidth, plotHeight),
  11081. i,
  11082. value;
  11083. for (i = 0; i < 4; ++i) {
  11084. value = positions[i];
  11085. handleSlicingRoom = i < 2 || (i === 2 && /%$/.test(value));
  11086. // i == 0: centerX, relative to width
  11087. // i == 1: centerY, relative to height
  11088. // i == 2: size, relative to smallestSize
  11089. // i == 3: innerSize, relative to size
  11090. positions[i] = relativeLength(value, [plotWidth, plotHeight, smallestSize, positions[2]][i]) +
  11091. (handleSlicingRoom ? slicingRoom : 0);
  11092. }
  11093. // innerSize cannot be larger than size (#3632)
  11094. if (positions[3] > positions[2]) {
  11095. positions[3] = positions[2];
  11096. }
  11097. return positions;
  11098. }
  11099. };
  11100. /**
  11101. * The Point object and prototype. Inheritable and used as base for PiePoint
  11102. */
  11103. var Point = function () {};
  11104. Point.prototype = {
  11105. /**
  11106. * Initialize the point
  11107. * @param {Object} series The series object containing this point
  11108. * @param {Object} options The data in either number, array or object format
  11109. */
  11110. init: function (series, options, x) {
  11111. var point = this,
  11112. colors;
  11113. point.series = series;
  11114. point.color = series.color; // #3445
  11115. point.applyOptions(options, x);
  11116. point.pointAttr = {};
  11117. if (series.options.colorByPoint) {
  11118. colors = series.options.colors || series.chart.options.colors;
  11119. point.color = point.color || colors[series.colorCounter++];
  11120. // loop back to zero
  11121. if (series.colorCounter === colors.length) {
  11122. series.colorCounter = 0;
  11123. }
  11124. }
  11125. series.chart.pointCount++;
  11126. return point;
  11127. },
  11128. /**
  11129. * Apply the options containing the x and y data and possible some extra properties.
  11130. * This is called on point init or from point.update.
  11131. *
  11132. * @param {Object} options
  11133. */
  11134. applyOptions: function (options, x) {
  11135. var point = this,
  11136. series = point.series,
  11137. pointValKey = series.options.pointValKey || series.pointValKey;
  11138. options = Point.prototype.optionsToObject.call(this, options);
  11139. // copy options directly to point
  11140. extend(point, options);
  11141. point.options = point.options ? extend(point.options, options) : options;
  11142. // For higher dimension series types. For instance, for ranges, point.y is mapped to point.low.
  11143. if (pointValKey) {
  11144. point.y = point[pointValKey];
  11145. }
  11146. // If no x is set by now, get auto incremented value. All points must have an
  11147. // x value, however the y value can be null to create a gap in the series
  11148. if (point.x === UNDEFINED && series) {
  11149. point.x = x === UNDEFINED ? series.autoIncrement() : x;
  11150. }
  11151. return point;
  11152. },
  11153. /**
  11154. * Transform number or array configs into objects
  11155. */
  11156. optionsToObject: function (options) {
  11157. var ret = {},
  11158. series = this.series,
  11159. keys = series.options.keys,
  11160. pointArrayMap = keys || series.pointArrayMap || ['y'],
  11161. valueCount = pointArrayMap.length,
  11162. firstItemType,
  11163. i = 0,
  11164. j = 0;
  11165. if (typeof options === 'number' || options === null) {
  11166. ret[pointArrayMap[0]] = options;
  11167. } else if (isArray(options)) {
  11168. // with leading x value
  11169. if (!keys && options.length > valueCount) {
  11170. firstItemType = typeof options[0];
  11171. if (firstItemType === 'string') {
  11172. ret.name = options[0];
  11173. } else if (firstItemType === 'number') {
  11174. ret.x = options[0];
  11175. }
  11176. i++;
  11177. }
  11178. while (j < valueCount) {
  11179. if (!keys || options[i] !== undefined) { // Skip undefined positions for keys
  11180. ret[pointArrayMap[j]] = options[i];
  11181. }
  11182. i++;
  11183. j++;
  11184. }
  11185. } else if (typeof options === 'object') {
  11186. ret = options;
  11187. // This is the fastest way to detect if there are individual point dataLabels that need
  11188. // to be considered in drawDataLabels. These can only occur in object configs.
  11189. if (options.dataLabels) {
  11190. series._hasPointLabels = true;
  11191. }
  11192. // Same approach as above for markers
  11193. if (options.marker) {
  11194. series._hasPointMarkers = true;
  11195. }
  11196. }
  11197. return ret;
  11198. },
  11199. /**
  11200. * Destroy a point to clear memory. Its reference still stays in series.data.
  11201. */
  11202. destroy: function () {
  11203. var point = this,
  11204. series = point.series,
  11205. chart = series.chart,
  11206. hoverPoints = chart.hoverPoints,
  11207. prop;
  11208. chart.pointCount--;
  11209. if (hoverPoints) {
  11210. point.setState();
  11211. erase(hoverPoints, point);
  11212. if (!hoverPoints.length) {
  11213. chart.hoverPoints = null;
  11214. }
  11215. }
  11216. if (point === chart.hoverPoint) {
  11217. point.onMouseOut();
  11218. }
  11219. // remove all events
  11220. if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive
  11221. removeEvent(point);
  11222. point.destroyElements();
  11223. }
  11224. if (point.legendItem) { // pies have legend items
  11225. chart.legend.destroyItem(point);
  11226. }
  11227. for (prop in point) {
  11228. point[prop] = null;
  11229. }
  11230. },
  11231. /**
  11232. * Destroy SVG elements associated with the point
  11233. */
  11234. destroyElements: function () {
  11235. var point = this,
  11236. props = ['graphic', 'dataLabel', 'dataLabelUpper', 'connector', 'shadowGroup'],
  11237. prop,
  11238. i = 6;
  11239. while (i--) {
  11240. prop = props[i];
  11241. if (point[prop]) {
  11242. point[prop] = point[prop].destroy();
  11243. }
  11244. }
  11245. },
  11246. /**
  11247. * Return the configuration hash needed for the data label and tooltip formatters
  11248. */
  11249. getLabelConfig: function () {
  11250. return {
  11251. x: this.category,
  11252. y: this.y,
  11253. color: this.color,
  11254. key: this.name || this.category,
  11255. series: this.series,
  11256. point: this,
  11257. percentage: this.percentage,
  11258. total: this.total || this.stackTotal
  11259. };
  11260. },
  11261. /**
  11262. * Extendable method for formatting each point's tooltip line
  11263. *
  11264. * @return {String} A string to be concatenated in to the common tooltip text
  11265. */
  11266. tooltipFormatter: function (pointFormat) {
  11267. // Insert options for valueDecimals, valuePrefix, and valueSuffix
  11268. var series = this.series,
  11269. seriesTooltipOptions = series.tooltipOptions,
  11270. valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''),
  11271. valuePrefix = seriesTooltipOptions.valuePrefix || '',
  11272. valueSuffix = seriesTooltipOptions.valueSuffix || '';
  11273. // Loop over the point array map and replace unformatted values with sprintf formatting markup
  11274. each(series.pointArrayMap || ['y'], function (key) {
  11275. key = '{point.' + key; // without the closing bracket
  11276. if (valuePrefix || valueSuffix) {
  11277. pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix);
  11278. }
  11279. pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}');
  11280. });
  11281. return format(pointFormat, {
  11282. point: this,
  11283. series: this.series
  11284. });
  11285. },
  11286. /**
  11287. * Fire an event on the Point object. Must not be renamed to fireEvent, as this
  11288. * causes a name clash in MooTools
  11289. * @param {String} eventType
  11290. * @param {Object} eventArgs Additional event arguments
  11291. * @param {Function} defaultFunction Default event handler
  11292. */
  11293. firePointEvent: function (eventType, eventArgs, defaultFunction) {
  11294. var point = this,
  11295. series = this.series,
  11296. seriesOptions = series.options;
  11297. // load event handlers on demand to save time on mouseover/out
  11298. if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) {
  11299. this.importEvents();
  11300. }
  11301. // add default handler if in selection mode
  11302. if (eventType === 'click' && seriesOptions.allowPointSelect) {
  11303. defaultFunction = function (event) {
  11304. // Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera
  11305. if (point.select) { // Could be destroyed by prior event handlers (#2911)
  11306. point.select(null, event.ctrlKey || event.metaKey || event.shiftKey);
  11307. }
  11308. };
  11309. }
  11310. fireEvent(this, eventType, eventArgs, defaultFunction);
  11311. },
  11312. visible: true
  11313. };/**
  11314. * @classDescription The base function which all other series types inherit from. The data in the series is stored
  11315. * in various arrays.
  11316. *
  11317. * - First, series.options.data contains all the original config options for
  11318. * each point whether added by options or methods like series.addPoint.
  11319. * - Next, series.data contains those values converted to points, but in case the series data length
  11320. * exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It
  11321. * only contains the points that have been created on demand.
  11322. * - Then there's series.points that contains all currently visible point objects. In case of cropping,
  11323. * the cropped-away points are not part of this array. The series.points array starts at series.cropStart
  11324. * compared to series.data and series.options.data. If however the series data is grouped, these can't
  11325. * be correlated one to one.
  11326. * - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points.
  11327. * - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points.
  11328. *
  11329. * @param {Object} chart
  11330. * @param {Object} options
  11331. */
  11332. var Series = Highcharts.Series = function () {};
  11333. Series.prototype = {
  11334. isCartesian: true,
  11335. type: 'line',
  11336. pointClass: Point,
  11337. sorted: true, // requires the data to be sorted
  11338. requireSorting: true,
  11339. pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
  11340. stroke: 'lineColor',
  11341. 'stroke-width': 'lineWidth',
  11342. fill: 'fillColor',
  11343. r: 'radius'
  11344. },
  11345. directTouch: false,
  11346. axisTypes: ['xAxis', 'yAxis'],
  11347. colorCounter: 0,
  11348. parallelArrays: ['x', 'y'], // each point's x and y values are stored in this.xData and this.yData
  11349. init: function (chart, options) {
  11350. var series = this,
  11351. eventType,
  11352. events,
  11353. chartSeries = chart.series,
  11354. sortByIndex = function (a, b) {
  11355. return pick(a.options.index, a._i) - pick(b.options.index, b._i);
  11356. };
  11357. series.chart = chart;
  11358. series.options = options = series.setOptions(options); // merge with plotOptions
  11359. series.linkedSeries = [];
  11360. // bind the axes
  11361. series.bindAxes();
  11362. // set some variables
  11363. extend(series, {
  11364. name: options.name,
  11365. state: NORMAL_STATE,
  11366. pointAttr: {},
  11367. visible: options.visible !== false, // true by default
  11368. selected: options.selected === true // false by default
  11369. });
  11370. // special
  11371. if (useCanVG) {
  11372. options.animation = false;
  11373. }
  11374. // register event listeners
  11375. events = options.events;
  11376. for (eventType in events) {
  11377. addEvent(series, eventType, events[eventType]);
  11378. }
  11379. if (
  11380. (events && events.click) ||
  11381. (options.point && options.point.events && options.point.events.click) ||
  11382. options.allowPointSelect
  11383. ) {
  11384. chart.runTrackerClick = true;
  11385. }
  11386. series.getColor();
  11387. series.getSymbol();
  11388. // Set the data
  11389. each(series.parallelArrays, function (key) {
  11390. series[key + 'Data'] = [];
  11391. });
  11392. series.setData(options.data, false);
  11393. // Mark cartesian
  11394. if (series.isCartesian) {
  11395. chart.hasCartesianSeries = true;
  11396. }
  11397. // Register it in the chart
  11398. chartSeries.push(series);
  11399. series._i = chartSeries.length - 1;
  11400. // Sort series according to index option (#248, #1123, #2456)
  11401. stableSort(chartSeries, sortByIndex);
  11402. if (this.yAxis) {
  11403. stableSort(this.yAxis.series, sortByIndex);
  11404. }
  11405. each(chartSeries, function (series, i) {
  11406. series.index = i;
  11407. series.name = series.name || 'Series ' + (i + 1);
  11408. });
  11409. },
  11410. /**
  11411. * Set the xAxis and yAxis properties of cartesian series, and register the series
  11412. * in the axis.series array
  11413. */
  11414. bindAxes: function () {
  11415. var series = this,
  11416. seriesOptions = series.options,
  11417. chart = series.chart,
  11418. axisOptions;
  11419. each(series.axisTypes || [], function (AXIS) { // repeat for xAxis and yAxis
  11420. each(chart[AXIS], function (axis) { // loop through the chart's axis objects
  11421. axisOptions = axis.options;
  11422. // apply if the series xAxis or yAxis option mathches the number of the
  11423. // axis, or if undefined, use the first axis
  11424. if ((seriesOptions[AXIS] === axisOptions.index) ||
  11425. (seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) ||
  11426. (seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) {
  11427. // register this series in the axis.series lookup
  11428. axis.series.push(series);
  11429. // set this series.xAxis or series.yAxis reference
  11430. series[AXIS] = axis;
  11431. // mark dirty for redraw
  11432. axis.isDirty = true;
  11433. }
  11434. });
  11435. // The series needs an X and an Y axis
  11436. if (!series[AXIS] && series.optionalAxis !== AXIS) {
  11437. error(18, true);
  11438. }
  11439. });
  11440. },
  11441. /**
  11442. * For simple series types like line and column, the data values are held in arrays like
  11443. * xData and yData for quick lookup to find extremes and more. For multidimensional series
  11444. * like bubble and map, this can be extended with arrays like zData and valueData by
  11445. * adding to the series.parallelArrays array.
  11446. */
  11447. updateParallelArrays: function (point, i) {
  11448. var series = point.series,
  11449. args = arguments,
  11450. fn = typeof i === 'number' ?
  11451. // Insert the value in the given position
  11452. function (key) {
  11453. var val = key === 'y' && series.toYData ? series.toYData(point) : point[key];
  11454. series[key + 'Data'][i] = val;
  11455. } :
  11456. // Apply the method specified in i with the following arguments as arguments
  11457. function (key) {
  11458. Array.prototype[i].apply(series[key + 'Data'], Array.prototype.slice.call(args, 2));
  11459. };
  11460. each(series.parallelArrays, fn);
  11461. },
  11462. /**
  11463. * Return an auto incremented x value based on the pointStart and pointInterval options.
  11464. * This is only used if an x value is not given for the point that calls autoIncrement.
  11465. */
  11466. autoIncrement: function () {
  11467. var options = this.options,
  11468. xIncrement = this.xIncrement,
  11469. date,
  11470. pointInterval,
  11471. pointIntervalUnit = options.pointIntervalUnit;
  11472. xIncrement = pick(xIncrement, options.pointStart, 0);
  11473. this.pointInterval = pointInterval = pick(this.pointInterval, options.pointInterval, 1);
  11474. // Added code for pointInterval strings
  11475. if (pointIntervalUnit === 'month' || pointIntervalUnit === 'year') {
  11476. date = new Date(xIncrement);
  11477. date = (pointIntervalUnit === 'month') ?
  11478. +date[setMonth](date[getMonth]() + pointInterval) :
  11479. +date[setFullYear](date[getFullYear]() + pointInterval);
  11480. pointInterval = date - xIncrement;
  11481. }
  11482. this.xIncrement = xIncrement + pointInterval;
  11483. return xIncrement;
  11484. },
  11485. /**
  11486. * Divide the series data into segments divided by null values.
  11487. */
  11488. getSegments: function () {
  11489. var series = this,
  11490. lastNull = -1,
  11491. segments = [],
  11492. i,
  11493. points = series.points,
  11494. pointsLength = points.length;
  11495. if (pointsLength) { // no action required for []
  11496. // if connect nulls, just remove null points
  11497. if (series.options.connectNulls) {
  11498. i = pointsLength;
  11499. while (i--) {
  11500. if (points[i].y === null) {
  11501. points.splice(i, 1);
  11502. }
  11503. }
  11504. if (points.length) {
  11505. segments = [points];
  11506. }
  11507. // else, split on null points
  11508. } else {
  11509. each(points, function (point, i) {
  11510. if (point.y === null) {
  11511. if (i > lastNull + 1) {
  11512. segments.push(points.slice(lastNull + 1, i));
  11513. }
  11514. lastNull = i;
  11515. } else if (i === pointsLength - 1) { // last value
  11516. segments.push(points.slice(lastNull + 1, i + 1));
  11517. }
  11518. });
  11519. }
  11520. }
  11521. // register it
  11522. series.segments = segments;
  11523. },
  11524. /**
  11525. * Set the series options by merging from the options tree
  11526. * @param {Object} itemOptions
  11527. */
  11528. setOptions: function (itemOptions) {
  11529. var chart = this.chart,
  11530. chartOptions = chart.options,
  11531. plotOptions = chartOptions.plotOptions,
  11532. userOptions = chart.userOptions || {},
  11533. userPlotOptions = userOptions.plotOptions || {},
  11534. typeOptions = plotOptions[this.type],
  11535. options,
  11536. zones;
  11537. this.userOptions = itemOptions;
  11538. // General series options take precedence over type options because otherwise, default
  11539. // type options like column.animation would be overwritten by the general option.
  11540. // But issues have been raised here (#3881), and the solution may be to distinguish
  11541. // between default option and userOptions like in the tooltip below.
  11542. options = merge(
  11543. typeOptions,
  11544. plotOptions.series,
  11545. itemOptions
  11546. );
  11547. // The tooltip options are merged between global and series specific options
  11548. this.tooltipOptions = merge(
  11549. defaultOptions.tooltip,
  11550. defaultOptions.plotOptions[this.type].tooltip,
  11551. userOptions.tooltip,
  11552. userPlotOptions.series && userPlotOptions.series.tooltip,
  11553. userPlotOptions[this.type] && userPlotOptions[this.type].tooltip,
  11554. itemOptions.tooltip
  11555. );
  11556. // Delete marker object if not allowed (#1125)
  11557. if (typeOptions.marker === null) {
  11558. delete options.marker;
  11559. }
  11560. // Handle color zones
  11561. this.zoneAxis = options.zoneAxis;
  11562. zones = this.zones = (options.zones || []).slice();
  11563. if ((options.negativeColor || options.negativeFillColor) && !options.zones) {
  11564. zones.push({
  11565. value: options[this.zoneAxis + 'Threshold'] || options.threshold || 0,
  11566. color: options.negativeColor,
  11567. fillColor: options.negativeFillColor
  11568. });
  11569. }
  11570. if (zones.length) { // Push one extra zone for the rest
  11571. if (defined(zones[zones.length - 1].value)) {
  11572. zones.push({
  11573. color: this.color,
  11574. fillColor: this.fillColor
  11575. });
  11576. }
  11577. }
  11578. return options;
  11579. },
  11580. getCyclic: function (prop, value, defaults) {
  11581. var i,
  11582. userOptions = this.userOptions,
  11583. indexName = '_' + prop + 'Index',
  11584. counterName = prop + 'Counter';
  11585. if (!value) {
  11586. if (defined(userOptions[indexName])) { // after Series.update()
  11587. i = userOptions[indexName];
  11588. } else {
  11589. userOptions[indexName] = i = this.chart[counterName] % defaults.length;
  11590. this.chart[counterName] += 1;
  11591. }
  11592. value = defaults[i];
  11593. }
  11594. this[prop] = value;
  11595. },
  11596. /**
  11597. * Get the series' color
  11598. */
  11599. getColor: function () {
  11600. if (this.options.colorByPoint) {
  11601. this.options.color = null; // #4359, selected slice got series.color even when colorByPoint was set.
  11602. } else {
  11603. this.getCyclic('color', this.options.color || defaultPlotOptions[this.type].color, this.chart.options.colors);
  11604. }
  11605. },
  11606. /**
  11607. * Get the series' symbol
  11608. */
  11609. getSymbol: function () {
  11610. var seriesMarkerOption = this.options.marker;
  11611. this.getCyclic('symbol', seriesMarkerOption.symbol, this.chart.options.symbols);
  11612. // don't substract radius in image symbols (#604)
  11613. if (/^url/.test(this.symbol)) {
  11614. seriesMarkerOption.radius = 0;
  11615. }
  11616. },
  11617. drawLegendSymbol: LegendSymbolMixin.drawLineMarker,
  11618. /**
  11619. * Replace the series data with a new set of data
  11620. * @param {Object} data
  11621. * @param {Object} redraw
  11622. */
  11623. setData: function (data, redraw, animation, updatePoints) {
  11624. var series = this,
  11625. oldData = series.points,
  11626. oldDataLength = (oldData && oldData.length) || 0,
  11627. dataLength,
  11628. options = series.options,
  11629. chart = series.chart,
  11630. firstPoint = null,
  11631. xAxis = series.xAxis,
  11632. hasCategories = xAxis && !!xAxis.categories,
  11633. i,
  11634. turboThreshold = options.turboThreshold,
  11635. pt,
  11636. xData = this.xData,
  11637. yData = this.yData,
  11638. pointArrayMap = series.pointArrayMap,
  11639. valueCount = pointArrayMap && pointArrayMap.length;
  11640. data = data || [];
  11641. dataLength = data.length;
  11642. redraw = pick(redraw, true);
  11643. // If the point count is the same as is was, just run Point.update which is
  11644. // cheaper, allows animation, and keeps references to points.
  11645. if (updatePoints !== false && dataLength && oldDataLength === dataLength && !series.cropped && !series.hasGroupedData && series.visible) {
  11646. each(data, function (point, i) {
  11647. if (oldData[i].update) { // Linked, previously hidden series (#3709)
  11648. oldData[i].update(point, false, null, false);
  11649. }
  11650. });
  11651. } else {
  11652. // Reset properties
  11653. series.xIncrement = null;
  11654. series.pointRange = hasCategories ? 1 : options.pointRange;
  11655. series.colorCounter = 0; // for series with colorByPoint (#1547)
  11656. // Update parallel arrays
  11657. each(this.parallelArrays, function (key) {
  11658. series[key + 'Data'].length = 0;
  11659. });
  11660. // In turbo mode, only one- or twodimensional arrays of numbers are allowed. The
  11661. // first value is tested, and we assume that all the rest are defined the same
  11662. // way. Although the 'for' loops are similar, they are repeated inside each
  11663. // if-else conditional for max performance.
  11664. if (turboThreshold && dataLength > turboThreshold) {
  11665. // find the first non-null point
  11666. i = 0;
  11667. while (firstPoint === null && i < dataLength) {
  11668. firstPoint = data[i];
  11669. i++;
  11670. }
  11671. if (isNumber(firstPoint)) { // assume all points are numbers
  11672. var x = pick(options.pointStart, 0),
  11673. pointInterval = pick(options.pointInterval, 1);
  11674. for (i = 0; i < dataLength; i++) {
  11675. xData[i] = x;
  11676. yData[i] = data[i];
  11677. x += pointInterval;
  11678. }
  11679. series.xIncrement = x;
  11680. } else if (isArray(firstPoint)) { // assume all points are arrays
  11681. if (valueCount) { // [x, low, high] or [x, o, h, l, c]
  11682. for (i = 0; i < dataLength; i++) {
  11683. pt = data[i];
  11684. xData[i] = pt[0];
  11685. yData[i] = pt.slice(1, valueCount + 1);
  11686. }
  11687. } else { // [x, y]
  11688. for (i = 0; i < dataLength; i++) {
  11689. pt = data[i];
  11690. xData[i] = pt[0];
  11691. yData[i] = pt[1];
  11692. }
  11693. }
  11694. } else {
  11695. error(12); // Highcharts expects configs to be numbers or arrays in turbo mode
  11696. }
  11697. } else {
  11698. for (i = 0; i < dataLength; i++) {
  11699. if (data[i] !== UNDEFINED) { // stray commas in oldIE
  11700. pt = { series: series };
  11701. series.pointClass.prototype.applyOptions.apply(pt, [data[i]]);
  11702. series.updateParallelArrays(pt, i);
  11703. if (hasCategories && defined(pt.name)) { // #4401
  11704. xAxis.names[pt.x] = pt.name; // #2046
  11705. }
  11706. }
  11707. }
  11708. }
  11709. // Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON
  11710. if (isString(yData[0])) {
  11711. error(14, true);
  11712. }
  11713. series.data = [];
  11714. series.options.data = data;
  11715. //series.zData = zData;
  11716. // destroy old points
  11717. i = oldDataLength;
  11718. while (i--) {
  11719. if (oldData[i] && oldData[i].destroy) {
  11720. oldData[i].destroy();
  11721. }
  11722. }
  11723. // reset minRange (#878)
  11724. if (xAxis) {
  11725. xAxis.minRange = xAxis.userMinRange;
  11726. }
  11727. // redraw
  11728. series.isDirty = series.isDirtyData = chart.isDirtyBox = true;
  11729. animation = false;
  11730. }
  11731. // Typically for pie series, points need to be processed and generated
  11732. // prior to rendering the legend
  11733. if (options.legendType === 'point') { // docs: legendType now supported on more series types (at least column and pie)
  11734. this.processData();
  11735. this.generatePoints();
  11736. }
  11737. if (redraw) {
  11738. chart.redraw(animation);
  11739. }
  11740. },
  11741. /**
  11742. * Process the data by cropping away unused data points if the series is longer
  11743. * than the crop threshold. This saves computing time for lage series.
  11744. */
  11745. processData: function (force) {
  11746. var series = this,
  11747. processedXData = series.xData, // copied during slice operation below
  11748. processedYData = series.yData,
  11749. dataLength = processedXData.length,
  11750. croppedData,
  11751. cropStart = 0,
  11752. cropped,
  11753. distance,
  11754. closestPointRange,
  11755. xAxis = series.xAxis,
  11756. i, // loop variable
  11757. options = series.options,
  11758. cropThreshold = options.cropThreshold,
  11759. getExtremesFromAll = series.getExtremesFromAll || options.getExtremesFromAll, // #4599
  11760. isCartesian = series.isCartesian,
  11761. xExtremes,
  11762. min,
  11763. max;
  11764. // If the series data or axes haven't changed, don't go through this. Return false to pass
  11765. // the message on to override methods like in data grouping.
  11766. if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) {
  11767. return false;
  11768. }
  11769. if (xAxis) {
  11770. xExtremes = xAxis.getExtremes(); // corrected for log axis (#3053)
  11771. min = xExtremes.min;
  11772. max = xExtremes.max;
  11773. }
  11774. // optionally filter out points outside the plot area
  11775. if (isCartesian && series.sorted && !getExtremesFromAll && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) {
  11776. // it's outside current extremes
  11777. if (processedXData[dataLength - 1] < min || processedXData[0] > max) {
  11778. processedXData = [];
  11779. processedYData = [];
  11780. // only crop if it's actually spilling out
  11781. } else if (processedXData[0] < min || processedXData[dataLength - 1] > max) {
  11782. croppedData = this.cropData(series.xData, series.yData, min, max);
  11783. processedXData = croppedData.xData;
  11784. processedYData = croppedData.yData;
  11785. cropStart = croppedData.start;
  11786. cropped = true;
  11787. }
  11788. }
  11789. // Find the closest distance between processed points
  11790. for (i = processedXData.length - 1; i >= 0; i--) {
  11791. distance = processedXData[i] - processedXData[i - 1];
  11792. if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) {
  11793. closestPointRange = distance;
  11794. // Unsorted data is not supported by the line tooltip, as well as data grouping and
  11795. // navigation in Stock charts (#725) and width calculation of columns (#1900)
  11796. } else if (distance < 0 && series.requireSorting) {
  11797. error(15);
  11798. }
  11799. }
  11800. // Record the properties
  11801. series.cropped = cropped; // undefined or true
  11802. series.cropStart = cropStart;
  11803. series.processedXData = processedXData;
  11804. series.processedYData = processedYData;
  11805. if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC
  11806. series.pointRange = closestPointRange || 1;
  11807. }
  11808. series.closestPointRange = closestPointRange;
  11809. },
  11810. /**
  11811. * Iterate over xData and crop values between min and max. Returns object containing crop start/end
  11812. * cropped xData with corresponding part of yData, dataMin and dataMax within the cropped range
  11813. */
  11814. cropData: function (xData, yData, min, max) {
  11815. var dataLength = xData.length,
  11816. cropStart = 0,
  11817. cropEnd = dataLength,
  11818. cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside
  11819. i;
  11820. // iterate up to find slice start
  11821. for (i = 0; i < dataLength; i++) {
  11822. if (xData[i] >= min) {
  11823. cropStart = mathMax(0, i - cropShoulder);
  11824. break;
  11825. }
  11826. }
  11827. // proceed to find slice end
  11828. for (; i < dataLength; i++) {
  11829. if (xData[i] > max) {
  11830. cropEnd = i + cropShoulder;
  11831. break;
  11832. }
  11833. }
  11834. return {
  11835. xData: xData.slice(cropStart, cropEnd),
  11836. yData: yData.slice(cropStart, cropEnd),
  11837. start: cropStart,
  11838. end: cropEnd
  11839. };
  11840. },
  11841. /**
  11842. * Generate the data point after the data has been processed by cropping away
  11843. * unused points and optionally grouped in Highcharts Stock.
  11844. */
  11845. generatePoints: function () {
  11846. var series = this,
  11847. options = series.options,
  11848. dataOptions = options.data,
  11849. data = series.data,
  11850. dataLength,
  11851. processedXData = series.processedXData,
  11852. processedYData = series.processedYData,
  11853. pointClass = series.pointClass,
  11854. processedDataLength = processedXData.length,
  11855. cropStart = series.cropStart || 0,
  11856. cursor,
  11857. hasGroupedData = series.hasGroupedData,
  11858. point,
  11859. points = [],
  11860. i;
  11861. if (!data && !hasGroupedData) {
  11862. var arr = [];
  11863. arr.length = dataOptions.length;
  11864. data = series.data = arr;
  11865. }
  11866. for (i = 0; i < processedDataLength; i++) {
  11867. cursor = cropStart + i;
  11868. if (!hasGroupedData) {
  11869. if (data[cursor]) {
  11870. point = data[cursor];
  11871. } else if (dataOptions[cursor] !== UNDEFINED) { // #970
  11872. data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]);
  11873. }
  11874. points[i] = point;
  11875. } else {
  11876. // splat the y data in case of ohlc data array
  11877. points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i])));
  11878. }
  11879. points[i].index = cursor; // For faster access in Point.update
  11880. }
  11881. // Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when
  11882. // swithching view from non-grouped data to grouped data (#637)
  11883. if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) {
  11884. for (i = 0; i < dataLength; i++) {
  11885. if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points
  11886. i += processedDataLength;
  11887. }
  11888. if (data[i]) {
  11889. data[i].destroyElements();
  11890. data[i].plotX = UNDEFINED; // #1003
  11891. }
  11892. }
  11893. }
  11894. series.data = data;
  11895. series.points = points;
  11896. },
  11897. /**
  11898. * Calculate Y extremes for visible data
  11899. */
  11900. getExtremes: function (yData) {
  11901. var xAxis = this.xAxis,
  11902. yAxis = this.yAxis,
  11903. xData = this.processedXData,
  11904. yDataLength,
  11905. activeYData = [],
  11906. activeCounter = 0,
  11907. xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis
  11908. xMin = xExtremes.min,
  11909. xMax = xExtremes.max,
  11910. validValue,
  11911. withinRange,
  11912. x,
  11913. y,
  11914. i,
  11915. j;
  11916. yData = yData || this.stackedYData || this.processedYData;
  11917. yDataLength = yData.length;
  11918. for (i = 0; i < yDataLength; i++) {
  11919. x = xData[i];
  11920. y = yData[i];
  11921. // For points within the visible range, including the first point outside the
  11922. // visible range, consider y extremes
  11923. validValue = y !== null && y !== UNDEFINED && (!yAxis.isLog || (y.length || y > 0));
  11924. withinRange = this.getExtremesFromAll || this.options.getExtremesFromAll || this.cropped ||
  11925. ((xData[i + 1] || x) >= xMin && (xData[i - 1] || x) <= xMax);
  11926. if (validValue && withinRange) {
  11927. j = y.length;
  11928. if (j) { // array, like ohlc or range data
  11929. while (j--) {
  11930. if (y[j] !== null) {
  11931. activeYData[activeCounter++] = y[j];
  11932. }
  11933. }
  11934. } else {
  11935. activeYData[activeCounter++] = y;
  11936. }
  11937. }
  11938. }
  11939. this.dataMin = arrayMin(activeYData);
  11940. this.dataMax = arrayMax(activeYData);
  11941. },
  11942. /**
  11943. * Translate data points from raw data values to chart specific positioning data
  11944. * needed later in drawPoints, drawGraph and drawTracker.
  11945. */
  11946. translate: function () {
  11947. if (!this.processedXData) { // hidden series
  11948. this.processData();
  11949. }
  11950. this.generatePoints();
  11951. var series = this,
  11952. options = series.options,
  11953. stacking = options.stacking,
  11954. xAxis = series.xAxis,
  11955. categories = xAxis.categories,
  11956. yAxis = series.yAxis,
  11957. points = series.points,
  11958. dataLength = points.length,
  11959. hasModifyValue = !!series.modifyValue,
  11960. i,
  11961. pointPlacement = options.pointPlacement,
  11962. dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement),
  11963. threshold = options.threshold,
  11964. stackThreshold = options.startFromThreshold ? threshold : 0,
  11965. plotX,
  11966. plotY,
  11967. lastPlotX,
  11968. stackIndicator,
  11969. closestPointRangePx = Number.MAX_VALUE;
  11970. // Translate each point
  11971. for (i = 0; i < dataLength; i++) {
  11972. var point = points[i],
  11973. xValue = point.x,
  11974. yValue = point.y,
  11975. yBottom = point.low,
  11976. stack = stacking && yAxis.stacks[(series.negStacks && yValue < (stackThreshold ? 0 : threshold) ? '-' : '') + series.stackKey],
  11977. pointStack,
  11978. stackValues;
  11979. // Discard disallowed y values for log axes (#3434)
  11980. if (yAxis.isLog && yValue !== null && yValue <= 0) {
  11981. point.y = yValue = null;
  11982. error(10);
  11983. }
  11984. // Get the plotX translation
  11985. point.plotX = plotX = mathMin(mathMax(-1e5, xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags')), 1e5); // #3923
  11986. // Calculate the bottom y value for stacked series
  11987. if (stacking && series.visible && stack && stack[xValue]) {
  11988. stackIndicator = series.getStackIndicator(stackIndicator, xValue, series.index);
  11989. pointStack = stack[xValue];
  11990. stackValues = pointStack.points[stackIndicator.key];
  11991. yBottom = stackValues[0];
  11992. yValue = stackValues[1];
  11993. if (yBottom === stackThreshold) {
  11994. yBottom = pick(threshold, yAxis.min);
  11995. }
  11996. if (yAxis.isLog && yBottom <= 0) { // #1200, #1232
  11997. yBottom = null;
  11998. }
  11999. point.total = point.stackTotal = pointStack.total;
  12000. point.percentage = pointStack.total && (point.y / pointStack.total * 100);
  12001. point.stackY = yValue;
  12002. // Place the stack label
  12003. pointStack.setOffset(series.pointXOffset || 0, series.barW || 0);
  12004. }
  12005. // Set translated yBottom or remove it
  12006. point.yBottom = defined(yBottom) ?
  12007. yAxis.translate(yBottom, 0, 1, 0, 1) :
  12008. null;
  12009. // general hook, used for Highstock compare mode
  12010. if (hasModifyValue) {
  12011. yValue = series.modifyValue(yValue, point);
  12012. }
  12013. // Set the the plotY value, reset it for redraws
  12014. point.plotY = plotY = (typeof yValue === 'number' && yValue !== Infinity) ?
  12015. mathMin(mathMax(-1e5, yAxis.translate(yValue, 0, 1, 0, 1)), 1e5) : // #3201
  12016. UNDEFINED;
  12017. point.isInside = plotY !== UNDEFINED && plotY >= 0 && plotY <= yAxis.len && // #3519
  12018. plotX >= 0 && plotX <= xAxis.len;
  12019. // Set client related positions for mouse tracking
  12020. point.clientX = dynamicallyPlaced ? xAxis.translate(xValue, 0, 0, 0, 1) : plotX; // #1514
  12021. point.negative = point.y < (threshold || 0);
  12022. // some API data
  12023. point.category = categories && categories[point.x] !== UNDEFINED ?
  12024. categories[point.x] : point.x;
  12025. // Determine auto enabling of markers (#3635)
  12026. if (i) {
  12027. closestPointRangePx = mathMin(closestPointRangePx, mathAbs(plotX - lastPlotX));
  12028. }
  12029. lastPlotX = plotX;
  12030. }
  12031. series.closestPointRangePx = closestPointRangePx;
  12032. // now that we have the cropped data, build the segments
  12033. series.getSegments();
  12034. },
  12035. /**
  12036. * Set the clipping for the series. For animated series it is called twice, first to initiate
  12037. * animating the clip then the second time without the animation to set the final clip.
  12038. */
  12039. setClip: function (animation) {
  12040. var chart = this.chart,
  12041. options = this.options,
  12042. renderer = chart.renderer,
  12043. inverted = chart.inverted,
  12044. seriesClipBox = this.clipBox,
  12045. clipBox = seriesClipBox || chart.clipBox,
  12046. sharedClipKey = this.sharedClipKey || ['_sharedClip', animation && animation.duration, animation && animation.easing, clipBox.height, options.xAxis, options.yAxis].join(','), // #4526
  12047. clipRect = chart[sharedClipKey],
  12048. markerClipRect = chart[sharedClipKey + 'm'];
  12049. // If a clipping rectangle with the same properties is currently present in the chart, use that.
  12050. if (!clipRect) {
  12051. // When animation is set, prepare the initial positions
  12052. if (animation) {
  12053. clipBox.width = 0;
  12054. chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect(
  12055. -99, // include the width of the first marker
  12056. inverted ? -chart.plotLeft : -chart.plotTop,
  12057. 99,
  12058. inverted ? chart.chartWidth : chart.chartHeight
  12059. );
  12060. }
  12061. chart[sharedClipKey] = clipRect = renderer.clipRect(clipBox);
  12062. }
  12063. if (animation) {
  12064. clipRect.count += 1;
  12065. }
  12066. if (options.clip !== false) {
  12067. this.group.clip(animation || seriesClipBox ? clipRect : chart.clipRect);
  12068. this.markerGroup.clip(markerClipRect);
  12069. this.sharedClipKey = sharedClipKey;
  12070. }
  12071. // Remove the shared clipping rectangle when all series are shown
  12072. if (!animation) {
  12073. clipRect.count -= 1;
  12074. if (clipRect.count <= 0 && sharedClipKey && chart[sharedClipKey]) {
  12075. if (!seriesClipBox) {
  12076. chart[sharedClipKey] = chart[sharedClipKey].destroy();
  12077. }
  12078. if (chart[sharedClipKey + 'm']) {
  12079. chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy();
  12080. }
  12081. }
  12082. }
  12083. },
  12084. /**
  12085. * Animate in the series
  12086. */
  12087. animate: function (init) {
  12088. var series = this,
  12089. chart = series.chart,
  12090. clipRect,
  12091. animation = series.options.animation,
  12092. sharedClipKey;
  12093. // Animation option is set to true
  12094. if (animation && !isObject(animation)) {
  12095. animation = defaultPlotOptions[series.type].animation;
  12096. }
  12097. // Initialize the animation. Set up the clipping rectangle.
  12098. if (init) {
  12099. series.setClip(animation);
  12100. // Run the animation
  12101. } else {
  12102. sharedClipKey = this.sharedClipKey;
  12103. clipRect = chart[sharedClipKey];
  12104. if (clipRect) {
  12105. clipRect.animate({
  12106. width: chart.plotSizeX
  12107. }, animation);
  12108. }
  12109. if (chart[sharedClipKey + 'm']) {
  12110. chart[sharedClipKey + 'm'].animate({
  12111. width: chart.plotSizeX + 99
  12112. }, animation);
  12113. }
  12114. // Delete this function to allow it only once
  12115. series.animate = null;
  12116. }
  12117. },
  12118. /**
  12119. * This runs after animation to land on the final plot clipping
  12120. */
  12121. afterAnimate: function () {
  12122. this.setClip();
  12123. fireEvent(this, 'afterAnimate');
  12124. },
  12125. /**
  12126. * Draw the markers
  12127. */
  12128. drawPoints: function () {
  12129. var series = this,
  12130. pointAttr,
  12131. points = series.points,
  12132. chart = series.chart,
  12133. plotX,
  12134. plotY,
  12135. i,
  12136. point,
  12137. radius,
  12138. symbol,
  12139. isImage,
  12140. graphic,
  12141. options = series.options,
  12142. seriesMarkerOptions = options.marker,
  12143. seriesPointAttr = series.pointAttr[''],
  12144. pointMarkerOptions,
  12145. hasPointMarker,
  12146. enabled,
  12147. isInside,
  12148. markerGroup = series.markerGroup,
  12149. xAxis = series.xAxis,
  12150. globallyEnabled = pick(
  12151. seriesMarkerOptions.enabled,
  12152. xAxis.isRadial,
  12153. series.closestPointRangePx > 2 * seriesMarkerOptions.radius
  12154. );
  12155. if (seriesMarkerOptions.enabled !== false || series._hasPointMarkers) {
  12156. i = points.length;
  12157. while (i--) {
  12158. point = points[i];
  12159. plotX = mathFloor(point.plotX); // #1843
  12160. plotY = point.plotY;
  12161. graphic = point.graphic;
  12162. pointMarkerOptions = point.marker || {};
  12163. hasPointMarker = !!point.marker;
  12164. enabled = (globallyEnabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled;
  12165. isInside = point.isInside;
  12166. // only draw the point if y is defined
  12167. if (enabled && plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) {
  12168. // shortcuts
  12169. pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || seriesPointAttr;
  12170. radius = pointAttr.r;
  12171. symbol = pick(pointMarkerOptions.symbol, series.symbol);
  12172. isImage = symbol.indexOf('url') === 0;
  12173. if (graphic) { // update
  12174. graphic[isInside ? 'show' : 'hide'](true) // Since the marker group isn't clipped, each individual marker must be toggled
  12175. .animate(extend({
  12176. x: plotX - radius,
  12177. y: plotY - radius
  12178. }, graphic.symbolName ? { // don't apply to image symbols #507
  12179. width: 2 * radius,
  12180. height: 2 * radius
  12181. } : {}));
  12182. } else if (isInside && (radius > 0 || isImage)) {
  12183. point.graphic = graphic = chart.renderer.symbol(
  12184. symbol,
  12185. plotX - radius,
  12186. plotY - radius,
  12187. 2 * radius,
  12188. 2 * radius,
  12189. hasPointMarker ? pointMarkerOptions : seriesMarkerOptions
  12190. )
  12191. .attr(pointAttr)
  12192. .add(markerGroup);
  12193. }
  12194. } else if (graphic) {
  12195. point.graphic = graphic.destroy(); // #1269
  12196. }
  12197. }
  12198. }
  12199. },
  12200. /**
  12201. * Convert state properties from API naming conventions to SVG attributes
  12202. *
  12203. * @param {Object} options API options object
  12204. * @param {Object} base1 SVG attribute object to inherit from
  12205. * @param {Object} base2 Second level SVG attribute object to inherit from
  12206. */
  12207. convertAttribs: function (options, base1, base2, base3) {
  12208. var conversion = this.pointAttrToOptions,
  12209. attr,
  12210. option,
  12211. obj = {};
  12212. options = options || {};
  12213. base1 = base1 || {};
  12214. base2 = base2 || {};
  12215. base3 = base3 || {};
  12216. for (attr in conversion) {
  12217. option = conversion[attr];
  12218. obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]);
  12219. }
  12220. return obj;
  12221. },
  12222. /**
  12223. * Get the state attributes. Each series type has its own set of attributes
  12224. * that are allowed to change on a point's state change. Series wide attributes are stored for
  12225. * all series, and additionally point specific attributes are stored for all
  12226. * points with individual marker options. If such options are not defined for the point,
  12227. * a reference to the series wide attributes is stored in point.pointAttr.
  12228. */
  12229. getAttribs: function () {
  12230. var series = this,
  12231. seriesOptions = series.options,
  12232. normalOptions = defaultPlotOptions[series.type].marker ? seriesOptions.marker : seriesOptions,
  12233. stateOptions = normalOptions.states,
  12234. stateOptionsHover = stateOptions[HOVER_STATE],
  12235. pointStateOptionsHover,
  12236. seriesColor = series.color,
  12237. seriesNegativeColor = series.options.negativeColor,
  12238. normalDefaults = {
  12239. stroke: seriesColor,
  12240. fill: seriesColor
  12241. },
  12242. points = series.points || [], // #927
  12243. i,
  12244. j,
  12245. threshold,
  12246. point,
  12247. seriesPointAttr = [],
  12248. pointAttr,
  12249. pointAttrToOptions = series.pointAttrToOptions,
  12250. hasPointSpecificOptions = series.hasPointSpecificOptions,
  12251. defaultLineColor = normalOptions.lineColor,
  12252. defaultFillColor = normalOptions.fillColor,
  12253. turboThreshold = seriesOptions.turboThreshold,
  12254. zones = series.zones,
  12255. zoneAxis = series.zoneAxis || 'y',
  12256. attr,
  12257. key;
  12258. // series type specific modifications
  12259. if (seriesOptions.marker) { // line, spline, area, areaspline, scatter
  12260. // if no hover radius is given, default to normal radius + 2
  12261. stateOptionsHover.radius = stateOptionsHover.radius || normalOptions.radius + stateOptionsHover.radiusPlus;
  12262. stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + stateOptionsHover.lineWidthPlus;
  12263. } else { // column, bar, pie
  12264. // if no hover color is given, brighten the normal color
  12265. stateOptionsHover.color = stateOptionsHover.color ||
  12266. Color(stateOptionsHover.color || seriesColor)
  12267. .brighten(stateOptionsHover.brightness).get();
  12268. // if no hover negativeColor is given, brighten the normal negativeColor
  12269. stateOptionsHover.negativeColor = stateOptionsHover.negativeColor ||
  12270. Color(stateOptionsHover.negativeColor || seriesNegativeColor)
  12271. .brighten(stateOptionsHover.brightness).get();
  12272. }
  12273. // general point attributes for the series normal state
  12274. seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults);
  12275. // HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius
  12276. each([HOVER_STATE, SELECT_STATE], function (state) {
  12277. seriesPointAttr[state] =
  12278. series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]);
  12279. });
  12280. // set it
  12281. series.pointAttr = seriesPointAttr;
  12282. // Generate the point-specific attribute collections if specific point
  12283. // options are given. If not, create a referance to the series wide point
  12284. // attributes
  12285. i = points.length;
  12286. if (!turboThreshold || i < turboThreshold || hasPointSpecificOptions) {
  12287. while (i--) {
  12288. point = points[i];
  12289. normalOptions = (point.options && point.options.marker) || point.options;
  12290. if (normalOptions && normalOptions.enabled === false) {
  12291. normalOptions.radius = 0;
  12292. }
  12293. if (zones.length) {
  12294. j = 0;
  12295. threshold = zones[j];
  12296. while (point[zoneAxis] >= threshold.value) {
  12297. threshold = zones[++j];
  12298. }
  12299. point.color = point.fillColor = pick(threshold.color, series.color); // #3636, #4267, #4430 - inherit color from series, when color is undefined
  12300. }
  12301. hasPointSpecificOptions = seriesOptions.colorByPoint || point.color; // #868
  12302. // check if the point has specific visual options
  12303. if (point.options) {
  12304. for (key in pointAttrToOptions) {
  12305. if (defined(normalOptions[pointAttrToOptions[key]])) {
  12306. hasPointSpecificOptions = true;
  12307. }
  12308. }
  12309. }
  12310. // a specific marker config object is defined for the individual point:
  12311. // create it's own attribute collection
  12312. if (hasPointSpecificOptions) {
  12313. normalOptions = normalOptions || {};
  12314. pointAttr = [];
  12315. stateOptions = normalOptions.states || {}; // reassign for individual point
  12316. pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {};
  12317. // Handle colors for column and pies
  12318. if (!seriesOptions.marker || (point.negative && !pointStateOptionsHover.fillColor && !stateOptionsHover.fillColor)) { // column, bar, point or negative threshold for series with markers (#3636)
  12319. // If no hover color is given, brighten the normal color. #1619, #2579
  12320. pointStateOptionsHover[series.pointAttrToOptions.fill] = pointStateOptionsHover.color || (!point.options.color && stateOptionsHover[(point.negative && seriesNegativeColor ? 'negativeColor' : 'color')]) ||
  12321. Color(point.color)
  12322. .brighten(pointStateOptionsHover.brightness || stateOptionsHover.brightness)
  12323. .get();
  12324. }
  12325. // normal point state inherits series wide normal state
  12326. attr = { color: point.color }; // #868
  12327. if (!defaultFillColor) { // Individual point color or negative color markers (#2219)
  12328. attr.fillColor = point.color;
  12329. }
  12330. if (!defaultLineColor) {
  12331. attr.lineColor = point.color; // Bubbles take point color, line markers use white
  12332. }
  12333. // Color is explicitly set to null or undefined (#1288, #4068)
  12334. if (normalOptions.hasOwnProperty('color') && !normalOptions.color) {
  12335. delete normalOptions.color;
  12336. }
  12337. pointAttr[NORMAL_STATE] = series.convertAttribs(extend(attr, normalOptions), seriesPointAttr[NORMAL_STATE]);
  12338. // inherit from point normal and series hover
  12339. pointAttr[HOVER_STATE] = series.convertAttribs(
  12340. stateOptions[HOVER_STATE],
  12341. seriesPointAttr[HOVER_STATE],
  12342. pointAttr[NORMAL_STATE]
  12343. );
  12344. // inherit from point normal and series hover
  12345. pointAttr[SELECT_STATE] = series.convertAttribs(
  12346. stateOptions[SELECT_STATE],
  12347. seriesPointAttr[SELECT_STATE],
  12348. pointAttr[NORMAL_STATE]
  12349. );
  12350. // no marker config object is created: copy a reference to the series-wide
  12351. // attribute collection
  12352. } else {
  12353. pointAttr = seriesPointAttr;
  12354. }
  12355. point.pointAttr = pointAttr;
  12356. }
  12357. }
  12358. },
  12359. /**
  12360. * Clear DOM objects and free up memory
  12361. */
  12362. destroy: function () {
  12363. var series = this,
  12364. chart = series.chart,
  12365. issue134 = /AppleWebKit\/533/.test(userAgent),
  12366. destroy,
  12367. i,
  12368. data = series.data || [],
  12369. point,
  12370. prop,
  12371. axis;
  12372. // add event hook
  12373. fireEvent(series, 'destroy');
  12374. // remove all events
  12375. removeEvent(series);
  12376. // erase from axes
  12377. each(series.axisTypes || [], function (AXIS) {
  12378. axis = series[AXIS];
  12379. if (axis) {
  12380. erase(axis.series, series);
  12381. axis.isDirty = axis.forceRedraw = true;
  12382. }
  12383. });
  12384. // remove legend items
  12385. if (series.legendItem) {
  12386. series.chart.legend.destroyItem(series);
  12387. }
  12388. // destroy all points with their elements
  12389. i = data.length;
  12390. while (i--) {
  12391. point = data[i];
  12392. if (point && point.destroy) {
  12393. point.destroy();
  12394. }
  12395. }
  12396. series.points = null;
  12397. // Clear the animation timeout if we are destroying the series during initial animation
  12398. clearTimeout(series.animationTimeout);
  12399. // Destroy all SVGElements associated to the series
  12400. for (prop in series) {
  12401. if (series[prop] instanceof SVGElement && !series[prop].survive) { // Survive provides a hook for not destroying
  12402. // issue 134 workaround
  12403. destroy = issue134 && prop === 'group' ?
  12404. 'hide' :
  12405. 'destroy';
  12406. series[prop][destroy]();
  12407. }
  12408. }
  12409. // remove from hoverSeries
  12410. if (chart.hoverSeries === series) {
  12411. chart.hoverSeries = null;
  12412. }
  12413. erase(chart.series, series);
  12414. // clear all members
  12415. for (prop in series) {
  12416. delete series[prop];
  12417. }
  12418. },
  12419. /**
  12420. * Return the graph path of a segment
  12421. */
  12422. getSegmentPath: function (segment) {
  12423. var series = this,
  12424. segmentPath = [],
  12425. step = series.options.step;
  12426. // build the segment line
  12427. each(segment, function (point, i) {
  12428. var plotX = point.plotX,
  12429. plotY = point.plotY,
  12430. lastPoint;
  12431. if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object
  12432. segmentPath.push.apply(segmentPath, series.getPointSpline(segment, point, i));
  12433. } else {
  12434. // moveTo or lineTo
  12435. segmentPath.push(i ? L : M);
  12436. // step line?
  12437. if (step && i) {
  12438. lastPoint = segment[i - 1];
  12439. if (step === 'right') {
  12440. segmentPath.push(
  12441. lastPoint.plotX,
  12442. plotY,
  12443. L
  12444. );
  12445. } else if (step === 'center') {
  12446. segmentPath.push(
  12447. (lastPoint.plotX + plotX) / 2,
  12448. lastPoint.plotY,
  12449. L,
  12450. (lastPoint.plotX + plotX) / 2,
  12451. plotY,
  12452. L
  12453. );
  12454. } else {
  12455. segmentPath.push(
  12456. plotX,
  12457. lastPoint.plotY,
  12458. L
  12459. );
  12460. }
  12461. }
  12462. // normal line to next point
  12463. segmentPath.push(
  12464. point.plotX,
  12465. point.plotY
  12466. );
  12467. }
  12468. });
  12469. return segmentPath;
  12470. },
  12471. /**
  12472. * Get the graph path
  12473. */
  12474. getGraphPath: function () {
  12475. var series = this,
  12476. graphPath = [],
  12477. segmentPath,
  12478. singlePoints = []; // used in drawTracker
  12479. // Divide into segments and build graph and area paths
  12480. each(series.segments, function (segment) {
  12481. segmentPath = series.getSegmentPath(segment);
  12482. // add the segment to the graph, or a single point for tracking
  12483. if (segment.length > 1) {
  12484. graphPath = graphPath.concat(segmentPath);
  12485. } else {
  12486. singlePoints.push(segment[0]);
  12487. }
  12488. });
  12489. // Record it for use in drawGraph and drawTracker, and return graphPath
  12490. series.singlePoints = singlePoints;
  12491. series.graphPath = graphPath;
  12492. return graphPath;
  12493. },
  12494. /**
  12495. * Draw the actual graph
  12496. */
  12497. drawGraph: function () {
  12498. var series = this,
  12499. options = this.options,
  12500. props = [['graph', options.lineColor || this.color, options.dashStyle]],
  12501. lineWidth = options.lineWidth,
  12502. roundCap = options.linecap !== 'square',
  12503. graphPath = this.getGraphPath(),
  12504. fillColor = (this.fillGraph && this.color) || NONE, // polygon series use filled graph
  12505. zones = this.zones;
  12506. each(zones, function (threshold, i) {
  12507. props.push(['zoneGraph' + i, threshold.color || series.color, threshold.dashStyle || options.dashStyle]);
  12508. });
  12509. // Draw the graph
  12510. each(props, function (prop, i) {
  12511. var graphKey = prop[0],
  12512. graph = series[graphKey],
  12513. attribs;
  12514. if (graph) {
  12515. graph.animate({ d: graphPath });
  12516. } else if ((lineWidth || fillColor) && graphPath.length) { // #1487
  12517. attribs = {
  12518. stroke: prop[1],
  12519. 'stroke-width': lineWidth,
  12520. fill: fillColor,
  12521. zIndex: 1 // #1069
  12522. };
  12523. if (prop[2]) {
  12524. attribs.dashstyle = prop[2];
  12525. } else if (roundCap) {
  12526. attribs['stroke-linecap'] = attribs['stroke-linejoin'] = 'round';
  12527. }
  12528. series[graphKey] = series.chart.renderer.path(graphPath)
  12529. .attr(attribs)
  12530. .add(series.group)
  12531. .shadow((i < 2) && options.shadow); // add shadow to normal series (0) or to first zone (1) #3932
  12532. }
  12533. });
  12534. },
  12535. /**
  12536. * Clip the graphs into the positive and negative coloured graphs
  12537. */
  12538. applyZones: function () {
  12539. var series = this,
  12540. chart = this.chart,
  12541. renderer = chart.renderer,
  12542. zones = this.zones,
  12543. translatedFrom,
  12544. translatedTo,
  12545. clips = this.clips || [],
  12546. clipAttr,
  12547. graph = this.graph,
  12548. area = this.area,
  12549. chartSizeMax = mathMax(chart.chartWidth, chart.chartHeight),
  12550. axis = this[(this.zoneAxis || 'y') + 'Axis'],
  12551. extremes,
  12552. reversed = axis.reversed,
  12553. inverted = chart.inverted,
  12554. horiz = axis.horiz,
  12555. pxRange,
  12556. pxPosMin,
  12557. pxPosMax,
  12558. ignoreZones = false;
  12559. if (zones.length && (graph || area) && axis.min !== UNDEFINED) {
  12560. // The use of the Color Threshold assumes there are no gaps
  12561. // so it is safe to hide the original graph and area
  12562. if (graph) {
  12563. graph.hide();
  12564. }
  12565. if (area) {
  12566. area.hide();
  12567. }
  12568. // Create the clips
  12569. extremes = axis.getExtremes();
  12570. each(zones, function (threshold, i) {
  12571. translatedFrom = reversed ?
  12572. (horiz ? chart.plotWidth : 0) :
  12573. (horiz ? 0 : axis.toPixels(extremes.min));
  12574. translatedFrom = mathMin(mathMax(pick(translatedTo, translatedFrom), 0), chartSizeMax);
  12575. translatedTo = mathMin(mathMax(mathRound(axis.toPixels(pick(threshold.value, extremes.max), true)), 0), chartSizeMax);
  12576. if (ignoreZones) {
  12577. translatedFrom = translatedTo = axis.toPixels(extremes.max);
  12578. }
  12579. pxRange = Math.abs(translatedFrom - translatedTo);
  12580. pxPosMin = mathMin(translatedFrom, translatedTo);
  12581. pxPosMax = mathMax(translatedFrom, translatedTo);
  12582. if (axis.isXAxis) {
  12583. clipAttr = {
  12584. x: inverted ? pxPosMax : pxPosMin,
  12585. y: 0,
  12586. width: pxRange,
  12587. height: chartSizeMax
  12588. };
  12589. if (!horiz) {
  12590. clipAttr.x = chart.plotHeight - clipAttr.x;
  12591. }
  12592. } else {
  12593. clipAttr = {
  12594. x: 0,
  12595. y: inverted ? pxPosMax : pxPosMin,
  12596. width: chartSizeMax,
  12597. height: pxRange
  12598. };
  12599. if (horiz) {
  12600. clipAttr.y = chart.plotWidth - clipAttr.y;
  12601. }
  12602. }
  12603. /// VML SUPPPORT
  12604. if (chart.inverted && renderer.isVML) {
  12605. if (axis.isXAxis) {
  12606. clipAttr = {
  12607. x: 0,
  12608. y: reversed ? pxPosMin : pxPosMax,
  12609. height: clipAttr.width,
  12610. width: chart.chartWidth
  12611. };
  12612. } else {
  12613. clipAttr = {
  12614. x: clipAttr.y - chart.plotLeft - chart.spacingBox.x,
  12615. y: 0,
  12616. width: clipAttr.height,
  12617. height: chart.chartHeight
  12618. };
  12619. }
  12620. }
  12621. /// END OF VML SUPPORT
  12622. if (clips[i]) {
  12623. clips[i].animate(clipAttr);
  12624. } else {
  12625. clips[i] = renderer.clipRect(clipAttr);
  12626. if (graph) {
  12627. series['zoneGraph' + i].clip(clips[i]);
  12628. }
  12629. if (area) {
  12630. series['zoneArea' + i].clip(clips[i]);
  12631. }
  12632. }
  12633. // if this zone extends out of the axis, ignore the others
  12634. ignoreZones = threshold.value > extremes.max;
  12635. });
  12636. this.clips = clips;
  12637. }
  12638. },
  12639. /**
  12640. * Initialize and perform group inversion on series.group and series.markerGroup
  12641. */
  12642. invertGroups: function () {
  12643. var series = this,
  12644. chart = series.chart;
  12645. // Pie, go away (#1736)
  12646. if (!series.xAxis) {
  12647. return;
  12648. }
  12649. // A fixed size is needed for inversion to work
  12650. function setInvert() {
  12651. var size = {
  12652. width: series.yAxis.len,
  12653. height: series.xAxis.len
  12654. };
  12655. each(['group', 'markerGroup'], function (groupName) {
  12656. if (series[groupName]) {
  12657. series[groupName].attr(size).invert();
  12658. }
  12659. });
  12660. }
  12661. addEvent(chart, 'resize', setInvert); // do it on resize
  12662. addEvent(series, 'destroy', function () {
  12663. removeEvent(chart, 'resize', setInvert);
  12664. });
  12665. // Do it now
  12666. setInvert(); // do it now
  12667. // On subsequent render and redraw, just do setInvert without setting up events again
  12668. series.invertGroups = setInvert;
  12669. },
  12670. /**
  12671. * General abstraction for creating plot groups like series.group, series.dataLabelsGroup and
  12672. * series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size.
  12673. */
  12674. plotGroup: function (prop, name, visibility, zIndex, parent) {
  12675. var group = this[prop],
  12676. isNew = !group;
  12677. // Generate it on first call
  12678. if (isNew) {
  12679. this[prop] = group = this.chart.renderer.g(name)
  12680. .attr({
  12681. visibility: visibility,
  12682. zIndex: zIndex || 0.1 // IE8 needs this
  12683. })
  12684. .add(parent);
  12685. group.addClass('highcharts-series-' + this.index);
  12686. }
  12687. // Place it on first and subsequent (redraw) calls
  12688. group[isNew ? 'attr' : 'animate'](this.getPlotBox());
  12689. return group;
  12690. },
  12691. /**
  12692. * Get the translation and scale for the plot area of this series
  12693. */
  12694. getPlotBox: function () {
  12695. var chart = this.chart,
  12696. xAxis = this.xAxis,
  12697. yAxis = this.yAxis;
  12698. // Swap axes for inverted (#2339)
  12699. if (chart.inverted) {
  12700. xAxis = yAxis;
  12701. yAxis = this.xAxis;
  12702. }
  12703. return {
  12704. translateX: xAxis ? xAxis.left : chart.plotLeft,
  12705. translateY: yAxis ? yAxis.top : chart.plotTop,
  12706. scaleX: 1, // #1623
  12707. scaleY: 1
  12708. };
  12709. },
  12710. /**
  12711. * Render the graph and markers
  12712. */
  12713. render: function () {
  12714. var series = this,
  12715. chart = series.chart,
  12716. group,
  12717. options = series.options,
  12718. animation = options.animation,
  12719. // Animation doesn't work in IE8 quirks when the group div is hidden,
  12720. // and looks bad in other oldIE
  12721. animDuration = (animation && !!series.animate && chart.renderer.isSVG && pick(animation.duration, 500)) || 0,
  12722. visibility = series.visible ? VISIBLE : HIDDEN,
  12723. zIndex = options.zIndex,
  12724. hasRendered = series.hasRendered,
  12725. chartSeriesGroup = chart.seriesGroup;
  12726. // the group
  12727. group = series.plotGroup(
  12728. 'group',
  12729. 'series',
  12730. visibility,
  12731. zIndex,
  12732. chartSeriesGroup
  12733. );
  12734. series.markerGroup = series.plotGroup(
  12735. 'markerGroup',
  12736. 'markers',
  12737. visibility,
  12738. zIndex,
  12739. chartSeriesGroup
  12740. );
  12741. // initiate the animation
  12742. if (animDuration) {
  12743. series.animate(true);
  12744. }
  12745. // cache attributes for shapes
  12746. series.getAttribs();
  12747. // SVGRenderer needs to know this before drawing elements (#1089, #1795)
  12748. group.inverted = series.isCartesian ? chart.inverted : false;
  12749. // draw the graph if any
  12750. if (series.drawGraph) {
  12751. series.drawGraph();
  12752. series.applyZones();
  12753. }
  12754. each(series.points, function (point) {
  12755. if (point.redraw) {
  12756. point.redraw();
  12757. }
  12758. });
  12759. // draw the data labels (inn pies they go before the points)
  12760. if (series.drawDataLabels) {
  12761. series.drawDataLabels();
  12762. }
  12763. // draw the points
  12764. if (series.visible) {
  12765. series.drawPoints();
  12766. }
  12767. // draw the mouse tracking area
  12768. if (series.drawTracker && series.options.enableMouseTracking !== false) {
  12769. series.drawTracker();
  12770. }
  12771. // Handle inverted series and tracker groups
  12772. if (chart.inverted) {
  12773. series.invertGroups();
  12774. }
  12775. // Initial clipping, must be defined after inverting groups for VML. Applies to columns etc. (#3839).
  12776. if (options.clip !== false && !series.sharedClipKey && !hasRendered) {
  12777. group.clip(chart.clipRect);
  12778. }
  12779. // Run the animation
  12780. if (animDuration) {
  12781. series.animate();
  12782. }
  12783. // Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option
  12784. // which should be available to the user).
  12785. if (!hasRendered) {
  12786. if (animDuration) {
  12787. series.animationTimeout = setTimeout(function () {
  12788. series.afterAnimate();
  12789. }, animDuration);
  12790. } else {
  12791. series.afterAnimate();
  12792. }
  12793. }
  12794. series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
  12795. // (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
  12796. series.hasRendered = true;
  12797. },
  12798. /**
  12799. * Redraw the series after an update in the axes.
  12800. */
  12801. redraw: function () {
  12802. var series = this,
  12803. chart = series.chart,
  12804. wasDirtyData = series.isDirtyData, // cache it here as it is set to false in render, but used after
  12805. wasDirty = series.isDirty,
  12806. group = series.group,
  12807. xAxis = series.xAxis,
  12808. yAxis = series.yAxis;
  12809. // reposition on resize
  12810. if (group) {
  12811. if (chart.inverted) {
  12812. group.attr({
  12813. width: chart.plotWidth,
  12814. height: chart.plotHeight
  12815. });
  12816. }
  12817. group.animate({
  12818. translateX: pick(xAxis && xAxis.left, chart.plotLeft),
  12819. translateY: pick(yAxis && yAxis.top, chart.plotTop)
  12820. });
  12821. }
  12822. series.translate();
  12823. series.render();
  12824. if (wasDirtyData) {
  12825. fireEvent(series, 'updatedData');
  12826. }
  12827. if (wasDirty || wasDirtyData) { // #3945 recalculate the kdtree when dirty
  12828. delete this.kdTree; // #3868 recalculate the kdtree with dirty data
  12829. }
  12830. },
  12831. /**
  12832. * KD Tree && PointSearching Implementation
  12833. */
  12834. kdDimensions: 1,
  12835. kdAxisArray: ['clientX', 'plotY'],
  12836. searchPoint: function (e, compareX) {
  12837. var series = this,
  12838. xAxis = series.xAxis,
  12839. yAxis = series.yAxis,
  12840. inverted = series.chart.inverted;
  12841. return this.searchKDTree({
  12842. clientX: inverted ? xAxis.len - e.chartY + xAxis.pos : e.chartX - xAxis.pos,
  12843. plotY: inverted ? yAxis.len - e.chartX + yAxis.pos : e.chartY - yAxis.pos
  12844. }, compareX);
  12845. },
  12846. buildKDTree: function () {
  12847. var series = this,
  12848. dimensions = series.kdDimensions;
  12849. // Internal function
  12850. function _kdtree(points, depth, dimensions) {
  12851. var axis, median, length = points && points.length;
  12852. if (length) {
  12853. // alternate between the axis
  12854. axis = series.kdAxisArray[depth % dimensions];
  12855. // sort point array
  12856. points.sort(function(a, b) {
  12857. return a[axis] - b[axis];
  12858. });
  12859. median = Math.floor(length / 2);
  12860. // build and return nod
  12861. return {
  12862. point: points[median],
  12863. left: _kdtree(points.slice(0, median), depth + 1, dimensions),
  12864. right: _kdtree(points.slice(median + 1), depth + 1, dimensions)
  12865. };
  12866. }
  12867. }
  12868. // Start the recursive build process with a clone of the points array and null points filtered out (#3873)
  12869. function startRecursive() {
  12870. var points = grep(series.points || [], function (point) { // #4390
  12871. return point.y !== null;
  12872. });
  12873. series.kdTree = _kdtree(points, dimensions, dimensions);
  12874. }
  12875. delete series.kdTree;
  12876. if (series.options.kdSync) { // For testing tooltips, don't build async
  12877. startRecursive();
  12878. } else {
  12879. setTimeout(startRecursive);
  12880. }
  12881. },
  12882. searchKDTree: function (point, compareX) {
  12883. var series = this,
  12884. kdX = this.kdAxisArray[0],
  12885. kdY = this.kdAxisArray[1],
  12886. kdComparer = compareX ? 'distX' : 'dist';
  12887. // Set the one and two dimensional distance on the point object
  12888. function setDistance(p1, p2) {
  12889. var x = (defined(p1[kdX]) && defined(p2[kdX])) ? Math.pow(p1[kdX] - p2[kdX], 2) : null,
  12890. y = (defined(p1[kdY]) && defined(p2[kdY])) ? Math.pow(p1[kdY] - p2[kdY], 2) : null,
  12891. r = (x || 0) + (y || 0);
  12892. p2.dist = defined(r) ? Math.sqrt(r) : Number.MAX_VALUE;
  12893. p2.distX = defined(x) ? Math.sqrt(x) : Number.MAX_VALUE;
  12894. }
  12895. function _search(search, tree, depth, dimensions) {
  12896. var point = tree.point,
  12897. axis = series.kdAxisArray[depth % dimensions],
  12898. tdist,
  12899. sideA,
  12900. sideB,
  12901. ret = point,
  12902. nPoint1,
  12903. nPoint2;
  12904. setDistance(search, point);
  12905. // Pick side based on distance to splitting point
  12906. tdist = search[axis] - point[axis];
  12907. sideA = tdist < 0 ? 'left' : 'right';
  12908. sideB = tdist < 0 ? 'right' : 'left';
  12909. // End of tree
  12910. if (tree[sideA]) {
  12911. nPoint1 =_search(search, tree[sideA], depth + 1, dimensions);
  12912. ret = (nPoint1[kdComparer] < ret[kdComparer] ? nPoint1 : point);
  12913. }
  12914. if (tree[sideB]) {
  12915. // compare distance to current best to splitting point to decide wether to check side B or not
  12916. if (Math.sqrt(tdist * tdist) < ret[kdComparer]) {
  12917. nPoint2 = _search(search, tree[sideB], depth + 1, dimensions);
  12918. ret = (nPoint2[kdComparer] < ret[kdComparer] ? nPoint2 : ret);
  12919. }
  12920. }
  12921. return ret;
  12922. }
  12923. if (!this.kdTree) {
  12924. this.buildKDTree();
  12925. }
  12926. if (this.kdTree) {
  12927. return _search(point,
  12928. this.kdTree, this.kdDimensions, this.kdDimensions);
  12929. }
  12930. }
  12931. }; // end Series prototype
  12932. /**
  12933. * The class for stack items
  12934. */
  12935. function StackItem(axis, options, isNegative, x, stackOption) {
  12936. var inverted = axis.chart.inverted;
  12937. this.axis = axis;
  12938. // Tells if the stack is negative
  12939. this.isNegative = isNegative;
  12940. // Save the options to be able to style the label
  12941. this.options = options;
  12942. // Save the x value to be able to position the label later
  12943. this.x = x;
  12944. // Initialize total value
  12945. this.total = null;
  12946. // This will keep each points' extremes stored by series.index and point index
  12947. this.points = {};
  12948. // Save the stack option on the series configuration object, and whether to treat it as percent
  12949. this.stack = stackOption;
  12950. // The align options and text align varies on whether the stack is negative and
  12951. // if the chart is inverted or not.
  12952. // First test the user supplied value, then use the dynamic.
  12953. this.alignOptions = {
  12954. align: options.align || (inverted ? (isNegative ? 'left' : 'right') : 'center'),
  12955. verticalAlign: options.verticalAlign || (inverted ? 'middle' : (isNegative ? 'bottom' : 'top')),
  12956. y: pick(options.y, inverted ? 4 : (isNegative ? 14 : -6)),
  12957. x: pick(options.x, inverted ? (isNegative ? -6 : 6) : 0)
  12958. };
  12959. this.textAlign = options.textAlign || (inverted ? (isNegative ? 'right' : 'left') : 'center');
  12960. }
  12961. StackItem.prototype = {
  12962. destroy: function () {
  12963. destroyObjectProperties(this, this.axis);
  12964. },
  12965. /**
  12966. * Renders the stack total label and adds it to the stack label group.
  12967. */
  12968. render: function (group) {
  12969. var options = this.options,
  12970. formatOption = options.format,
  12971. str = formatOption ?
  12972. format(formatOption, this) :
  12973. options.formatter.call(this); // format the text in the label
  12974. // Change the text to reflect the new total and set visibility to hidden in case the serie is hidden
  12975. if (this.label) {
  12976. this.label.attr({text: str, visibility: HIDDEN});
  12977. // Create new label
  12978. } else {
  12979. this.label =
  12980. this.axis.chart.renderer.text(str, null, null, options.useHTML) // dummy positions, actual position updated with setOffset method in columnseries
  12981. .css(options.style) // apply style
  12982. .attr({
  12983. align: this.textAlign, // fix the text-anchor
  12984. rotation: options.rotation, // rotation
  12985. visibility: HIDDEN // hidden until setOffset is called
  12986. })
  12987. .add(group); // add to the labels-group
  12988. }
  12989. },
  12990. /**
  12991. * Sets the offset that the stack has from the x value and repositions the label.
  12992. */
  12993. setOffset: function (xOffset, xWidth) {
  12994. var stackItem = this,
  12995. axis = stackItem.axis,
  12996. chart = axis.chart,
  12997. inverted = chart.inverted,
  12998. reversed = axis.reversed,
  12999. neg = (this.isNegative && !reversed) || (!this.isNegative && reversed), // #4056
  13000. y = axis.translate(axis.usePercentage ? 100 : this.total, 0, 0, 0, 1), // stack value translated mapped to chart coordinates
  13001. yZero = axis.translate(0), // stack origin
  13002. h = mathAbs(y - yZero), // stack height
  13003. x = chart.xAxis[0].translate(this.x) + xOffset, // stack x position
  13004. plotHeight = chart.plotHeight,
  13005. stackBox = { // this is the box for the complete stack
  13006. x: inverted ? (neg ? y : y - h) : x,
  13007. y: inverted ? plotHeight - x - xWidth : (neg ? (plotHeight - y - h) : plotHeight - y),
  13008. width: inverted ? h : xWidth,
  13009. height: inverted ? xWidth : h
  13010. },
  13011. label = this.label,
  13012. alignAttr;
  13013. if (label) {
  13014. label.align(this.alignOptions, null, stackBox); // align the label to the box
  13015. // Set visibility (#678)
  13016. alignAttr = label.alignAttr;
  13017. label[this.options.crop === false || chart.isInsidePlot(alignAttr.x, alignAttr.y) ? 'show' : 'hide'](true);
  13018. }
  13019. }
  13020. };
  13021. /**
  13022. * Generate stacks for each series and calculate stacks total values
  13023. */
  13024. Chart.prototype.getStacks = function () {
  13025. var chart = this;
  13026. // reset stacks for each yAxis
  13027. each(chart.yAxis, function (axis) {
  13028. if (axis.stacks && axis.hasVisibleSeries) {
  13029. axis.oldStacks = axis.stacks;
  13030. }
  13031. });
  13032. each(chart.series, function (series) {
  13033. if (series.options.stacking && (series.visible === true || chart.options.chart.ignoreHiddenSeries === false)) {
  13034. series.stackKey = series.type + pick(series.options.stack, '');
  13035. }
  13036. });
  13037. };
  13038. // Stacking methods defined on the Axis prototype
  13039. /**
  13040. * Build the stacks from top down
  13041. */
  13042. Axis.prototype.buildStacks = function () {
  13043. var series = this.series,
  13044. reversedStacks = pick(this.options.reversedStacks, true),
  13045. i = series.length;
  13046. if (!this.isXAxis) {
  13047. this.usePercentage = false;
  13048. while (i--) {
  13049. series[reversedStacks ? i : series.length - i - 1].setStackedPoints();
  13050. }
  13051. // Loop up again to compute percent stack
  13052. if (this.usePercentage) {
  13053. for (i = 0; i < series.length; i++) {
  13054. series[i].setPercentStacks();
  13055. }
  13056. }
  13057. }
  13058. };
  13059. Axis.prototype.renderStackTotals = function () {
  13060. var axis = this,
  13061. chart = axis.chart,
  13062. renderer = chart.renderer,
  13063. stacks = axis.stacks,
  13064. stackKey,
  13065. oneStack,
  13066. stackCategory,
  13067. stackTotalGroup = axis.stackTotalGroup;
  13068. // Create a separate group for the stack total labels
  13069. if (!stackTotalGroup) {
  13070. axis.stackTotalGroup = stackTotalGroup =
  13071. renderer.g('stack-labels')
  13072. .attr({
  13073. visibility: VISIBLE,
  13074. zIndex: 6
  13075. })
  13076. .add();
  13077. }
  13078. // plotLeft/Top will change when y axis gets wider so we need to translate the
  13079. // stackTotalGroup at every render call. See bug #506 and #516
  13080. stackTotalGroup.translate(chart.plotLeft, chart.plotTop);
  13081. // Render each stack total
  13082. for (stackKey in stacks) {
  13083. oneStack = stacks[stackKey];
  13084. for (stackCategory in oneStack) {
  13085. oneStack[stackCategory].render(stackTotalGroup);
  13086. }
  13087. }
  13088. };
  13089. /**
  13090. * Set all the stacks to initial states and destroy unused ones.
  13091. */
  13092. Axis.prototype.resetStacks = function () {
  13093. var stacks = this.stacks,
  13094. type,
  13095. i;
  13096. if (!this.isXAxis) {
  13097. for (type in stacks) {
  13098. for (i in stacks[type]) {
  13099. // Clean up memory after point deletion (#1044, #4320)
  13100. if (stacks[type][i].touched < this.stacksTouched) {
  13101. stacks[type][i].destroy();
  13102. delete stacks[type][i];
  13103. // Reset stacks
  13104. } else {
  13105. stacks[type][i].total = null;
  13106. stacks[type][i].cum = 0;
  13107. }
  13108. }
  13109. }
  13110. }
  13111. };
  13112. Axis.prototype.cleanStacks = function () {
  13113. var stacks, type, i;
  13114. if (!this.isXAxis) {
  13115. if (this.oldStacks) {
  13116. stacks = this.stacks = this.oldStacks;
  13117. }
  13118. // reset stacks
  13119. for (type in stacks) {
  13120. for (i in stacks[type]) {
  13121. stacks[type][i].cum = stacks[type][i].total;
  13122. }
  13123. }
  13124. }
  13125. };
  13126. // Stacking methods defnied for Series prototype
  13127. /**
  13128. * Adds series' points value to corresponding stack
  13129. */
  13130. Series.prototype.setStackedPoints = function () {
  13131. if (!this.options.stacking || (this.visible !== true && this.chart.options.chart.ignoreHiddenSeries !== false)) {
  13132. return;
  13133. }
  13134. var series = this,
  13135. xData = series.processedXData,
  13136. yData = series.processedYData,
  13137. stackedYData = [],
  13138. yDataLength = yData.length,
  13139. seriesOptions = series.options,
  13140. threshold = seriesOptions.threshold,
  13141. stackThreshold = seriesOptions.startFromThreshold ? threshold : 0,
  13142. stackOption = seriesOptions.stack,
  13143. stacking = seriesOptions.stacking,
  13144. stackKey = series.stackKey,
  13145. negKey = '-' + stackKey,
  13146. negStacks = series.negStacks,
  13147. yAxis = series.yAxis,
  13148. stacks = yAxis.stacks,
  13149. oldStacks = yAxis.oldStacks,
  13150. stackIndicator,
  13151. isNegative,
  13152. stack,
  13153. other,
  13154. key,
  13155. pointKey,
  13156. i,
  13157. x,
  13158. y;
  13159. yAxis.stacksTouched += 1;
  13160. // loop over the non-null y values and read them into a local array
  13161. for (i = 0; i < yDataLength; i++) {
  13162. x = xData[i];
  13163. y = yData[i];
  13164. stackIndicator = series.getStackIndicator(stackIndicator, x, series.index);
  13165. pointKey = stackIndicator.key;
  13166. // Read stacked values into a stack based on the x value,
  13167. // the sign of y and the stack key. Stacking is also handled for null values (#739)
  13168. isNegative = negStacks && y < (stackThreshold ? 0 : threshold);
  13169. key = isNegative ? negKey : stackKey;
  13170. // Create empty object for this stack if it doesn't exist yet
  13171. if (!stacks[key]) {
  13172. stacks[key] = {};
  13173. }
  13174. // Initialize StackItem for this x
  13175. if (!stacks[key][x]) {
  13176. if (oldStacks[key] && oldStacks[key][x]) {
  13177. stacks[key][x] = oldStacks[key][x];
  13178. stacks[key][x].total = null;
  13179. } else {
  13180. stacks[key][x] = new StackItem(yAxis, yAxis.options.stackLabels, isNegative, x, stackOption);
  13181. }
  13182. }
  13183. // If the StackItem doesn't exist, create it first
  13184. stack = stacks[key][x];
  13185. //stack.points[pointKey] = [stack.cum || stackThreshold];
  13186. stack.points[pointKey] = [pick(stack.cum, stackThreshold)];
  13187. stack.touched = yAxis.stacksTouched;
  13188. // Add value to the stack total
  13189. if (stacking === 'percent') {
  13190. // Percent stacked column, totals are the same for the positive and negative stacks
  13191. other = isNegative ? stackKey : negKey;
  13192. if (negStacks && stacks[other] && stacks[other][x]) {
  13193. other = stacks[other][x];
  13194. stack.total = other.total = mathMax(other.total, stack.total) + mathAbs(y) || 0;
  13195. // Percent stacked areas
  13196. } else {
  13197. stack.total = correctFloat(stack.total + (mathAbs(y) || 0));
  13198. }
  13199. } else {
  13200. stack.total = correctFloat(stack.total + (y || 0));
  13201. }
  13202. stack.cum = pick(stack.cum, stackThreshold) + (y || 0);
  13203. stack.points[pointKey].push(stack.cum);
  13204. stackedYData[i] = stack.cum;
  13205. }
  13206. if (stacking === 'percent') {
  13207. yAxis.usePercentage = true;
  13208. }
  13209. this.stackedYData = stackedYData; // To be used in getExtremes
  13210. // Reset old stacks
  13211. yAxis.oldStacks = {};
  13212. };
  13213. /**
  13214. * Iterate over all stacks and compute the absolute values to percent
  13215. */
  13216. Series.prototype.setPercentStacks = function () {
  13217. var series = this,
  13218. stackKey = series.stackKey,
  13219. stacks = series.yAxis.stacks,
  13220. processedXData = series.processedXData,
  13221. stackIndicator;
  13222. each([stackKey, '-' + stackKey], function (key) {
  13223. var i = processedXData.length,
  13224. x,
  13225. stack,
  13226. pointExtremes,
  13227. totalFactor;
  13228. while (i--) {
  13229. x = processedXData[i];
  13230. stackIndicator = series.getStackIndicator(stackIndicator, x, series.index);
  13231. stack = stacks[key] && stacks[key][x];
  13232. pointExtremes = stack && stack.points[stackIndicator.key];
  13233. if (pointExtremes) {
  13234. totalFactor = stack.total ? 100 / stack.total : 0;
  13235. pointExtremes[0] = correctFloat(pointExtremes[0] * totalFactor); // Y bottom value
  13236. pointExtremes[1] = correctFloat(pointExtremes[1] * totalFactor); // Y value
  13237. series.stackedYData[i] = pointExtremes[1];
  13238. }
  13239. }
  13240. });
  13241. };
  13242. /**
  13243. * Get stack indicator, according to it's x-value, to determine points with the same x-value
  13244. */
  13245. Series.prototype.getStackIndicator = function(stackIndicator, x, index) {
  13246. if (!defined(stackIndicator) || stackIndicator.x !== x) {
  13247. stackIndicator = {
  13248. x: x,
  13249. index: 0
  13250. };
  13251. } else {
  13252. stackIndicator.index++;
  13253. }
  13254. stackIndicator.key = [index, x, stackIndicator.index].join(',');
  13255. return stackIndicator;
  13256. };
  13257. // Extend the Chart prototype for dynamic methods
  13258. extend(Chart.prototype, {
  13259. /**
  13260. * Add a series dynamically after time
  13261. *
  13262. * @param {Object} options The config options
  13263. * @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true.
  13264. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  13265. * configuration
  13266. *
  13267. * @return {Object} series The newly created series object
  13268. */
  13269. addSeries: function (options, redraw, animation) {
  13270. var series,
  13271. chart = this;
  13272. if (options) {
  13273. redraw = pick(redraw, true); // defaults to true
  13274. fireEvent(chart, 'addSeries', { options: options }, function () {
  13275. series = chart.initSeries(options);
  13276. chart.isDirtyLegend = true; // the series array is out of sync with the display
  13277. chart.linkSeries();
  13278. if (redraw) {
  13279. chart.redraw(animation);
  13280. }
  13281. });
  13282. }
  13283. return series;
  13284. },
  13285. /**
  13286. * Add an axis to the chart
  13287. * @param {Object} options The axis option
  13288. * @param {Boolean} isX Whether it is an X axis or a value axis
  13289. */
  13290. addAxis: function (options, isX, redraw, animation) {
  13291. var key = isX ? 'xAxis' : 'yAxis',
  13292. chartOptions = this.options,
  13293. axis;
  13294. /*jslint unused: false*/
  13295. axis = new Axis(this, merge(options, {
  13296. index: this[key].length,
  13297. isX: isX
  13298. }));
  13299. /*jslint unused: true*/
  13300. // Push the new axis options to the chart options
  13301. chartOptions[key] = splat(chartOptions[key] || {});
  13302. chartOptions[key].push(options);
  13303. if (pick(redraw, true)) {
  13304. this.redraw(animation);
  13305. }
  13306. },
  13307. /**
  13308. * Dim the chart and show a loading text or symbol
  13309. * @param {String} str An optional text to show in the loading label instead of the default one
  13310. */
  13311. showLoading: function (str) {
  13312. var chart = this,
  13313. options = chart.options,
  13314. loadingDiv = chart.loadingDiv,
  13315. loadingOptions = options.loading,
  13316. setLoadingSize = function () {
  13317. if (loadingDiv) {
  13318. css(loadingDiv, {
  13319. left: chart.plotLeft + PX,
  13320. top: chart.plotTop + PX,
  13321. width: chart.plotWidth + PX,
  13322. height: chart.plotHeight + PX
  13323. });
  13324. }
  13325. };
  13326. // create the layer at the first call
  13327. if (!loadingDiv) {
  13328. chart.loadingDiv = loadingDiv = createElement(DIV, {
  13329. className: PREFIX + 'loading'
  13330. }, extend(loadingOptions.style, {
  13331. zIndex: 10,
  13332. display: NONE
  13333. }), chart.container);
  13334. chart.loadingSpan = createElement(
  13335. 'span',
  13336. null,
  13337. loadingOptions.labelStyle,
  13338. loadingDiv
  13339. );
  13340. addEvent(chart, 'redraw', setLoadingSize); // #1080
  13341. }
  13342. // update text
  13343. chart.loadingSpan.innerHTML = str || options.lang.loading;
  13344. // show it
  13345. if (!chart.loadingShown) {
  13346. css(loadingDiv, {
  13347. opacity: 0,
  13348. display: ''
  13349. });
  13350. animate(loadingDiv, {
  13351. opacity: loadingOptions.style.opacity
  13352. }, {
  13353. duration: loadingOptions.showDuration || 0
  13354. });
  13355. chart.loadingShown = true;
  13356. }
  13357. setLoadingSize();
  13358. },
  13359. /**
  13360. * Hide the loading layer
  13361. */
  13362. hideLoading: function () {
  13363. var options = this.options,
  13364. loadingDiv = this.loadingDiv;
  13365. if (loadingDiv) {
  13366. animate(loadingDiv, {
  13367. opacity: 0
  13368. }, {
  13369. duration: options.loading.hideDuration || 100,
  13370. complete: function () {
  13371. css(loadingDiv, { display: NONE });
  13372. }
  13373. });
  13374. }
  13375. this.loadingShown = false;
  13376. }
  13377. });
  13378. // extend the Point prototype for dynamic methods
  13379. extend(Point.prototype, {
  13380. /**
  13381. * Update the point with new options (typically x/y data) and optionally redraw the series.
  13382. *
  13383. * @param {Object} options Point options as defined in the series.data array
  13384. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  13385. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  13386. * configuration
  13387. *
  13388. */
  13389. update: function (options, redraw, animation, runEvent) {
  13390. var point = this,
  13391. series = point.series,
  13392. graphic = point.graphic,
  13393. i,
  13394. chart = series.chart,
  13395. seriesOptions = series.options,
  13396. names = series.xAxis && series.xAxis.names;
  13397. redraw = pick(redraw, true);
  13398. function update() {
  13399. point.applyOptions(options);
  13400. // Update visuals
  13401. if (point.y === null && graphic) { // #4146
  13402. point.graphic = graphic.destroy();
  13403. }
  13404. if (isObject(options) && !isArray(options)) {
  13405. // Defer the actual redraw until getAttribs has been called (#3260)
  13406. point.redraw = function () {
  13407. if (graphic && graphic.element) {
  13408. if (options && options.marker && options.marker.symbol) {
  13409. point.graphic = graphic.destroy();
  13410. }
  13411. }
  13412. if (options && options.dataLabels && point.dataLabel) { // #2468
  13413. point.dataLabel = point.dataLabel.destroy();
  13414. }
  13415. point.redraw = null;
  13416. };
  13417. }
  13418. // record changes in the parallel arrays
  13419. i = point.index;
  13420. series.updateParallelArrays(point, i);
  13421. if (names && point.name) {
  13422. names[point.x] = point.name;
  13423. }
  13424. seriesOptions.data[i] = point.options;
  13425. // redraw
  13426. series.isDirty = series.isDirtyData = true;
  13427. if (!series.fixedBox && series.hasCartesianSeries) { // #1906, #2320
  13428. chart.isDirtyBox = true;
  13429. }
  13430. if (seriesOptions.legendType === 'point') { // #1831, #1885
  13431. chart.isDirtyLegend = true;
  13432. }
  13433. if (redraw) {
  13434. chart.redraw(animation);
  13435. }
  13436. }
  13437. // Fire the event with a default handler of doing the update
  13438. if (runEvent === false) { // When called from setData
  13439. update();
  13440. } else {
  13441. point.firePointEvent('update', { options: options }, update);
  13442. }
  13443. },
  13444. /**
  13445. * Remove a point and optionally redraw the series and if necessary the axes
  13446. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  13447. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  13448. * configuration
  13449. */
  13450. remove: function (redraw, animation) {
  13451. this.series.removePoint(inArray(this, this.series.data), redraw, animation);
  13452. }
  13453. });
  13454. // Extend the series prototype for dynamic methods
  13455. extend(Series.prototype, {
  13456. /**
  13457. * Add a point dynamically after chart load time
  13458. * @param {Object} options Point options as given in series.data
  13459. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  13460. * @param {Boolean} shift If shift is true, a point is shifted off the start
  13461. * of the series as one is appended to the end.
  13462. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  13463. * configuration
  13464. */
  13465. addPoint: function (options, redraw, shift, animation) {
  13466. var series = this,
  13467. seriesOptions = series.options,
  13468. data = series.data,
  13469. graph = series.graph,
  13470. area = series.area,
  13471. chart = series.chart,
  13472. names = series.xAxis && series.xAxis.names,
  13473. currentShift = (graph && graph.shift) || 0,
  13474. shiftShapes = ['graph', 'area'],
  13475. dataOptions = seriesOptions.data,
  13476. point,
  13477. isInTheMiddle,
  13478. xData = series.xData,
  13479. i,
  13480. x;
  13481. setAnimation(animation, chart);
  13482. // Make graph animate sideways
  13483. if (shift) {
  13484. i = series.zones.length;
  13485. while (i--) {
  13486. shiftShapes.push('zoneGraph' + i, 'zoneArea' + i);
  13487. }
  13488. each(shiftShapes, function (shape) {
  13489. if (series[shape]) {
  13490. series[shape].shift = currentShift + (seriesOptions.step ? 2 : 1);
  13491. }
  13492. });
  13493. }
  13494. if (area) {
  13495. area.isArea = true; // needed in animation, both with and without shift
  13496. }
  13497. // Optional redraw, defaults to true
  13498. redraw = pick(redraw, true);
  13499. // Get options and push the point to xData, yData and series.options. In series.generatePoints
  13500. // the Point instance will be created on demand and pushed to the series.data array.
  13501. point = { series: series };
  13502. series.pointClass.prototype.applyOptions.apply(point, [options]);
  13503. x = point.x;
  13504. // Get the insertion point
  13505. i = xData.length;
  13506. if (series.requireSorting && x < xData[i - 1]) {
  13507. isInTheMiddle = true;
  13508. while (i && xData[i - 1] > x) {
  13509. i--;
  13510. }
  13511. }
  13512. series.updateParallelArrays(point, 'splice', i, 0, 0); // insert undefined item
  13513. series.updateParallelArrays(point, i); // update it
  13514. if (names && point.name) {
  13515. names[x] = point.name;
  13516. }
  13517. dataOptions.splice(i, 0, options);
  13518. if (isInTheMiddle) {
  13519. series.data.splice(i, 0, null);
  13520. series.processData();
  13521. }
  13522. // Generate points to be added to the legend (#1329)
  13523. if (seriesOptions.legendType === 'point') {
  13524. series.generatePoints();
  13525. }
  13526. // Shift the first point off the parallel arrays
  13527. // todo: consider series.removePoint(i) method
  13528. if (shift) {
  13529. if (data[0] && data[0].remove) {
  13530. data[0].remove(false);
  13531. } else {
  13532. data.shift();
  13533. series.updateParallelArrays(point, 'shift');
  13534. dataOptions.shift();
  13535. }
  13536. }
  13537. // redraw
  13538. series.isDirty = true;
  13539. series.isDirtyData = true;
  13540. if (redraw) {
  13541. series.getAttribs(); // #1937
  13542. chart.redraw();
  13543. }
  13544. },
  13545. /**
  13546. * Remove a point (rendered or not), by index
  13547. */
  13548. removePoint: function (i, redraw, animation) {
  13549. var series = this,
  13550. data = series.data,
  13551. point = data[i],
  13552. points = series.points,
  13553. chart = series.chart,
  13554. remove = function () {
  13555. if (data.length === points.length) {
  13556. points.splice(i, 1);
  13557. }
  13558. data.splice(i, 1);
  13559. series.options.data.splice(i, 1);
  13560. series.updateParallelArrays(point || { series: series }, 'splice', i, 1);
  13561. if (point) {
  13562. point.destroy();
  13563. }
  13564. // redraw
  13565. series.isDirty = true;
  13566. series.isDirtyData = true;
  13567. if (redraw) {
  13568. chart.redraw();
  13569. }
  13570. };
  13571. setAnimation(animation, chart);
  13572. redraw = pick(redraw, true);
  13573. // Fire the event with a default handler of removing the point
  13574. if (point) {
  13575. point.firePointEvent('remove', null, remove);
  13576. } else {
  13577. remove();
  13578. }
  13579. },
  13580. /**
  13581. * Remove a series and optionally redraw the chart
  13582. *
  13583. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  13584. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  13585. * configuration
  13586. */
  13587. remove: function (redraw, animation) {
  13588. var series = this,
  13589. chart = series.chart;
  13590. redraw = pick(redraw, true);
  13591. if (!series.isRemoving) { /* prevent triggering native event in jQuery
  13592. (calling the remove function from the remove event) */
  13593. series.isRemoving = true;
  13594. // fire the event with a default handler of removing the point
  13595. fireEvent(series, 'remove', null, function () {
  13596. // destroy elements
  13597. series.destroy();
  13598. // redraw
  13599. chart.isDirtyLegend = chart.isDirtyBox = true;
  13600. chart.linkSeries();
  13601. if (redraw) {
  13602. chart.redraw(animation);
  13603. }
  13604. });
  13605. }
  13606. series.isRemoving = false;
  13607. },
  13608. /**
  13609. * Update the series with a new set of options
  13610. */
  13611. update: function (newOptions, redraw) {
  13612. var series = this,
  13613. chart = this.chart,
  13614. // must use user options when changing type because this.options is merged
  13615. // in with type specific plotOptions
  13616. oldOptions = this.userOptions,
  13617. oldType = this.type,
  13618. proto = seriesTypes[oldType].prototype,
  13619. preserve = ['group', 'markerGroup', 'dataLabelsGroup'],
  13620. n;
  13621. // If we're changing type or zIndex, create new groups (#3380, #3404)
  13622. if ((newOptions.type && newOptions.type !== oldType) || newOptions.zIndex !== undefined) {
  13623. preserve.length = 0;
  13624. }
  13625. // Make sure groups are not destroyed (#3094)
  13626. each(preserve, function (prop) {
  13627. preserve[prop] = series[prop];
  13628. delete series[prop];
  13629. });
  13630. // Do the merge, with some forced options
  13631. newOptions = merge(oldOptions, {
  13632. animation: false,
  13633. index: this.index,
  13634. pointStart: this.xData[0] // when updating after addPoint
  13635. }, { data: this.options.data }, newOptions);
  13636. // Destroy the series and delete all properties. Reinsert all methods
  13637. // and properties from the new type prototype (#2270, #3719)
  13638. this.remove(false);
  13639. for (n in proto) {
  13640. this[n] = UNDEFINED;
  13641. }
  13642. extend(this, seriesTypes[newOptions.type || oldType].prototype);
  13643. // Re-register groups (#3094)
  13644. each(preserve, function (prop) {
  13645. series[prop] = preserve[prop];
  13646. });
  13647. this.init(chart, newOptions);
  13648. chart.linkSeries(); // Links are lost in this.remove (#3028)
  13649. if (pick(redraw, true)) {
  13650. chart.redraw(false);
  13651. }
  13652. }
  13653. });
  13654. // Extend the Axis.prototype for dynamic methods
  13655. extend(Axis.prototype, {
  13656. /**
  13657. * Update the axis with a new options structure
  13658. */
  13659. update: function (newOptions, redraw) {
  13660. var chart = this.chart;
  13661. newOptions = chart.options[this.coll][this.options.index] = merge(this.userOptions, newOptions);
  13662. this.destroy(true);
  13663. this._addedPlotLB = this.chart._labelPanes = UNDEFINED; // #1611, #2887, #4314
  13664. this.init(chart, extend(newOptions, { events: UNDEFINED }));
  13665. chart.isDirtyBox = true;
  13666. if (pick(redraw, true)) {
  13667. chart.redraw();
  13668. }
  13669. },
  13670. /**
  13671. * Remove the axis from the chart
  13672. */
  13673. remove: function (redraw) {
  13674. var chart = this.chart,
  13675. key = this.coll, // xAxis or yAxis
  13676. axisSeries = this.series,
  13677. i = axisSeries.length;
  13678. // Remove associated series (#2687)
  13679. while (i--) {
  13680. if (axisSeries[i]) {
  13681. axisSeries[i].remove(false);
  13682. }
  13683. }
  13684. // Remove the axis
  13685. erase(chart.axes, this);
  13686. erase(chart[key], this);
  13687. chart.options[key].splice(this.options.index, 1);
  13688. each(chart[key], function (axis, i) { // Re-index, #1706
  13689. axis.options.index = i;
  13690. });
  13691. this.destroy();
  13692. chart.isDirtyBox = true;
  13693. if (pick(redraw, true)) {
  13694. chart.redraw();
  13695. }
  13696. },
  13697. /**
  13698. * Update the axis title by options
  13699. */
  13700. setTitle: function (newTitleOptions, redraw) {
  13701. this.update({ title: newTitleOptions }, redraw);
  13702. },
  13703. /**
  13704. * Set new axis categories and optionally redraw
  13705. * @param {Array} categories
  13706. * @param {Boolean} redraw
  13707. */
  13708. setCategories: function (categories, redraw) {
  13709. this.update({ categories: categories }, redraw);
  13710. }
  13711. });
  13712. /**
  13713. * LineSeries object
  13714. */
  13715. var LineSeries = extendClass(Series);
  13716. seriesTypes.line = LineSeries;
  13717. /**
  13718. * Set the default options for area
  13719. */
  13720. defaultPlotOptions.area = merge(defaultSeriesOptions, {
  13721. softThreshold: false,
  13722. threshold: 0
  13723. // trackByArea: false,
  13724. // lineColor: null, // overrides color, but lets fillColor be unaltered
  13725. // fillOpacity: 0.75,
  13726. // fillColor: null
  13727. });
  13728. /**
  13729. * AreaSeries object
  13730. */
  13731. var AreaSeries = extendClass(Series, {
  13732. type: 'area',
  13733. /**
  13734. * For stacks, don't split segments on null values. Instead, draw null values with
  13735. * no marker. Also insert dummy points for any X position that exists in other series
  13736. * in the stack.
  13737. */
  13738. getSegments: function () {
  13739. var series = this,
  13740. segments = [],
  13741. segment = [],
  13742. keys = [],
  13743. xAxis = this.xAxis,
  13744. yAxis = this.yAxis,
  13745. stack = yAxis.stacks[this.stackKey],
  13746. pointMap = {},
  13747. plotX,
  13748. plotY,
  13749. points = this.points,
  13750. connectNulls = this.options.connectNulls,
  13751. stackIndicator,
  13752. i,
  13753. x;
  13754. if (this.options.stacking && !this.cropped) { // cropped causes artefacts in Stock, and perf issue
  13755. // Create a map where we can quickly look up the points by their X value.
  13756. for (i = 0; i < points.length; i++) {
  13757. pointMap[points[i].x] = points[i];
  13758. }
  13759. // Sort the keys (#1651)
  13760. for (x in stack) {
  13761. if (stack[x].total !== null) { // nulled after switching between grouping and not (#1651, #2336)
  13762. keys.push(+x);
  13763. }
  13764. }
  13765. keys.sort(function (a, b) {
  13766. return a - b;
  13767. });
  13768. each(keys, function (x) {
  13769. var threshold = null,
  13770. stackPoint;
  13771. if (connectNulls && (!pointMap[x] || pointMap[x].y === null)) { // #1836
  13772. return;
  13773. // The point exists, push it to the segment
  13774. } else if (pointMap[x]) {
  13775. segment.push(pointMap[x]);
  13776. // There is no point for this X value in this series, so we
  13777. // insert a dummy point in order for the areas to be drawn
  13778. // correctly.
  13779. } else {
  13780. // Loop down the stack to find the series below this one that has
  13781. // a value (#1991)
  13782. for (i = series.index; i <= yAxis.series.length; i++) {
  13783. stackIndicator = series.getStackIndicator(null, x, i);
  13784. stackPoint = stack[x].points[stackIndicator.key];
  13785. if (stackPoint) {
  13786. threshold = stackPoint[1];
  13787. break;
  13788. }
  13789. }
  13790. plotX = xAxis.translate(x);
  13791. plotY = yAxis.getThreshold(threshold);
  13792. segment.push({
  13793. y: null,
  13794. plotX: plotX,
  13795. clientX: plotX,
  13796. plotY: plotY,
  13797. yBottom: plotY,
  13798. onMouseOver: noop
  13799. });
  13800. }
  13801. });
  13802. if (segment.length) {
  13803. segments.push(segment);
  13804. }
  13805. } else {
  13806. Series.prototype.getSegments.call(this);
  13807. segments = this.segments;
  13808. }
  13809. this.segments = segments;
  13810. },
  13811. /**
  13812. * Extend the base Series getSegmentPath method by adding the path for the area.
  13813. * This path is pushed to the series.areaPath property.
  13814. */
  13815. getSegmentPath: function (segment) {
  13816. var segmentPath = Series.prototype.getSegmentPath.call(this, segment), // call base method
  13817. areaSegmentPath = [].concat(segmentPath), // work on a copy for the area path
  13818. i,
  13819. options = this.options,
  13820. segLength = segmentPath.length,
  13821. translatedThreshold = this.yAxis.getThreshold(options.threshold), // #2181
  13822. yBottom;
  13823. if (segLength === 3) { // for animation from 1 to two points
  13824. areaSegmentPath.push(L, segmentPath[1], segmentPath[2]);
  13825. }
  13826. if (options.stacking && !this.closedStacks) {
  13827. // Follow stack back. Todo: implement areaspline. A general solution could be to
  13828. // reverse the entire graphPath of the previous series, though may be hard with
  13829. // splines and with series with different extremes
  13830. for (i = segment.length - 1; i >= 0; i--) {
  13831. yBottom = pick(segment[i].yBottom, translatedThreshold);
  13832. // step line?
  13833. if (i < segment.length - 1 && options.step) {
  13834. areaSegmentPath.push(segment[i + 1].plotX, yBottom);
  13835. }
  13836. areaSegmentPath.push(segment[i].plotX, yBottom);
  13837. }
  13838. } else { // follow zero line back
  13839. this.closeSegment(areaSegmentPath, segment, translatedThreshold);
  13840. }
  13841. this.areaPath = this.areaPath.concat(areaSegmentPath);
  13842. return segmentPath;
  13843. },
  13844. /**
  13845. * Extendable method to close the segment path of an area. This is overridden in polar
  13846. * charts.
  13847. */
  13848. closeSegment: function (path, segment, translatedThreshold) {
  13849. path.push(
  13850. L,
  13851. segment[segment.length - 1].plotX,
  13852. translatedThreshold,
  13853. L,
  13854. segment[0].plotX,
  13855. translatedThreshold
  13856. );
  13857. },
  13858. /**
  13859. * Draw the graph and the underlying area. This method calls the Series base
  13860. * function and adds the area. The areaPath is calculated in the getSegmentPath
  13861. * method called from Series.prototype.drawGraph.
  13862. */
  13863. drawGraph: function () {
  13864. // Define or reset areaPath
  13865. this.areaPath = [];
  13866. // Call the base method
  13867. Series.prototype.drawGraph.apply(this);
  13868. // Define local variables
  13869. var series = this,
  13870. areaPath = this.areaPath,
  13871. options = this.options,
  13872. zones = this.zones,
  13873. props = [['area', this.color, options.fillColor]]; // area name, main color, fill color
  13874. each(zones, function (threshold, i) {
  13875. props.push(['zoneArea' + i, threshold.color || series.color, threshold.fillColor || options.fillColor]);
  13876. });
  13877. each(props, function (prop) {
  13878. var areaKey = prop[0],
  13879. area = series[areaKey];
  13880. // Create or update the area
  13881. if (area) { // update
  13882. area.animate({ d: areaPath });
  13883. } else { // create
  13884. series[areaKey] = series.chart.renderer.path(areaPath)
  13885. .attr({
  13886. fill: pick(
  13887. prop[2],
  13888. Color(prop[1]).setOpacity(pick(options.fillOpacity, 0.75)).get()
  13889. ),
  13890. zIndex: 0 // #1069
  13891. }).add(series.group);
  13892. }
  13893. });
  13894. },
  13895. drawLegendSymbol: LegendSymbolMixin.drawRectangle
  13896. });
  13897. seriesTypes.area = AreaSeries;
  13898. /**
  13899. * Set the default options for spline
  13900. */
  13901. defaultPlotOptions.spline = merge(defaultSeriesOptions);
  13902. /**
  13903. * SplineSeries object
  13904. */
  13905. var SplineSeries = extendClass(Series, {
  13906. type: 'spline',
  13907. /**
  13908. * Get the spline segment from a given point's previous neighbour to the given point
  13909. */
  13910. getPointSpline: function (segment, point, i) {
  13911. var smoothing = 1.5, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc
  13912. denom = smoothing + 1,
  13913. plotX = point.plotX,
  13914. plotY = point.plotY,
  13915. lastPoint = segment[i - 1],
  13916. nextPoint = segment[i + 1],
  13917. leftContX,
  13918. leftContY,
  13919. rightContX,
  13920. rightContY,
  13921. ret;
  13922. // find control points
  13923. if (lastPoint && nextPoint) {
  13924. var lastX = lastPoint.plotX,
  13925. lastY = lastPoint.plotY,
  13926. nextX = nextPoint.plotX,
  13927. nextY = nextPoint.plotY,
  13928. correction;
  13929. leftContX = (smoothing * plotX + lastX) / denom;
  13930. leftContY = (smoothing * plotY + lastY) / denom;
  13931. rightContX = (smoothing * plotX + nextX) / denom;
  13932. rightContY = (smoothing * plotY + nextY) / denom;
  13933. // have the two control points make a straight line through main point
  13934. correction = ((rightContY - leftContY) * (rightContX - plotX)) /
  13935. (rightContX - leftContX) + plotY - rightContY;
  13936. leftContY += correction;
  13937. rightContY += correction;
  13938. // to prevent false extremes, check that control points are between
  13939. // neighbouring points' y values
  13940. if (leftContY > lastY && leftContY > plotY) {
  13941. leftContY = mathMax(lastY, plotY);
  13942. rightContY = 2 * plotY - leftContY; // mirror of left control point
  13943. } else if (leftContY < lastY && leftContY < plotY) {
  13944. leftContY = mathMin(lastY, plotY);
  13945. rightContY = 2 * plotY - leftContY;
  13946. }
  13947. if (rightContY > nextY && rightContY > plotY) {
  13948. rightContY = mathMax(nextY, plotY);
  13949. leftContY = 2 * plotY - rightContY;
  13950. } else if (rightContY < nextY && rightContY < plotY) {
  13951. rightContY = mathMin(nextY, plotY);
  13952. leftContY = 2 * plotY - rightContY;
  13953. }
  13954. // record for drawing in next point
  13955. point.rightContX = rightContX;
  13956. point.rightContY = rightContY;
  13957. }
  13958. // Visualize control points for debugging
  13959. /*
  13960. if (leftContX) {
  13961. this.chart.renderer.circle(leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 2)
  13962. .attr({
  13963. stroke: 'red',
  13964. 'stroke-width': 1,
  13965. fill: 'none'
  13966. })
  13967. .add();
  13968. this.chart.renderer.path(['M', leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop,
  13969. 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
  13970. .attr({
  13971. stroke: 'red',
  13972. 'stroke-width': 1
  13973. })
  13974. .add();
  13975. this.chart.renderer.circle(rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 2)
  13976. .attr({
  13977. stroke: 'green',
  13978. 'stroke-width': 1,
  13979. fill: 'none'
  13980. })
  13981. .add();
  13982. this.chart.renderer.path(['M', rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop,
  13983. 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
  13984. .attr({
  13985. stroke: 'green',
  13986. 'stroke-width': 1
  13987. })
  13988. .add();
  13989. }
  13990. */
  13991. // moveTo or lineTo
  13992. if (!i) {
  13993. ret = [M, plotX, plotY];
  13994. } else { // curve from last point to this
  13995. ret = [
  13996. 'C',
  13997. lastPoint.rightContX || lastPoint.plotX,
  13998. lastPoint.rightContY || lastPoint.plotY,
  13999. leftContX || plotX,
  14000. leftContY || plotY,
  14001. plotX,
  14002. plotY
  14003. ];
  14004. lastPoint.rightContX = lastPoint.rightContY = null; // reset for updating series later
  14005. }
  14006. return ret;
  14007. }
  14008. });
  14009. seriesTypes.spline = SplineSeries;
  14010. /**
  14011. * Set the default options for areaspline
  14012. */
  14013. defaultPlotOptions.areaspline = merge(defaultPlotOptions.area);
  14014. /**
  14015. * AreaSplineSeries object
  14016. */
  14017. var areaProto = AreaSeries.prototype,
  14018. AreaSplineSeries = extendClass(SplineSeries, {
  14019. type: 'areaspline',
  14020. closedStacks: true, // instead of following the previous graph back, follow the threshold back
  14021. // Mix in methods from the area series
  14022. getSegmentPath: areaProto.getSegmentPath,
  14023. closeSegment: areaProto.closeSegment,
  14024. drawGraph: areaProto.drawGraph,
  14025. drawLegendSymbol: LegendSymbolMixin.drawRectangle
  14026. });
  14027. seriesTypes.areaspline = AreaSplineSeries;
  14028. /**
  14029. * Set the default options for column
  14030. */
  14031. defaultPlotOptions.column = merge(defaultSeriesOptions, {
  14032. borderColor: '#FFFFFF',
  14033. //borderWidth: 1,
  14034. borderRadius: 0,
  14035. //colorByPoint: undefined,
  14036. groupPadding: 0.2,
  14037. //grouping: true,
  14038. marker: null, // point options are specified in the base options
  14039. pointPadding: 0.1,
  14040. //pointWidth: null,
  14041. minPointLength: 0,
  14042. cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes
  14043. pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories
  14044. states: {
  14045. hover: {
  14046. brightness: 0.1,
  14047. shadow: false,
  14048. halo: false
  14049. },
  14050. select: {
  14051. color: '#C0C0C0',
  14052. borderColor: '#000000',
  14053. shadow: false
  14054. }
  14055. },
  14056. dataLabels: {
  14057. align: null, // auto
  14058. verticalAlign: null, // auto
  14059. y: null
  14060. },
  14061. softThreshold: false,
  14062. startFromThreshold: true, // docs (but false doesn't work well): http://jsfiddle.net/highcharts/hz8fopan/14/
  14063. stickyTracking: false,
  14064. tooltip: {
  14065. distance: 6
  14066. },
  14067. threshold: 0
  14068. });
  14069. /**
  14070. * ColumnSeries object
  14071. */
  14072. var ColumnSeries = extendClass(Series, {
  14073. type: 'column',
  14074. pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
  14075. stroke: 'borderColor',
  14076. fill: 'color',
  14077. r: 'borderRadius'
  14078. },
  14079. cropShoulder: 0,
  14080. directTouch: true, // When tooltip is not shared, this series (and derivatives) requires direct touch/hover. KD-tree does not apply.
  14081. trackerGroups: ['group', 'dataLabelsGroup'],
  14082. negStacks: true, // use separate negative stacks, unlike area stacks where a negative
  14083. // point is substracted from previous (#1910)
  14084. /**
  14085. * Initialize the series
  14086. */
  14087. init: function () {
  14088. Series.prototype.init.apply(this, arguments);
  14089. var series = this,
  14090. chart = series.chart;
  14091. // if the series is added dynamically, force redraw of other
  14092. // series affected by a new column
  14093. if (chart.hasRendered) {
  14094. each(chart.series, function (otherSeries) {
  14095. if (otherSeries.type === series.type) {
  14096. otherSeries.isDirty = true;
  14097. }
  14098. });
  14099. }
  14100. },
  14101. /**
  14102. * Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding,
  14103. * pointWidth etc.
  14104. */
  14105. getColumnMetrics: function () {
  14106. var series = this,
  14107. options = series.options,
  14108. xAxis = series.xAxis,
  14109. yAxis = series.yAxis,
  14110. reversedXAxis = xAxis.reversed,
  14111. stackKey,
  14112. stackGroups = {},
  14113. columnIndex,
  14114. columnCount = 0;
  14115. // Get the total number of column type series.
  14116. // This is called on every series. Consider moving this logic to a
  14117. // chart.orderStacks() function and call it on init, addSeries and removeSeries
  14118. if (options.grouping === false) {
  14119. columnCount = 1;
  14120. } else {
  14121. each(series.chart.series, function (otherSeries) {
  14122. var otherOptions = otherSeries.options,
  14123. otherYAxis = otherSeries.yAxis;
  14124. if (otherSeries.type === series.type && otherSeries.visible &&
  14125. yAxis.len === otherYAxis.len && yAxis.pos === otherYAxis.pos) { // #642, #2086
  14126. if (otherOptions.stacking) {
  14127. stackKey = otherSeries.stackKey;
  14128. if (stackGroups[stackKey] === UNDEFINED) {
  14129. stackGroups[stackKey] = columnCount++;
  14130. }
  14131. columnIndex = stackGroups[stackKey];
  14132. } else if (otherOptions.grouping !== false) { // #1162
  14133. columnIndex = columnCount++;
  14134. }
  14135. otherSeries.columnIndex = columnIndex;
  14136. }
  14137. });
  14138. }
  14139. var categoryWidth = mathMin(
  14140. mathAbs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || xAxis.tickInterval || 1), // #2610
  14141. xAxis.len // #1535
  14142. ),
  14143. groupPadding = categoryWidth * options.groupPadding,
  14144. groupWidth = categoryWidth - 2 * groupPadding,
  14145. pointOffsetWidth = groupWidth / columnCount,
  14146. pointWidth = mathMin(
  14147. options.maxPointWidth || xAxis.len,
  14148. pick(options.pointWidth, pointOffsetWidth * (1 - 2 * options.pointPadding))
  14149. ),
  14150. pointPadding = (pointOffsetWidth - pointWidth) / 2,
  14151. colIndex = (reversedXAxis ?
  14152. columnCount - (series.columnIndex || 0) : // #1251
  14153. series.columnIndex) || 0,
  14154. pointXOffset = pointPadding + (groupPadding + colIndex *
  14155. pointOffsetWidth - (categoryWidth / 2)) *
  14156. (reversedXAxis ? -1 : 1);
  14157. // Save it for reading in linked series (Error bars particularly)
  14158. return (series.columnMetrics = {
  14159. width: pointWidth,
  14160. offset: pointXOffset
  14161. });
  14162. },
  14163. /**
  14164. * Make the columns crisp. The edges are rounded to the nearest full pixel.
  14165. */
  14166. crispCol: function (x, y, w, h) {
  14167. var chart = this.chart,
  14168. borderWidth = this.borderWidth,
  14169. xCrisp = -(borderWidth % 2 ? 0.5 : 0),
  14170. yCrisp = borderWidth % 2 ? 0.5 : 1,
  14171. right,
  14172. bottom,
  14173. fromTop;
  14174. if (chart.inverted && chart.renderer.isVML) {
  14175. yCrisp += 1;
  14176. }
  14177. // Horizontal. We need to first compute the exact right edge, then round it
  14178. // and compute the width from there.
  14179. right = Math.round(x + w) + xCrisp;
  14180. x = Math.round(x) + xCrisp;
  14181. w = right - x;
  14182. // Vertical
  14183. fromTop = mathAbs(y) <= 0.5; // #4504
  14184. bottom = Math.round(y + h) + yCrisp;
  14185. y = Math.round(y) + yCrisp;
  14186. h = bottom - y;
  14187. // Top edges are exceptions
  14188. if (fromTop) {
  14189. y -= 1;
  14190. h += 1;
  14191. }
  14192. return {
  14193. x: x,
  14194. y: y,
  14195. width: w,
  14196. height: h
  14197. };
  14198. },
  14199. /**
  14200. * Translate each point to the plot area coordinate system and find shape positions
  14201. */
  14202. translate: function () {
  14203. var series = this,
  14204. chart = series.chart,
  14205. options = series.options,
  14206. borderWidth = series.borderWidth = pick(
  14207. options.borderWidth,
  14208. series.closestPointRange * series.xAxis.transA < 2 ? 0 : 1 // #3635
  14209. ),
  14210. yAxis = series.yAxis,
  14211. threshold = options.threshold,
  14212. translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold),
  14213. minPointLength = pick(options.minPointLength, 5),
  14214. metrics = series.getColumnMetrics(),
  14215. pointWidth = metrics.width,
  14216. seriesBarW = series.barW = mathMax(pointWidth, 1 + 2 * borderWidth), // postprocessed for border width
  14217. pointXOffset = series.pointXOffset = metrics.offset;
  14218. if (chart.inverted) {
  14219. translatedThreshold -= 0.5; // #3355
  14220. }
  14221. // When the pointPadding is 0, we want the columns to be packed tightly, so we allow individual
  14222. // columns to have individual sizes. When pointPadding is greater, we strive for equal-width
  14223. // columns (#2694).
  14224. if (options.pointPadding) {
  14225. seriesBarW = mathCeil(seriesBarW);
  14226. }
  14227. Series.prototype.translate.apply(series);
  14228. // Record the new values
  14229. each(series.points, function (point) {
  14230. var yBottom = mathMin(pick(point.yBottom, translatedThreshold), 9e4), // #3575
  14231. safeDistance = 999 + mathAbs(yBottom),
  14232. plotY = mathMin(mathMax(-safeDistance, point.plotY), yAxis.len + safeDistance), // Don't draw too far outside plot area (#1303, #2241, #4264)
  14233. barX = point.plotX + pointXOffset,
  14234. barW = seriesBarW,
  14235. barY = mathMin(plotY, yBottom),
  14236. up,
  14237. barH = mathMax(plotY, yBottom) - barY;
  14238. // Handle options.minPointLength
  14239. if (mathAbs(barH) < minPointLength) {
  14240. if (minPointLength) {
  14241. barH = minPointLength;
  14242. up = (!yAxis.reversed && !point.negative) || (yAxis.reversed && point.negative);
  14243. barY = mathAbs(barY - translatedThreshold) > minPointLength ? // stacked
  14244. yBottom - minPointLength : // keep position
  14245. translatedThreshold - (up ? minPointLength : 0); // #1485, #4051
  14246. }
  14247. }
  14248. // Cache for access in polar
  14249. point.barX = barX;
  14250. point.pointWidth = pointWidth;
  14251. // Fix the tooltip on center of grouped columns (#1216, #424, #3648)
  14252. point.tooltipPos = chart.inverted ?
  14253. [yAxis.len + yAxis.pos - chart.plotLeft - plotY, series.xAxis.len - barX - barW / 2, barH] :
  14254. [barX + barW / 2, plotY + yAxis.pos - chart.plotTop, barH];
  14255. // Register shape type and arguments to be used in drawPoints
  14256. point.shapeType = 'rect';
  14257. point.shapeArgs = series.crispCol(barX, barY, barW, barH);
  14258. });
  14259. },
  14260. getSymbol: noop,
  14261. /**
  14262. * Use a solid rectangle like the area series types
  14263. */
  14264. drawLegendSymbol: LegendSymbolMixin.drawRectangle,
  14265. /**
  14266. * Columns have no graph
  14267. */
  14268. drawGraph: noop,
  14269. /**
  14270. * Draw the columns. For bars, the series.group is rotated, so the same coordinates
  14271. * apply for columns and bars. This method is inherited by scatter series.
  14272. *
  14273. */
  14274. drawPoints: function () {
  14275. var series = this,
  14276. chart = this.chart,
  14277. options = series.options,
  14278. renderer = chart.renderer,
  14279. animationLimit = options.animationLimit || 250,
  14280. shapeArgs,
  14281. pointAttr;
  14282. // draw the columns
  14283. each(series.points, function (point) {
  14284. var plotY = point.plotY,
  14285. graphic = point.graphic,
  14286. borderAttr;
  14287. if (plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) {
  14288. shapeArgs = point.shapeArgs;
  14289. borderAttr = defined(series.borderWidth) ? {
  14290. 'stroke-width': series.borderWidth
  14291. } : {};
  14292. pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || series.pointAttr[NORMAL_STATE];
  14293. if (graphic) { // update
  14294. stop(graphic);
  14295. graphic.attr(borderAttr)[chart.pointCount < animationLimit ? 'animate' : 'attr'](merge(shapeArgs));
  14296. } else {
  14297. point.graphic = graphic = renderer[point.shapeType](shapeArgs)
  14298. .attr(borderAttr)
  14299. .attr(pointAttr)
  14300. .add(point.group || series.group)
  14301. .shadow(options.shadow, null, options.stacking && !options.borderRadius);
  14302. }
  14303. } else if (graphic) {
  14304. point.graphic = graphic.destroy(); // #1269
  14305. }
  14306. });
  14307. },
  14308. /**
  14309. * Animate the column heights one by one from zero
  14310. * @param {Boolean} init Whether to initialize the animation or run it
  14311. */
  14312. animate: function (init) {
  14313. var series = this,
  14314. yAxis = this.yAxis,
  14315. options = series.options,
  14316. inverted = this.chart.inverted,
  14317. attr = {},
  14318. translatedThreshold;
  14319. if (hasSVG) { // VML is too slow anyway
  14320. if (init) {
  14321. attr.scaleY = 0.001;
  14322. translatedThreshold = mathMin(yAxis.pos + yAxis.len, mathMax(yAxis.pos, yAxis.toPixels(options.threshold)));
  14323. if (inverted) {
  14324. attr.translateX = translatedThreshold - yAxis.len;
  14325. } else {
  14326. attr.translateY = translatedThreshold;
  14327. }
  14328. series.group.attr(attr);
  14329. } else { // run the animation
  14330. attr.scaleY = 1;
  14331. attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos;
  14332. series.group.animate(attr, series.options.animation);
  14333. // delete this function to allow it only once
  14334. series.animate = null;
  14335. }
  14336. }
  14337. },
  14338. /**
  14339. * Remove this series from the chart
  14340. */
  14341. remove: function () {
  14342. var series = this,
  14343. chart = series.chart;
  14344. // column and bar series affects other series of the same type
  14345. // as they are either stacked or grouped
  14346. if (chart.hasRendered) {
  14347. each(chart.series, function (otherSeries) {
  14348. if (otherSeries.type === series.type) {
  14349. otherSeries.isDirty = true;
  14350. }
  14351. });
  14352. }
  14353. Series.prototype.remove.apply(series, arguments);
  14354. }
  14355. });
  14356. seriesTypes.column = ColumnSeries;
  14357. /**
  14358. * Set the default options for bar
  14359. */
  14360. defaultPlotOptions.bar = merge(defaultPlotOptions.column);
  14361. /**
  14362. * The Bar series class
  14363. */
  14364. var BarSeries = extendClass(ColumnSeries, {
  14365. type: 'bar',
  14366. inverted: true
  14367. });
  14368. seriesTypes.bar = BarSeries;
  14369. /**
  14370. * Set the default options for scatter
  14371. */
  14372. defaultPlotOptions.scatter = merge(defaultSeriesOptions, {
  14373. lineWidth: 0,
  14374. marker: {
  14375. enabled: true // Overrides auto-enabling in line series (#3647)
  14376. },
  14377. tooltip: {
  14378. headerFormat: '<span style="color:{point.color}">\u25CF</span> <span style="font-size: 10px;"> {series.name}</span><br/>',
  14379. pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>'
  14380. }
  14381. });
  14382. /**
  14383. * The scatter series class
  14384. */
  14385. var ScatterSeries = extendClass(Series, {
  14386. type: 'scatter',
  14387. sorted: false,
  14388. requireSorting: false,
  14389. noSharedTooltip: true,
  14390. trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'],
  14391. takeOrdinalPosition: false, // #2342
  14392. kdDimensions: 2,
  14393. drawGraph: function () {
  14394. if (this.options.lineWidth) {
  14395. Series.prototype.drawGraph.call(this);
  14396. }
  14397. }
  14398. });
  14399. seriesTypes.scatter = ScatterSeries;
  14400. /**
  14401. * Set the default options for pie
  14402. */
  14403. defaultPlotOptions.pie = merge(defaultSeriesOptions, {
  14404. borderColor: '#FFFFFF',
  14405. borderWidth: 1,
  14406. center: [null, null],
  14407. clip: false,
  14408. colorByPoint: true, // always true for pies
  14409. dataLabels: {
  14410. // align: null,
  14411. // connectorWidth: 1,
  14412. // connectorColor: point.color,
  14413. // connectorPadding: 5,
  14414. distance: 30,
  14415. enabled: true,
  14416. formatter: function () { // #2945
  14417. return this.y === null ? undefined : this.point.name;
  14418. },
  14419. // softConnector: true,
  14420. x: 0
  14421. // y: 0
  14422. },
  14423. ignoreHiddenPoint: true,
  14424. //innerSize: 0,
  14425. legendType: 'point',
  14426. marker: null, // point options are specified in the base options
  14427. size: null,
  14428. showInLegend: false,
  14429. slicedOffset: 10,
  14430. states: {
  14431. hover: {
  14432. brightness: 0.1,
  14433. shadow: false
  14434. }
  14435. },
  14436. stickyTracking: false,
  14437. tooltip: {
  14438. followPointer: true
  14439. }
  14440. });
  14441. /**
  14442. * Extended point object for pies
  14443. */
  14444. var PiePoint = extendClass(Point, {
  14445. /**
  14446. * Initiate the pie slice
  14447. */
  14448. init: function () {
  14449. Point.prototype.init.apply(this, arguments);
  14450. var point = this,
  14451. toggleSlice;
  14452. point.name = pick(point.name, 'Slice');
  14453. // add event listener for select
  14454. toggleSlice = function (e) {
  14455. point.slice(e.type === 'select');
  14456. };
  14457. addEvent(point, 'select', toggleSlice);
  14458. addEvent(point, 'unselect', toggleSlice);
  14459. return point;
  14460. },
  14461. /**
  14462. * Toggle the visibility of the pie slice
  14463. * @param {Boolean} vis Whether to show the slice or not. If undefined, the
  14464. * visibility is toggled
  14465. */
  14466. setVisible: function (vis, redraw) {
  14467. var point = this,
  14468. series = point.series,
  14469. chart = series.chart,
  14470. ignoreHiddenPoint = series.options.ignoreHiddenPoint;
  14471. redraw = pick(redraw, ignoreHiddenPoint);
  14472. if (vis !== point.visible) {
  14473. // If called without an argument, toggle visibility
  14474. point.visible = point.options.visible = vis = vis === UNDEFINED ? !point.visible : vis;
  14475. series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data
  14476. // Show and hide associated elements. This is performed regardless of redraw or not,
  14477. // because chart.redraw only handles full series.
  14478. each(['graphic', 'dataLabel', 'connector', 'shadowGroup'], function (key) {
  14479. if (point[key]) {
  14480. point[key][vis ? 'show' : 'hide'](true);
  14481. }
  14482. });
  14483. if (point.legendItem) {
  14484. chart.legend.colorizeItem(point, vis);
  14485. }
  14486. // #4170, hide halo after hiding point
  14487. if (!vis && point.state === 'hover') {
  14488. point.setState('');
  14489. }
  14490. // Handle ignore hidden slices
  14491. if (ignoreHiddenPoint) {
  14492. series.isDirty = true;
  14493. }
  14494. if (redraw) {
  14495. chart.redraw();
  14496. }
  14497. }
  14498. },
  14499. /**
  14500. * Set or toggle whether the slice is cut out from the pie
  14501. * @param {Boolean} sliced When undefined, the slice state is toggled
  14502. * @param {Boolean} redraw Whether to redraw the chart. True by default.
  14503. */
  14504. slice: function (sliced, redraw, animation) {
  14505. var point = this,
  14506. series = point.series,
  14507. chart = series.chart,
  14508. translation;
  14509. setAnimation(animation, chart);
  14510. // redraw is true by default
  14511. redraw = pick(redraw, true);
  14512. // if called without an argument, toggle
  14513. point.sliced = point.options.sliced = sliced = defined(sliced) ? sliced : !point.sliced;
  14514. series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data
  14515. translation = sliced ? point.slicedTranslation : {
  14516. translateX: 0,
  14517. translateY: 0
  14518. };
  14519. point.graphic.animate(translation);
  14520. if (point.shadowGroup) {
  14521. point.shadowGroup.animate(translation);
  14522. }
  14523. },
  14524. haloPath: function (size) {
  14525. var shapeArgs = this.shapeArgs,
  14526. chart = this.series.chart;
  14527. 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, {
  14528. innerR: this.shapeArgs.r,
  14529. start: shapeArgs.start,
  14530. end: shapeArgs.end
  14531. });
  14532. }
  14533. });
  14534. /**
  14535. * The Pie series class
  14536. */
  14537. var PieSeries = {
  14538. type: 'pie',
  14539. isCartesian: false,
  14540. pointClass: PiePoint,
  14541. requireSorting: false,
  14542. directTouch: true,
  14543. noSharedTooltip: true,
  14544. trackerGroups: ['group', 'dataLabelsGroup'],
  14545. axisTypes: [],
  14546. pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
  14547. stroke: 'borderColor',
  14548. 'stroke-width': 'borderWidth',
  14549. fill: 'color'
  14550. },
  14551. /**
  14552. * Animate the pies in
  14553. */
  14554. animate: function (init) {
  14555. var series = this,
  14556. points = series.points,
  14557. startAngleRad = series.startAngleRad;
  14558. if (!init) {
  14559. each(points, function (point) {
  14560. var graphic = point.graphic,
  14561. args = point.shapeArgs;
  14562. if (graphic) {
  14563. // start values
  14564. graphic.attr({
  14565. r: point.startR || (series.center[3] / 2), // animate from inner radius (#779)
  14566. start: startAngleRad,
  14567. end: startAngleRad
  14568. });
  14569. // animate
  14570. graphic.animate({
  14571. r: args.r,
  14572. start: args.start,
  14573. end: args.end
  14574. }, series.options.animation);
  14575. }
  14576. });
  14577. // delete this function to allow it only once
  14578. series.animate = null;
  14579. }
  14580. },
  14581. /**
  14582. * Recompute total chart sum and update percentages of points.
  14583. */
  14584. updateTotals: function () {
  14585. var i,
  14586. total = 0,
  14587. points = this.points,
  14588. len = points.length,
  14589. point,
  14590. ignoreHiddenPoint = this.options.ignoreHiddenPoint;
  14591. // Get the total sum
  14592. for (i = 0; i < len; i++) {
  14593. point = points[i];
  14594. total += (ignoreHiddenPoint && !point.visible) ? 0 : point.y;
  14595. }
  14596. this.total = total;
  14597. // Set each point's properties
  14598. for (i = 0; i < len; i++) {
  14599. point = points[i];
  14600. point.percentage = (total > 0 && (point.visible || !ignoreHiddenPoint)) ? point.y / total * 100 : 0;
  14601. point.total = total;
  14602. }
  14603. },
  14604. /**
  14605. * Extend the generatePoints method by adding total and percentage properties to each point
  14606. */
  14607. generatePoints: function () {
  14608. Series.prototype.generatePoints.call(this);
  14609. this.updateTotals();
  14610. },
  14611. /**
  14612. * Do translation for pie slices
  14613. */
  14614. translate: function (positions) {
  14615. this.generatePoints();
  14616. var series = this,
  14617. cumulative = 0,
  14618. precision = 1000, // issue #172
  14619. options = series.options,
  14620. slicedOffset = options.slicedOffset,
  14621. connectorOffset = slicedOffset + options.borderWidth,
  14622. start,
  14623. end,
  14624. angle,
  14625. startAngle = options.startAngle || 0,
  14626. startAngleRad = series.startAngleRad = mathPI / 180 * (startAngle - 90),
  14627. endAngleRad = series.endAngleRad = mathPI / 180 * ((pick(options.endAngle, startAngle + 360)) - 90),
  14628. circ = endAngleRad - startAngleRad, //2 * mathPI,
  14629. points = series.points,
  14630. radiusX, // the x component of the radius vector for a given point
  14631. radiusY,
  14632. labelDistance = options.dataLabels.distance,
  14633. ignoreHiddenPoint = options.ignoreHiddenPoint,
  14634. i,
  14635. len = points.length,
  14636. point;
  14637. // Get positions - either an integer or a percentage string must be given.
  14638. // If positions are passed as a parameter, we're in a recursive loop for adjusting
  14639. // space for data labels.
  14640. if (!positions) {
  14641. series.center = positions = series.getCenter();
  14642. }
  14643. // utility for getting the x value from a given y, used for anticollision logic in data labels
  14644. series.getX = function (y, left) {
  14645. angle = math.asin(mathMin((y - positions[1]) / (positions[2] / 2 + labelDistance), 1));
  14646. return positions[0] +
  14647. (left ? -1 : 1) *
  14648. (mathCos(angle) * (positions[2] / 2 + labelDistance));
  14649. };
  14650. // Calculate the geometry for each point
  14651. for (i = 0; i < len; i++) {
  14652. point = points[i];
  14653. // set start and end angle
  14654. start = startAngleRad + (cumulative * circ);
  14655. if (!ignoreHiddenPoint || point.visible) {
  14656. cumulative += point.percentage / 100;
  14657. }
  14658. end = startAngleRad + (cumulative * circ);
  14659. // set the shape
  14660. point.shapeType = 'arc';
  14661. point.shapeArgs = {
  14662. x: positions[0],
  14663. y: positions[1],
  14664. r: positions[2] / 2,
  14665. innerR: positions[3] / 2,
  14666. start: mathRound(start * precision) / precision,
  14667. end: mathRound(end * precision) / precision
  14668. };
  14669. // The angle must stay within -90 and 270 (#2645)
  14670. angle = (end + start) / 2;
  14671. if (angle > 1.5 * mathPI) {
  14672. angle -= 2 * mathPI;
  14673. } else if (angle < -mathPI / 2) {
  14674. angle += 2 * mathPI;
  14675. }
  14676. // Center for the sliced out slice
  14677. point.slicedTranslation = {
  14678. translateX: mathRound(mathCos(angle) * slicedOffset),
  14679. translateY: mathRound(mathSin(angle) * slicedOffset)
  14680. };
  14681. // set the anchor point for tooltips
  14682. radiusX = mathCos(angle) * positions[2] / 2;
  14683. radiusY = mathSin(angle) * positions[2] / 2;
  14684. point.tooltipPos = [
  14685. positions[0] + radiusX * 0.7,
  14686. positions[1] + radiusY * 0.7
  14687. ];
  14688. point.half = angle < -mathPI / 2 || angle > mathPI / 2 ? 1 : 0;
  14689. point.angle = angle;
  14690. // set the anchor point for data labels
  14691. connectorOffset = mathMin(connectorOffset, labelDistance / 2); // #1678
  14692. point.labelPos = [
  14693. positions[0] + radiusX + mathCos(angle) * labelDistance, // first break of connector
  14694. positions[1] + radiusY + mathSin(angle) * labelDistance, // a/a
  14695. positions[0] + radiusX + mathCos(angle) * connectorOffset, // second break, right outside pie
  14696. positions[1] + radiusY + mathSin(angle) * connectorOffset, // a/a
  14697. positions[0] + radiusX, // landing point for connector
  14698. positions[1] + radiusY, // a/a
  14699. labelDistance < 0 ? // alignment
  14700. 'center' :
  14701. point.half ? 'right' : 'left', // alignment
  14702. angle // center angle
  14703. ];
  14704. }
  14705. },
  14706. drawGraph: null,
  14707. /**
  14708. * Draw the data points
  14709. */
  14710. drawPoints: function () {
  14711. var series = this,
  14712. chart = series.chart,
  14713. renderer = chart.renderer,
  14714. groupTranslation,
  14715. //center,
  14716. graphic,
  14717. //group,
  14718. shadow = series.options.shadow,
  14719. shadowGroup,
  14720. shapeArgs,
  14721. attr;
  14722. if (shadow && !series.shadowGroup) {
  14723. series.shadowGroup = renderer.g('shadow')
  14724. .add(series.group);
  14725. }
  14726. // draw the slices
  14727. each(series.points, function (point) {
  14728. if (point.y !== null) {
  14729. graphic = point.graphic;
  14730. shapeArgs = point.shapeArgs;
  14731. shadowGroup = point.shadowGroup;
  14732. // put the shadow behind all points
  14733. if (shadow && !shadowGroup) {
  14734. shadowGroup = point.shadowGroup = renderer.g('shadow')
  14735. .add(series.shadowGroup);
  14736. }
  14737. // if the point is sliced, use special translation, else use plot area traslation
  14738. groupTranslation = point.sliced ? point.slicedTranslation : {
  14739. translateX: 0,
  14740. translateY: 0
  14741. };
  14742. //group.translate(groupTranslation[0], groupTranslation[1]);
  14743. if (shadowGroup) {
  14744. shadowGroup.attr(groupTranslation);
  14745. }
  14746. // draw the slice
  14747. if (graphic) {
  14748. graphic
  14749. .setRadialReference(series.center)
  14750. .animate(extend(shapeArgs, groupTranslation));
  14751. } else {
  14752. attr = { 'stroke-linejoin': 'round' };
  14753. if (!point.visible) {
  14754. attr.visibility = 'hidden';
  14755. }
  14756. point.graphic = graphic = renderer[point.shapeType](shapeArgs)
  14757. .setRadialReference(series.center)
  14758. .attr(
  14759. point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE]
  14760. )
  14761. .attr(attr)
  14762. .attr(groupTranslation)
  14763. .add(series.group)
  14764. .shadow(shadow, shadowGroup);
  14765. }
  14766. }
  14767. });
  14768. },
  14769. searchPoint: noop,
  14770. /**
  14771. * Utility for sorting data labels
  14772. */
  14773. sortByAngle: function (points, sign) {
  14774. points.sort(function (a, b) {
  14775. return a.angle !== undefined && (b.angle - a.angle) * sign;
  14776. });
  14777. },
  14778. /**
  14779. * Use a simple symbol from LegendSymbolMixin
  14780. */
  14781. drawLegendSymbol: LegendSymbolMixin.drawRectangle,
  14782. /**
  14783. * Use the getCenter method from drawLegendSymbol
  14784. */
  14785. getCenter: CenteredSeriesMixin.getCenter,
  14786. /**
  14787. * Pies don't have point marker symbols
  14788. */
  14789. getSymbol: noop
  14790. };
  14791. PieSeries = extendClass(Series, PieSeries);
  14792. seriesTypes.pie = PieSeries;
  14793. /**
  14794. * Draw the data labels
  14795. */
  14796. Series.prototype.drawDataLabels = function () {
  14797. var series = this,
  14798. seriesOptions = series.options,
  14799. cursor = seriesOptions.cursor,
  14800. options = seriesOptions.dataLabels,
  14801. points = series.points,
  14802. pointOptions,
  14803. generalOptions,
  14804. hasRendered = series.hasRendered || 0,
  14805. str,
  14806. dataLabelsGroup,
  14807. renderer = series.chart.renderer;
  14808. if (options.enabled || series._hasPointLabels) {
  14809. // Process default alignment of data labels for columns
  14810. if (series.dlProcessOptions) {
  14811. series.dlProcessOptions(options);
  14812. }
  14813. // Create a separate group for the data labels to avoid rotation
  14814. dataLabelsGroup = series.plotGroup(
  14815. 'dataLabelsGroup',
  14816. 'data-labels',
  14817. options.defer ? HIDDEN : VISIBLE,
  14818. options.zIndex || 6
  14819. );
  14820. if (pick(options.defer, true)) {
  14821. dataLabelsGroup.attr({ opacity: +hasRendered }); // #3300
  14822. if (!hasRendered) {
  14823. addEvent(series, 'afterAnimate', function () {
  14824. if (series.visible) { // #3023, #3024
  14825. dataLabelsGroup.show();
  14826. }
  14827. dataLabelsGroup[seriesOptions.animation ? 'animate' : 'attr']({ opacity: 1 }, { duration: 200 });
  14828. });
  14829. }
  14830. }
  14831. // Make the labels for each point
  14832. generalOptions = options;
  14833. each(points, function (point) {
  14834. var enabled,
  14835. dataLabel = point.dataLabel,
  14836. labelConfig,
  14837. attr,
  14838. name,
  14839. rotation,
  14840. connector = point.connector,
  14841. isNew = true,
  14842. style,
  14843. moreStyle = {};
  14844. // Determine if each data label is enabled
  14845. pointOptions = point.dlOptions || (point.options && point.options.dataLabels); // dlOptions is used in treemaps
  14846. enabled = pick(pointOptions && pointOptions.enabled, generalOptions.enabled); // #2282
  14847. // If the point is outside the plot area, destroy it. #678, #820
  14848. if (dataLabel && !enabled) {
  14849. point.dataLabel = dataLabel.destroy();
  14850. // Individual labels are disabled if the are explicitly disabled
  14851. // in the point options, or if they fall outside the plot area.
  14852. } else if (enabled) {
  14853. // Create individual options structure that can be extended without
  14854. // affecting others
  14855. options = merge(generalOptions, pointOptions);
  14856. style = options.style;
  14857. rotation = options.rotation;
  14858. // Get the string
  14859. labelConfig = point.getLabelConfig();
  14860. str = options.format ?
  14861. format(options.format, labelConfig) :
  14862. options.formatter.call(labelConfig, options);
  14863. // Determine the color
  14864. style.color = pick(options.color, style.color, series.color, 'black');
  14865. // update existing label
  14866. if (dataLabel) {
  14867. if (defined(str)) {
  14868. dataLabel
  14869. .attr({
  14870. text: str
  14871. });
  14872. isNew = false;
  14873. } else { // #1437 - the label is shown conditionally
  14874. point.dataLabel = dataLabel = dataLabel.destroy();
  14875. if (connector) {
  14876. point.connector = connector.destroy();
  14877. }
  14878. }
  14879. // create new label
  14880. } else if (defined(str)) {
  14881. attr = {
  14882. //align: align,
  14883. fill: options.backgroundColor,
  14884. stroke: options.borderColor,
  14885. 'stroke-width': options.borderWidth,
  14886. r: options.borderRadius || 0,
  14887. rotation: rotation,
  14888. padding: options.padding,
  14889. zIndex: 1
  14890. };
  14891. // Get automated contrast color
  14892. if (style.color === 'contrast') {
  14893. moreStyle.color = options.inside || options.distance < 0 || !!seriesOptions.stacking ?
  14894. renderer.getContrast(point.color || series.color) :
  14895. '#000000';
  14896. }
  14897. if (cursor) {
  14898. moreStyle.cursor = cursor;
  14899. }
  14900. // Remove unused attributes (#947)
  14901. for (name in attr) {
  14902. if (attr[name] === UNDEFINED) {
  14903. delete attr[name];
  14904. }
  14905. }
  14906. dataLabel = point.dataLabel = renderer[rotation ? 'text' : 'label']( // labels don't support rotation
  14907. str,
  14908. 0,
  14909. -999,
  14910. options.shape,
  14911. null,
  14912. null,
  14913. options.useHTML
  14914. )
  14915. .attr(attr)
  14916. .css(extend(style, moreStyle))
  14917. .add(dataLabelsGroup)
  14918. .shadow(options.shadow);
  14919. }
  14920. if (dataLabel) {
  14921. // Now the data label is created and placed at 0,0, so we need to align it
  14922. series.alignDataLabel(point, dataLabel, options, null, isNew);
  14923. }
  14924. }
  14925. });
  14926. }
  14927. };
  14928. /**
  14929. * Align each individual data label
  14930. */
  14931. Series.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) {
  14932. var chart = this.chart,
  14933. inverted = chart.inverted,
  14934. plotX = pick(point.plotX, -999),
  14935. plotY = pick(point.plotY, -999),
  14936. bBox = dataLabel.getBBox(),
  14937. baseline = chart.renderer.fontMetrics(options.style.fontSize).b,
  14938. rotCorr, // rotation correction
  14939. // Math.round for rounding errors (#2683), alignTo to allow column labels (#2700)
  14940. visible = this.visible && (point.series.forceDL || chart.isInsidePlot(plotX, mathRound(plotY), inverted) ||
  14941. (alignTo && chart.isInsidePlot(plotX, inverted ? alignTo.x + 1 : alignTo.y + alignTo.height - 1, inverted))),
  14942. alignAttr; // the final position;
  14943. if (visible) {
  14944. // The alignment box is a singular point
  14945. alignTo = extend({
  14946. x: inverted ? chart.plotWidth - plotY : plotX,
  14947. y: mathRound(inverted ? chart.plotHeight - plotX : plotY),
  14948. width: 0,
  14949. height: 0
  14950. }, alignTo);
  14951. // Add the text size for alignment calculation
  14952. extend(options, {
  14953. width: bBox.width,
  14954. height: bBox.height
  14955. });
  14956. // Allow a hook for changing alignment in the last moment, then do the alignment
  14957. if (options.rotation) { // Fancy box alignment isn't supported for rotated text
  14958. rotCorr = chart.renderer.rotCorr(baseline, options.rotation); // #3723
  14959. dataLabel[isNew ? 'attr' : 'animate']({
  14960. x: alignTo.x + options.x + alignTo.width / 2 + rotCorr.x,
  14961. y: alignTo.y + options.y + alignTo.height / 2
  14962. })
  14963. .attr({ // #3003
  14964. align: options.align
  14965. });
  14966. } else {
  14967. dataLabel.align(options, null, alignTo);
  14968. alignAttr = dataLabel.alignAttr;
  14969. // Handle justify or crop
  14970. if (pick(options.overflow, 'justify') === 'justify') {
  14971. this.justifyDataLabel(dataLabel, options, alignAttr, bBox, alignTo, isNew);
  14972. } else if (pick(options.crop, true)) {
  14973. // Now check that the data label is within the plot area
  14974. visible = chart.isInsidePlot(alignAttr.x, alignAttr.y) && chart.isInsidePlot(alignAttr.x + bBox.width, alignAttr.y + bBox.height);
  14975. }
  14976. // When we're using a shape, make it possible with a connector or an arrow pointing to thie point
  14977. if (options.shape) {
  14978. dataLabel.attr({
  14979. anchorX: point.plotX,
  14980. anchorY: point.plotY
  14981. });
  14982. }
  14983. }
  14984. }
  14985. // Show or hide based on the final aligned position
  14986. if (!visible) {
  14987. stop(dataLabel);
  14988. dataLabel.attr({ y: -999 });
  14989. dataLabel.placed = false; // don't animate back in
  14990. }
  14991. };
  14992. /**
  14993. * If data labels fall partly outside the plot area, align them back in, in a way that
  14994. * doesn't hide the point.
  14995. */
  14996. Series.prototype.justifyDataLabel = function (dataLabel, options, alignAttr, bBox, alignTo, isNew) {
  14997. var chart = this.chart,
  14998. align = options.align,
  14999. verticalAlign = options.verticalAlign,
  15000. off,
  15001. justified,
  15002. padding = dataLabel.box ? 0 : (dataLabel.padding || 0);
  15003. // Off left
  15004. off = alignAttr.x + padding;
  15005. if (off < 0) {
  15006. if (align === 'right') {
  15007. options.align = 'left';
  15008. } else {
  15009. options.x = -off;
  15010. }
  15011. justified = true;
  15012. }
  15013. // Off right
  15014. off = alignAttr.x + bBox.width - padding;
  15015. if (off > chart.plotWidth) {
  15016. if (align === 'left') {
  15017. options.align = 'right';
  15018. } else {
  15019. options.x = chart.plotWidth - off;
  15020. }
  15021. justified = true;
  15022. }
  15023. // Off top
  15024. off = alignAttr.y + padding;
  15025. if (off < 0) {
  15026. if (verticalAlign === 'bottom') {
  15027. options.verticalAlign = 'top';
  15028. } else {
  15029. options.y = -off;
  15030. }
  15031. justified = true;
  15032. }
  15033. // Off bottom
  15034. off = alignAttr.y + bBox.height - padding;
  15035. if (off > chart.plotHeight) {
  15036. if (verticalAlign === 'top') {
  15037. options.verticalAlign = 'bottom';
  15038. } else {
  15039. options.y = chart.plotHeight - off;
  15040. }
  15041. justified = true;
  15042. }
  15043. if (justified) {
  15044. dataLabel.placed = !isNew;
  15045. dataLabel.align(options, null, alignTo);
  15046. }
  15047. };
  15048. /**
  15049. * Override the base drawDataLabels method by pie specific functionality
  15050. */
  15051. if (seriesTypes.pie) {
  15052. seriesTypes.pie.prototype.drawDataLabels = function () {
  15053. var series = this,
  15054. data = series.data,
  15055. point,
  15056. chart = series.chart,
  15057. options = series.options.dataLabels,
  15058. connectorPadding = pick(options.connectorPadding, 10),
  15059. connectorWidth = pick(options.connectorWidth, 1),
  15060. plotWidth = chart.plotWidth,
  15061. plotHeight = chart.plotHeight,
  15062. connector,
  15063. connectorPath,
  15064. softConnector = pick(options.softConnector, true),
  15065. distanceOption = options.distance,
  15066. seriesCenter = series.center,
  15067. radius = seriesCenter[2] / 2,
  15068. centerY = seriesCenter[1],
  15069. outside = distanceOption > 0,
  15070. dataLabel,
  15071. dataLabelWidth,
  15072. labelPos,
  15073. labelHeight,
  15074. halves = [// divide the points into right and left halves for anti collision
  15075. [], // right
  15076. [] // left
  15077. ],
  15078. x,
  15079. y,
  15080. visibility,
  15081. rankArr,
  15082. i,
  15083. j,
  15084. overflow = [0, 0, 0, 0], // top, right, bottom, left
  15085. sort = function (a, b) {
  15086. return b.y - a.y;
  15087. };
  15088. // get out if not enabled
  15089. if (!series.visible || (!options.enabled && !series._hasPointLabels)) {
  15090. return;
  15091. }
  15092. // run parent method
  15093. Series.prototype.drawDataLabels.apply(series);
  15094. // arrange points for detection collision
  15095. each(data, function (point) {
  15096. if (point.dataLabel && point.visible) { // #407, #2510
  15097. halves[point.half].push(point);
  15098. }
  15099. });
  15100. /* Loop over the points in each half, starting from the top and bottom
  15101. * of the pie to detect overlapping labels.
  15102. */
  15103. i = 2;
  15104. while (i--) {
  15105. var slots = [],
  15106. slotsLength,
  15107. usedSlots = [],
  15108. points = halves[i],
  15109. pos,
  15110. bottom,
  15111. length = points.length,
  15112. slotIndex;
  15113. if (!length) {
  15114. continue;
  15115. }
  15116. // Sort by angle
  15117. series.sortByAngle(points, i - 0.5);
  15118. // Assume equal label heights on either hemisphere (#2630)
  15119. j = labelHeight = 0;
  15120. while (!labelHeight && points[j]) { // #1569
  15121. labelHeight = points[j] && points[j].dataLabel && (points[j].dataLabel.getBBox().height || 21); // 21 is for #968
  15122. j++;
  15123. }
  15124. // Only do anti-collision when we are outside the pie and have connectors (#856)
  15125. if (distanceOption > 0) {
  15126. // Build the slots
  15127. bottom = mathMin(centerY + radius + distanceOption, chart.plotHeight);
  15128. for (pos = mathMax(0, centerY - radius - distanceOption); pos <= bottom; pos += labelHeight) {
  15129. slots.push(pos);
  15130. }
  15131. slotsLength = slots.length;
  15132. /* Visualize the slots
  15133. if (!series.slotElements) {
  15134. series.slotElements = [];
  15135. }
  15136. if (i === 1) {
  15137. series.slotElements.forEach(function (elem) {
  15138. elem.destroy();
  15139. });
  15140. series.slotElements.length = 0;
  15141. }
  15142. slots.forEach(function (pos, no) {
  15143. var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0),
  15144. slotY = pos + chart.plotTop;
  15145. if (!isNaN(slotX)) {
  15146. series.slotElements.push(chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1)
  15147. .attr({
  15148. 'stroke-width': 1,
  15149. stroke: 'silver',
  15150. fill: 'rgba(0,0,255,0.1)'
  15151. })
  15152. .add());
  15153. series.slotElements.push(chart.renderer.text('Slot '+ no, slotX, slotY + 4)
  15154. .attr({
  15155. fill: 'silver'
  15156. }).add());
  15157. }
  15158. });
  15159. // */
  15160. // if there are more values than available slots, remove lowest values
  15161. if (length > slotsLength) {
  15162. // create an array for sorting and ranking the points within each quarter
  15163. rankArr = [].concat(points);
  15164. rankArr.sort(sort);
  15165. j = length;
  15166. while (j--) {
  15167. rankArr[j].rank = j;
  15168. }
  15169. j = length;
  15170. while (j--) {
  15171. if (points[j].rank >= slotsLength) {
  15172. points.splice(j, 1);
  15173. }
  15174. }
  15175. length = points.length;
  15176. }
  15177. // The label goes to the nearest open slot, but not closer to the edge than
  15178. // the label's index.
  15179. for (j = 0; j < length; j++) {
  15180. point = points[j];
  15181. labelPos = point.labelPos;
  15182. var closest = 9999,
  15183. distance,
  15184. slotI;
  15185. // find the closest slot index
  15186. for (slotI = 0; slotI < slotsLength; slotI++) {
  15187. distance = mathAbs(slots[slotI] - labelPos[1]);
  15188. if (distance < closest) {
  15189. closest = distance;
  15190. slotIndex = slotI;
  15191. }
  15192. }
  15193. // if that slot index is closer to the edges of the slots, move it
  15194. // to the closest appropriate slot
  15195. if (slotIndex < j && slots[j] !== null) { // cluster at the top
  15196. slotIndex = j;
  15197. } else if (slotsLength < length - j + slotIndex && slots[j] !== null) { // cluster at the bottom
  15198. slotIndex = slotsLength - length + j;
  15199. while (slots[slotIndex] === null) { // make sure it is not taken
  15200. slotIndex++;
  15201. }
  15202. } else {
  15203. // Slot is taken, find next free slot below. In the next run, the next slice will find the
  15204. // slot above these, because it is the closest one
  15205. while (slots[slotIndex] === null) { // make sure it is not taken
  15206. slotIndex++;
  15207. }
  15208. }
  15209. usedSlots.push({ i: slotIndex, y: slots[slotIndex] });
  15210. slots[slotIndex] = null; // mark as taken
  15211. }
  15212. // sort them in order to fill in from the top
  15213. usedSlots.sort(sort);
  15214. }
  15215. // now the used slots are sorted, fill them up sequentially
  15216. for (j = 0; j < length; j++) {
  15217. var slot, naturalY;
  15218. point = points[j];
  15219. labelPos = point.labelPos;
  15220. dataLabel = point.dataLabel;
  15221. visibility = point.visible === false ? HIDDEN : 'inherit';
  15222. naturalY = labelPos[1];
  15223. if (distanceOption > 0) {
  15224. slot = usedSlots.pop();
  15225. slotIndex = slot.i;
  15226. // if the slot next to currrent slot is free, the y value is allowed
  15227. // to fall back to the natural position
  15228. y = slot.y;
  15229. if ((naturalY > y && slots[slotIndex + 1] !== null) ||
  15230. (naturalY < y && slots[slotIndex - 1] !== null)) {
  15231. y = mathMin(mathMax(0, naturalY), chart.plotHeight);
  15232. }
  15233. } else {
  15234. y = naturalY;
  15235. }
  15236. // get the x - use the natural x position for first and last slot, to prevent the top
  15237. // and botton slice connectors from touching each other on either side
  15238. x = options.justify ?
  15239. seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption) :
  15240. series.getX(y === centerY - radius - distanceOption || y === centerY + radius + distanceOption ? naturalY : y, i);
  15241. // Record the placement and visibility
  15242. dataLabel._attr = {
  15243. visibility: visibility,
  15244. align: labelPos[6]
  15245. };
  15246. dataLabel._pos = {
  15247. x: x + options.x +
  15248. ({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0),
  15249. y: y + options.y - 10 // 10 is for the baseline (label vs text)
  15250. };
  15251. dataLabel.connX = x;
  15252. dataLabel.connY = y;
  15253. // Detect overflowing data labels
  15254. if (this.options.size === null) {
  15255. dataLabelWidth = dataLabel.width;
  15256. // Overflow left
  15257. if (x - dataLabelWidth < connectorPadding) {
  15258. overflow[3] = mathMax(mathRound(dataLabelWidth - x + connectorPadding), overflow[3]);
  15259. // Overflow right
  15260. } else if (x + dataLabelWidth > plotWidth - connectorPadding) {
  15261. overflow[1] = mathMax(mathRound(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]);
  15262. }
  15263. // Overflow top
  15264. if (y - labelHeight / 2 < 0) {
  15265. overflow[0] = mathMax(mathRound(-y + labelHeight / 2), overflow[0]);
  15266. // Overflow left
  15267. } else if (y + labelHeight / 2 > plotHeight) {
  15268. overflow[2] = mathMax(mathRound(y + labelHeight / 2 - plotHeight), overflow[2]);
  15269. }
  15270. }
  15271. } // for each point
  15272. } // for each half
  15273. // Do not apply the final placement and draw the connectors until we have verified
  15274. // that labels are not spilling over.
  15275. if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) {
  15276. // Place the labels in the final position
  15277. this.placeDataLabels();
  15278. // Draw the connectors
  15279. if (outside && connectorWidth) {
  15280. each(this.points, function (point) {
  15281. connector = point.connector;
  15282. labelPos = point.labelPos;
  15283. dataLabel = point.dataLabel;
  15284. if (dataLabel && dataLabel._pos && point.visible) {
  15285. visibility = dataLabel._attr.visibility;
  15286. x = dataLabel.connX;
  15287. y = dataLabel.connY;
  15288. connectorPath = softConnector ? [
  15289. M,
  15290. x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
  15291. 'C',
  15292. x, y, // first break, next to the label
  15293. 2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5],
  15294. labelPos[2], labelPos[3], // second break
  15295. L,
  15296. labelPos[4], labelPos[5] // base
  15297. ] : [
  15298. M,
  15299. x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
  15300. L,
  15301. labelPos[2], labelPos[3], // second break
  15302. L,
  15303. labelPos[4], labelPos[5] // base
  15304. ];
  15305. if (connector) {
  15306. connector.animate({ d: connectorPath });
  15307. connector.attr('visibility', visibility);
  15308. } else {
  15309. point.connector = connector = series.chart.renderer.path(connectorPath).attr({
  15310. 'stroke-width': connectorWidth,
  15311. stroke: options.connectorColor || point.color || '#606060',
  15312. visibility: visibility
  15313. //zIndex: 0 // #2722 (reversed)
  15314. })
  15315. .add(series.dataLabelsGroup);
  15316. }
  15317. } else if (connector) {
  15318. point.connector = connector.destroy();
  15319. }
  15320. });
  15321. }
  15322. }
  15323. };
  15324. /**
  15325. * Perform the final placement of the data labels after we have verified that they
  15326. * fall within the plot area.
  15327. */
  15328. seriesTypes.pie.prototype.placeDataLabels = function () {
  15329. each(this.points, function (point) {
  15330. var dataLabel = point.dataLabel,
  15331. _pos;
  15332. if (dataLabel && point.visible) {
  15333. _pos = dataLabel._pos;
  15334. if (_pos) {
  15335. dataLabel.attr(dataLabel._attr);
  15336. dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos);
  15337. dataLabel.moved = true;
  15338. } else if (dataLabel) {
  15339. dataLabel.attr({ y: -999 });
  15340. }
  15341. }
  15342. });
  15343. };
  15344. seriesTypes.pie.prototype.alignDataLabel = noop;
  15345. /**
  15346. * Verify whether the data labels are allowed to draw, or we should run more translation and data
  15347. * label positioning to keep them inside the plot area. Returns true when data labels are ready
  15348. * to draw.
  15349. */
  15350. seriesTypes.pie.prototype.verifyDataLabelOverflow = function (overflow) {
  15351. var center = this.center,
  15352. options = this.options,
  15353. centerOption = options.center,
  15354. minSize = options.minSize || 80,
  15355. newSize = minSize,
  15356. ret;
  15357. // Handle horizontal size and center
  15358. if (centerOption[0] !== null) { // Fixed center
  15359. newSize = mathMax(center[2] - mathMax(overflow[1], overflow[3]), minSize);
  15360. } else { // Auto center
  15361. newSize = mathMax(
  15362. center[2] - overflow[1] - overflow[3], // horizontal overflow
  15363. minSize
  15364. );
  15365. center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center
  15366. }
  15367. // Handle vertical size and center
  15368. if (centerOption[1] !== null) { // Fixed center
  15369. newSize = mathMax(mathMin(newSize, center[2] - mathMax(overflow[0], overflow[2])), minSize);
  15370. } else { // Auto center
  15371. newSize = mathMax(
  15372. mathMin(
  15373. newSize,
  15374. center[2] - overflow[0] - overflow[2] // vertical overflow
  15375. ),
  15376. minSize
  15377. );
  15378. center[1] += (overflow[0] - overflow[2]) / 2; // vertical center
  15379. }
  15380. // If the size must be decreased, we need to run translate and drawDataLabels again
  15381. if (newSize < center[2]) {
  15382. center[2] = newSize;
  15383. center[3] = Math.min(relativeLength(options.innerSize || 0, newSize), newSize); // #3632
  15384. this.translate(center);
  15385. each(this.points, function (point) {
  15386. if (point.dataLabel) {
  15387. point.dataLabel._pos = null; // reset
  15388. }
  15389. });
  15390. if (this.drawDataLabels) {
  15391. this.drawDataLabels();
  15392. }
  15393. // Else, return true to indicate that the pie and its labels is within the plot area
  15394. } else {
  15395. ret = true;
  15396. }
  15397. return ret;
  15398. };
  15399. }
  15400. if (seriesTypes.column) {
  15401. /**
  15402. * Override the basic data label alignment by adjusting for the position of the column
  15403. */
  15404. seriesTypes.column.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) {
  15405. var inverted = this.chart.inverted,
  15406. series = point.series,
  15407. dlBox = point.dlBox || point.shapeArgs, // data label box for alignment
  15408. below = pick(point.below, point.plotY > pick(this.translatedThreshold, series.yAxis.len)), // point.below is used in range series
  15409. inside = pick(options.inside, !!this.options.stacking); // draw it inside the box?
  15410. // Align to the column itself, or the top of it
  15411. if (dlBox) { // Area range uses this method but not alignTo
  15412. alignTo = merge(dlBox);
  15413. if (inverted) {
  15414. alignTo = {
  15415. x: series.yAxis.len - alignTo.y - alignTo.height,
  15416. y: series.xAxis.len - alignTo.x - alignTo.width,
  15417. width: alignTo.height,
  15418. height: alignTo.width
  15419. };
  15420. }
  15421. // Compute the alignment box
  15422. if (!inside) {
  15423. if (inverted) {
  15424. alignTo.x += below ? 0 : alignTo.width;
  15425. alignTo.width = 0;
  15426. } else {
  15427. alignTo.y += below ? alignTo.height : 0;
  15428. alignTo.height = 0;
  15429. }
  15430. }
  15431. }
  15432. // When alignment is undefined (typically columns and bars), display the individual
  15433. // point below or above the point depending on the threshold
  15434. options.align = pick(
  15435. options.align,
  15436. !inverted || inside ? 'center' : below ? 'right' : 'left'
  15437. );
  15438. options.verticalAlign = pick(
  15439. options.verticalAlign,
  15440. inverted || inside ? 'middle' : below ? 'top' : 'bottom'
  15441. );
  15442. // Call the parent method
  15443. Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew);
  15444. };
  15445. }
  15446. /**
  15447. * Highcharts JS v4.1.9 (2015-10-07)
  15448. * Highcharts module to hide overlapping data labels. This module is included by default in Highmaps.
  15449. *
  15450. * (c) 2010-2014 Torstein Honsi
  15451. *
  15452. * License: www.highcharts.com/license
  15453. */
  15454. /*global Highcharts, HighchartsAdapter */
  15455. (function (H) {
  15456. var Chart = H.Chart,
  15457. each = H.each,
  15458. pick = H.pick,
  15459. addEvent = HighchartsAdapter.addEvent;
  15460. // Collect potensial overlapping data labels. Stack labels probably don't need to be
  15461. // considered because they are usually accompanied by data labels that lie inside the columns.
  15462. Chart.prototype.callbacks.push(function (chart) {
  15463. function collectAndHide() {
  15464. var labels = [];
  15465. each(chart.series, function (series) {
  15466. var dlOptions = series.options.dataLabels,
  15467. collections = series.dataLabelCollections || ['dataLabel']; // Range series have two collections
  15468. if ((dlOptions.enabled || series._hasPointLabels) && !dlOptions.allowOverlap && series.visible) { // #3866
  15469. each(collections, function (coll) {
  15470. each(series.points, function (point) {
  15471. if (point[coll]) {
  15472. point[coll].labelrank = pick(point.labelrank, point.shapeArgs && point.shapeArgs.height); // #4118
  15473. labels.push(point[coll]);
  15474. }
  15475. });
  15476. });
  15477. }
  15478. });
  15479. chart.hideOverlappingLabels(labels);
  15480. }
  15481. // Do it now ...
  15482. collectAndHide();
  15483. // ... and after each chart redraw
  15484. addEvent(chart, 'redraw', collectAndHide);
  15485. });
  15486. /**
  15487. * Hide overlapping labels. Labels are moved and faded in and out on zoom to provide a smooth
  15488. * visual imression.
  15489. */
  15490. Chart.prototype.hideOverlappingLabels = function (labels) {
  15491. var len = labels.length,
  15492. label,
  15493. i,
  15494. j,
  15495. label1,
  15496. label2,
  15497. isIntersecting,
  15498. pos1,
  15499. pos2,
  15500. padding,
  15501. intersectRect = function (x1, y1, w1, h1, x2, y2, w2, h2) {
  15502. return !(
  15503. x2 > x1 + w1 ||
  15504. x2 + w2 < x1 ||
  15505. y2 > y1 + h1 ||
  15506. y2 + h2 < y1
  15507. );
  15508. };
  15509. // Mark with initial opacity
  15510. for (i = 0; i < len; i++) {
  15511. label = labels[i];
  15512. if (label) {
  15513. label.oldOpacity = label.opacity;
  15514. label.newOpacity = 1;
  15515. }
  15516. }
  15517. // Prevent a situation in a gradually rising slope, that each label
  15518. // will hide the previous one because the previous one always has
  15519. // lower rank.
  15520. labels.sort(function (a, b) {
  15521. return (b.labelrank || 0) - (a.labelrank || 0);
  15522. });
  15523. // Detect overlapping labels
  15524. for (i = 0; i < len; i++) {
  15525. label1 = labels[i];
  15526. for (j = i + 1; j < len; ++j) {
  15527. label2 = labels[j];
  15528. if (label1 && label2 && label1.placed && label2.placed && label1.newOpacity !== 0 && label2.newOpacity !== 0) {
  15529. pos1 = label1.alignAttr;
  15530. pos2 = label2.alignAttr;
  15531. padding = 2 * (label1.box ? 0 : label1.padding); // Substract the padding if no background or border (#4333)
  15532. isIntersecting = intersectRect(
  15533. pos1.x,
  15534. pos1.y,
  15535. label1.width - padding,
  15536. label1.height - padding,
  15537. pos2.x,
  15538. pos2.y,
  15539. label2.width - padding,
  15540. label2.height - padding
  15541. );
  15542. if (isIntersecting) {
  15543. (label1.labelrank < label2.labelrank ? label1 : label2).newOpacity = 0;
  15544. }
  15545. }
  15546. }
  15547. }
  15548. // Hide or show
  15549. each(labels, function (label) {
  15550. var complete,
  15551. newOpacity;
  15552. if (label) {
  15553. newOpacity = label.newOpacity;
  15554. if (label.oldOpacity !== newOpacity && label.placed) {
  15555. // Make sure the label is completely hidden to avoid catching clicks (#4362)
  15556. if (newOpacity) {
  15557. label.show(true);
  15558. } else {
  15559. complete = function () {
  15560. label.hide();
  15561. };
  15562. }
  15563. // Animate or set the opacity
  15564. label.alignAttr.opacity = newOpacity;
  15565. label[label.isOld ? 'animate' : 'attr'](label.alignAttr, null, complete);
  15566. }
  15567. label.isOld = true;
  15568. }
  15569. });
  15570. };
  15571. }(Highcharts));/**
  15572. * TrackerMixin for points and graphs
  15573. */
  15574. var TrackerMixin = Highcharts.TrackerMixin = {
  15575. drawTrackerPoint: function () {
  15576. var series = this,
  15577. chart = series.chart,
  15578. pointer = chart.pointer,
  15579. cursor = series.options.cursor,
  15580. css = cursor && { cursor: cursor },
  15581. onMouseOver = function (e) {
  15582. var target = e.target,
  15583. point;
  15584. while (target && !point) {
  15585. point = target.point;
  15586. target = target.parentNode;
  15587. }
  15588. if (point !== UNDEFINED && point !== chart.hoverPoint) { // undefined on graph in scatterchart
  15589. point.onMouseOver(e);
  15590. }
  15591. };
  15592. // Add reference to the point
  15593. each(series.points, function (point) {
  15594. if (point.graphic) {
  15595. point.graphic.element.point = point;
  15596. }
  15597. if (point.dataLabel) {
  15598. point.dataLabel.element.point = point;
  15599. }
  15600. });
  15601. // Add the event listeners, we need to do this only once
  15602. if (!series._hasTracking) {
  15603. each(series.trackerGroups, function (key) {
  15604. if (series[key]) { // we don't always have dataLabelsGroup
  15605. series[key]
  15606. .addClass(PREFIX + 'tracker')
  15607. .on('mouseover', onMouseOver)
  15608. .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); })
  15609. .css(css);
  15610. if (hasTouch) {
  15611. series[key].on('touchstart', onMouseOver);
  15612. }
  15613. }
  15614. });
  15615. series._hasTracking = true;
  15616. }
  15617. },
  15618. /**
  15619. * Draw the tracker object that sits above all data labels and markers to
  15620. * track mouse events on the graph or points. For the line type charts
  15621. * the tracker uses the same graphPath, but with a greater stroke width
  15622. * for better control.
  15623. */
  15624. drawTrackerGraph: function () {
  15625. var series = this,
  15626. options = series.options,
  15627. trackByArea = options.trackByArea,
  15628. trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath),
  15629. trackerPathLength = trackerPath.length,
  15630. chart = series.chart,
  15631. pointer = chart.pointer,
  15632. renderer = chart.renderer,
  15633. snap = chart.options.tooltip.snap,
  15634. tracker = series.tracker,
  15635. cursor = options.cursor,
  15636. css = cursor && { cursor: cursor },
  15637. singlePoints = series.singlePoints,
  15638. singlePoint,
  15639. i,
  15640. onMouseOver = function () {
  15641. if (chart.hoverSeries !== series) {
  15642. series.onMouseOver();
  15643. }
  15644. },
  15645. /*
  15646. * Empirical lowest possible opacities for TRACKER_FILL for an element to stay invisible but clickable
  15647. * IE6: 0.002
  15648. * IE7: 0.002
  15649. * IE8: 0.002
  15650. * IE9: 0.00000000001 (unlimited)
  15651. * IE10: 0.0001 (exporting only)
  15652. * FF: 0.00000000001 (unlimited)
  15653. * Chrome: 0.000001
  15654. * Safari: 0.000001
  15655. * Opera: 0.00000000001 (unlimited)
  15656. */
  15657. TRACKER_FILL = 'rgba(192,192,192,' + (hasSVG ? 0.0001 : 0.002) + ')';
  15658. // Extend end points. A better way would be to use round linecaps,
  15659. // but those are not clickable in VML.
  15660. if (trackerPathLength && !trackByArea) {
  15661. i = trackerPathLength + 1;
  15662. while (i--) {
  15663. if (trackerPath[i] === M) { // extend left side
  15664. trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L);
  15665. }
  15666. if ((i && trackerPath[i] === M) || i === trackerPathLength) { // extend right side
  15667. trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]);
  15668. }
  15669. }
  15670. }
  15671. // handle single points
  15672. for (i = 0; i < singlePoints.length; i++) {
  15673. singlePoint = singlePoints[i];
  15674. trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY,
  15675. L, singlePoint.plotX + snap, singlePoint.plotY);
  15676. }
  15677. // draw the tracker
  15678. if (tracker) {
  15679. tracker.attr({ d: trackerPath });
  15680. } else { // create
  15681. series.tracker = renderer.path(trackerPath)
  15682. .attr({
  15683. 'stroke-linejoin': 'round', // #1225
  15684. visibility: series.visible ? VISIBLE : HIDDEN,
  15685. stroke: TRACKER_FILL,
  15686. fill: trackByArea ? TRACKER_FILL : NONE,
  15687. 'stroke-width' : options.lineWidth + (trackByArea ? 0 : 2 * snap),
  15688. zIndex: 2
  15689. })
  15690. .add(series.group);
  15691. // The tracker is added to the series group, which is clipped, but is covered
  15692. // by the marker group. So the marker group also needs to capture events.
  15693. each([series.tracker, series.markerGroup], function (tracker) {
  15694. tracker.addClass(PREFIX + 'tracker')
  15695. .on('mouseover', onMouseOver)
  15696. .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); })
  15697. .css(css);
  15698. if (hasTouch) {
  15699. tracker.on('touchstart', onMouseOver);
  15700. }
  15701. });
  15702. }
  15703. }
  15704. };
  15705. /* End TrackerMixin */
  15706. /**
  15707. * Add tracking event listener to the series group, so the point graphics
  15708. * themselves act as trackers
  15709. */
  15710. if (seriesTypes.column) {
  15711. ColumnSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
  15712. }
  15713. if (seriesTypes.pie) {
  15714. seriesTypes.pie.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
  15715. }
  15716. if (seriesTypes.scatter) {
  15717. ScatterSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
  15718. }
  15719. /*
  15720. * Extend Legend for item events
  15721. */
  15722. extend(Legend.prototype, {
  15723. setItemEvents: function (item, legendItem, useHTML, itemStyle, itemHiddenStyle) {
  15724. var legend = this;
  15725. // Set the events on the item group, or in case of useHTML, the item itself (#1249)
  15726. (useHTML ? legendItem : item.legendGroup).on('mouseover', function () {
  15727. item.setState(HOVER_STATE);
  15728. legendItem.css(legend.options.itemHoverStyle);
  15729. })
  15730. .on('mouseout', function () {
  15731. legendItem.css(item.visible ? itemStyle : itemHiddenStyle);
  15732. item.setState();
  15733. })
  15734. .on('click', function (event) {
  15735. var strLegendItemClick = 'legendItemClick',
  15736. fnLegendItemClick = function () {
  15737. if (item.setVisible) {
  15738. item.setVisible();
  15739. }
  15740. };
  15741. // Pass over the click/touch event. #4.
  15742. event = {
  15743. browserEvent: event
  15744. };
  15745. // click the name or symbol
  15746. if (item.firePointEvent) { // point
  15747. item.firePointEvent(strLegendItemClick, event, fnLegendItemClick);
  15748. } else {
  15749. fireEvent(item, strLegendItemClick, event, fnLegendItemClick);
  15750. }
  15751. });
  15752. },
  15753. createCheckboxForItem: function (item) {
  15754. var legend = this;
  15755. item.checkbox = createElement('input', {
  15756. type: 'checkbox',
  15757. checked: item.selected,
  15758. defaultChecked: item.selected // required by IE7
  15759. }, legend.options.itemCheckboxStyle, legend.chart.container);
  15760. addEvent(item.checkbox, 'click', function (event) {
  15761. var target = event.target;
  15762. fireEvent(item.series || item, 'checkboxClick', { // #3712
  15763. checked: target.checked,
  15764. item: item
  15765. },
  15766. function () {
  15767. item.select();
  15768. }
  15769. );
  15770. });
  15771. }
  15772. });
  15773. /*
  15774. * Add pointer cursor to legend itemstyle in defaultOptions
  15775. */
  15776. defaultOptions.legend.itemStyle.cursor = 'pointer';
  15777. /*
  15778. * Extend the Chart object with interaction
  15779. */
  15780. extend(Chart.prototype, {
  15781. /**
  15782. * Display the zoom button
  15783. */
  15784. showResetZoom: function () {
  15785. var chart = this,
  15786. lang = defaultOptions.lang,
  15787. btnOptions = chart.options.chart.resetZoomButton,
  15788. theme = btnOptions.theme,
  15789. states = theme.states,
  15790. alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox';
  15791. this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, function () { chart.zoomOut(); }, theme, states && states.hover)
  15792. .attr({
  15793. align: btnOptions.position.align,
  15794. title: lang.resetZoomTitle
  15795. })
  15796. .add()
  15797. .align(btnOptions.position, false, alignTo);
  15798. },
  15799. /**
  15800. * Zoom out to 1:1
  15801. */
  15802. zoomOut: function () {
  15803. var chart = this;
  15804. fireEvent(chart, 'selection', { resetSelection: true }, function () {
  15805. chart.zoom();
  15806. });
  15807. },
  15808. /**
  15809. * Zoom into a given portion of the chart given by axis coordinates
  15810. * @param {Object} event
  15811. */
  15812. zoom: function (event) {
  15813. var chart = this,
  15814. hasZoomed,
  15815. pointer = chart.pointer,
  15816. displayButton = false,
  15817. resetZoomButton;
  15818. // If zoom is called with no arguments, reset the axes
  15819. if (!event || event.resetSelection) {
  15820. each(chart.axes, function (axis) {
  15821. hasZoomed = axis.zoom();
  15822. });
  15823. } else { // else, zoom in on all axes
  15824. each(event.xAxis.concat(event.yAxis), function (axisData) {
  15825. var axis = axisData.axis,
  15826. isXAxis = axis.isXAxis;
  15827. // don't zoom more than minRange
  15828. if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) {
  15829. hasZoomed = axis.zoom(axisData.min, axisData.max);
  15830. if (axis.displayBtn) {
  15831. displayButton = true;
  15832. }
  15833. }
  15834. });
  15835. }
  15836. // Show or hide the Reset zoom button
  15837. resetZoomButton = chart.resetZoomButton;
  15838. if (displayButton && !resetZoomButton) {
  15839. chart.showResetZoom();
  15840. } else if (!displayButton && isObject(resetZoomButton)) {
  15841. chart.resetZoomButton = resetZoomButton.destroy();
  15842. }
  15843. // Redraw
  15844. if (hasZoomed) {
  15845. chart.redraw(
  15846. pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation
  15847. );
  15848. }
  15849. },
  15850. /**
  15851. * Pan the chart by dragging the mouse across the pane. This function is called
  15852. * on mouse move, and the distance to pan is computed from chartX compared to
  15853. * the first chartX position in the dragging operation.
  15854. */
  15855. pan: function (e, panning) {
  15856. var chart = this,
  15857. hoverPoints = chart.hoverPoints,
  15858. doRedraw;
  15859. // remove active points for shared tooltip
  15860. if (hoverPoints) {
  15861. each(hoverPoints, function (point) {
  15862. point.setState();
  15863. });
  15864. }
  15865. each(panning === 'xy' ? [1, 0] : [1], function (isX) { // xy is used in maps
  15866. var mousePos = e[isX ? 'chartX' : 'chartY'],
  15867. axis = chart[isX ? 'xAxis' : 'yAxis'][0],
  15868. startPos = chart[isX ? 'mouseDownX' : 'mouseDownY'],
  15869. halfPointRange = (axis.pointRange || 0) / 2,
  15870. extremes = axis.getExtremes(),
  15871. newMin = axis.toValue(startPos - mousePos, true) + halfPointRange,
  15872. newMax = axis.toValue(startPos + chart[isX ? 'plotWidth' : 'plotHeight'] - mousePos, true) - halfPointRange,
  15873. goingLeft = startPos > mousePos; // #3613
  15874. if (axis.series.length &&
  15875. (goingLeft || newMin > mathMin(extremes.dataMin, extremes.min)) &&
  15876. (!goingLeft || newMax < mathMax(extremes.dataMax, extremes.max))) {
  15877. axis.setExtremes(newMin, newMax, false, false, { trigger: 'pan' });
  15878. doRedraw = true;
  15879. }
  15880. chart[isX ? 'mouseDownX' : 'mouseDownY'] = mousePos; // set new reference for next run
  15881. });
  15882. if (doRedraw) {
  15883. chart.redraw(false);
  15884. }
  15885. css(chart.container, { cursor: 'move' });
  15886. }
  15887. });
  15888. /*
  15889. * Extend the Point object with interaction
  15890. */
  15891. extend(Point.prototype, {
  15892. /**
  15893. * Toggle the selection status of a point
  15894. * @param {Boolean} selected Whether to select or unselect the point.
  15895. * @param {Boolean} accumulate Whether to add to the previous selection. By default,
  15896. * this happens if the control key (Cmd on Mac) was pressed during clicking.
  15897. */
  15898. select: function (selected, accumulate) {
  15899. var point = this,
  15900. series = point.series,
  15901. chart = series.chart;
  15902. selected = pick(selected, !point.selected);
  15903. // fire the event with the defalut handler
  15904. point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () {
  15905. point.selected = point.options.selected = selected;
  15906. series.options.data[inArray(point, series.data)] = point.options;
  15907. point.setState(selected && SELECT_STATE);
  15908. // unselect all other points unless Ctrl or Cmd + click
  15909. if (!accumulate) {
  15910. each(chart.getSelectedPoints(), function (loopPoint) {
  15911. if (loopPoint.selected && loopPoint !== point) {
  15912. loopPoint.selected = loopPoint.options.selected = false;
  15913. series.options.data[inArray(loopPoint, series.data)] = loopPoint.options;
  15914. loopPoint.setState(NORMAL_STATE);
  15915. loopPoint.firePointEvent('unselect');
  15916. }
  15917. });
  15918. }
  15919. });
  15920. },
  15921. /**
  15922. * Runs on mouse over the point
  15923. *
  15924. * @param {Object} e The event arguments
  15925. * @param {Boolean} byProximity Falsy for kd points that are closest to the mouse, or to
  15926. * actually hovered points. True for other points in shared tooltip.
  15927. */
  15928. onMouseOver: function (e, byProximity) {
  15929. var point = this,
  15930. series = point.series,
  15931. chart = series.chart,
  15932. tooltip = chart.tooltip,
  15933. hoverPoint = chart.hoverPoint;
  15934. if (chart.hoverSeries !== series) {
  15935. series.onMouseOver();
  15936. }
  15937. // set normal state to previous series
  15938. if (hoverPoint && hoverPoint !== point) {
  15939. hoverPoint.onMouseOut();
  15940. }
  15941. if (point.series) { // It may have been destroyed, #4130
  15942. // trigger the event
  15943. point.firePointEvent('mouseOver');
  15944. // update the tooltip
  15945. if (tooltip && (!tooltip.shared || series.noSharedTooltip)) {
  15946. tooltip.refresh(point, e);
  15947. }
  15948. // hover this
  15949. point.setState(HOVER_STATE);
  15950. if (!byProximity) {
  15951. chart.hoverPoint = point;
  15952. }
  15953. }
  15954. },
  15955. /**
  15956. * Runs on mouse out from the point
  15957. */
  15958. onMouseOut: function () {
  15959. var chart = this.series.chart,
  15960. hoverPoints = chart.hoverPoints;
  15961. this.firePointEvent('mouseOut');
  15962. if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887, #2240
  15963. this.setState();
  15964. chart.hoverPoint = null;
  15965. }
  15966. },
  15967. /**
  15968. * Import events from the series' and point's options. Only do it on
  15969. * demand, to save processing time on hovering.
  15970. */
  15971. importEvents: function () {
  15972. if (!this.hasImportedEvents) {
  15973. var point = this,
  15974. options = merge(point.series.options.point, point.options),
  15975. events = options.events,
  15976. eventType;
  15977. point.events = events;
  15978. for (eventType in events) {
  15979. addEvent(point, eventType, events[eventType]);
  15980. }
  15981. this.hasImportedEvents = true;
  15982. }
  15983. },
  15984. /**
  15985. * Set the point's state
  15986. * @param {String} state
  15987. */
  15988. setState: function (state, move) {
  15989. var point = this,
  15990. plotX = mathFloor(point.plotX), // #4586
  15991. plotY = point.plotY,
  15992. series = point.series,
  15993. stateOptions = series.options.states,
  15994. markerOptions = defaultPlotOptions[series.type].marker && series.options.marker,
  15995. normalDisabled = markerOptions && !markerOptions.enabled,
  15996. markerStateOptions = markerOptions && markerOptions.states[state],
  15997. stateDisabled = markerStateOptions && markerStateOptions.enabled === false,
  15998. stateMarkerGraphic = series.stateMarkerGraphic,
  15999. pointMarker = point.marker || {},
  16000. chart = series.chart,
  16001. radius,
  16002. halo = series.halo,
  16003. haloOptions,
  16004. newSymbol,
  16005. pointAttr;
  16006. state = state || NORMAL_STATE; // empty string
  16007. pointAttr = point.pointAttr[state] || series.pointAttr[state];
  16008. if (
  16009. // already has this state
  16010. (state === point.state && !move) ||
  16011. // selected points don't respond to hover
  16012. (point.selected && state !== SELECT_STATE) ||
  16013. // series' state options is disabled
  16014. (stateOptions[state] && stateOptions[state].enabled === false) ||
  16015. // general point marker's state options is disabled
  16016. (state && (stateDisabled || (normalDisabled && markerStateOptions.enabled === false))) ||
  16017. // individual point marker's state options is disabled
  16018. (state && pointMarker.states && pointMarker.states[state] && pointMarker.states[state].enabled === false) // #1610
  16019. ) {
  16020. return;
  16021. }
  16022. // apply hover styles to the existing point
  16023. if (point.graphic) {
  16024. radius = markerOptions && point.graphic.symbolName && pointAttr.r;
  16025. point.graphic.attr(merge(
  16026. pointAttr,
  16027. radius ? { // new symbol attributes (#507, #612)
  16028. x: plotX - radius,
  16029. y: plotY - radius,
  16030. width: 2 * radius,
  16031. height: 2 * radius
  16032. } : {}
  16033. ));
  16034. // Zooming in from a range with no markers to a range with markers
  16035. if (stateMarkerGraphic) {
  16036. stateMarkerGraphic.hide();
  16037. }
  16038. } else {
  16039. // if a graphic is not applied to each point in the normal state, create a shared
  16040. // graphic for the hover state
  16041. if (state && markerStateOptions) {
  16042. radius = markerStateOptions.radius;
  16043. newSymbol = pointMarker.symbol || series.symbol;
  16044. // If the point has another symbol than the previous one, throw away the
  16045. // state marker graphic and force a new one (#1459)
  16046. if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) {
  16047. stateMarkerGraphic = stateMarkerGraphic.destroy();
  16048. }
  16049. // Add a new state marker graphic
  16050. if (!stateMarkerGraphic) {
  16051. if (newSymbol) {
  16052. series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol(
  16053. newSymbol,
  16054. plotX - radius,
  16055. plotY - radius,
  16056. 2 * radius,
  16057. 2 * radius
  16058. )
  16059. .attr(pointAttr)
  16060. .add(series.markerGroup);
  16061. stateMarkerGraphic.currentSymbol = newSymbol;
  16062. }
  16063. // Move the existing graphic
  16064. } else {
  16065. stateMarkerGraphic[move ? 'animate' : 'attr']({ // #1054
  16066. x: plotX - radius,
  16067. y: plotY - radius
  16068. });
  16069. }
  16070. }
  16071. if (stateMarkerGraphic) {
  16072. stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY, chart.inverted) ? 'show' : 'hide'](); // #2450
  16073. stateMarkerGraphic.element.point = point; // #4310
  16074. }
  16075. }
  16076. // Show me your halo
  16077. haloOptions = stateOptions[state] && stateOptions[state].halo;
  16078. if (haloOptions && haloOptions.size) {
  16079. if (!halo) {
  16080. series.halo = halo = chart.renderer.path()
  16081. .add(chart.seriesGroup);
  16082. }
  16083. halo.attr(extend({
  16084. fill: Color(point.color || series.color).setOpacity(haloOptions.opacity).get()
  16085. }, haloOptions.attributes))[move ? 'animate' : 'attr']({
  16086. d: point.haloPath(haloOptions.size)
  16087. });
  16088. } else if (halo) {
  16089. halo.attr({ d: [] });
  16090. }
  16091. point.state = state;
  16092. },
  16093. haloPath: function (size) {
  16094. var series = this.series,
  16095. chart = series.chart,
  16096. plotBox = series.getPlotBox(),
  16097. inverted = chart.inverted;
  16098. return chart.renderer.symbols.circle(
  16099. plotBox.translateX + (inverted ? series.yAxis.len - this.plotY : this.plotX) - size,
  16100. plotBox.translateY + (inverted ? series.xAxis.len - this.plotX : this.plotY) - size,
  16101. size * 2,
  16102. size * 2
  16103. );
  16104. }
  16105. });
  16106. /*
  16107. * Extend the Series object with interaction
  16108. */
  16109. extend(Series.prototype, {
  16110. /**
  16111. * Series mouse over handler
  16112. */
  16113. onMouseOver: function () {
  16114. var series = this,
  16115. chart = series.chart,
  16116. hoverSeries = chart.hoverSeries;
  16117. // set normal state to previous series
  16118. if (hoverSeries && hoverSeries !== series) {
  16119. hoverSeries.onMouseOut();
  16120. }
  16121. // trigger the event, but to save processing time,
  16122. // only if defined
  16123. if (series.options.events.mouseOver) {
  16124. fireEvent(series, 'mouseOver');
  16125. }
  16126. // hover this
  16127. series.setState(HOVER_STATE);
  16128. chart.hoverSeries = series;
  16129. },
  16130. /**
  16131. * Series mouse out handler
  16132. */
  16133. onMouseOut: function () {
  16134. // trigger the event only if listeners exist
  16135. var series = this,
  16136. options = series.options,
  16137. chart = series.chart,
  16138. tooltip = chart.tooltip,
  16139. hoverPoint = chart.hoverPoint;
  16140. chart.hoverSeries = null; // #182, set to null before the mouseOut event fires
  16141. // trigger mouse out on the point, which must be in this series
  16142. if (hoverPoint) {
  16143. hoverPoint.onMouseOut();
  16144. }
  16145. // fire the mouse out event
  16146. if (series && options.events.mouseOut) {
  16147. fireEvent(series, 'mouseOut');
  16148. }
  16149. // hide the tooltip
  16150. if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) {
  16151. tooltip.hide();
  16152. }
  16153. // set normal state
  16154. series.setState();
  16155. },
  16156. /**
  16157. * Set the state of the graph
  16158. */
  16159. setState: function (state) {
  16160. var series = this,
  16161. options = series.options,
  16162. graph = series.graph,
  16163. stateOptions = options.states,
  16164. lineWidth = options.lineWidth,
  16165. attribs,
  16166. i = 0;
  16167. state = state || NORMAL_STATE;
  16168. if (series.state !== state) {
  16169. series.state = state;
  16170. if (stateOptions[state] && stateOptions[state].enabled === false) {
  16171. return;
  16172. }
  16173. if (state) {
  16174. lineWidth = stateOptions[state].lineWidth || lineWidth + (stateOptions[state].lineWidthPlus || 0); // #4035
  16175. }
  16176. if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML
  16177. attribs = {
  16178. 'stroke-width': lineWidth
  16179. };
  16180. // use attr because animate will cause any other animation on the graph to stop
  16181. graph.attr(attribs);
  16182. while (series['zoneGraph' + i]) {
  16183. series['zoneGraph' + i].attr(attribs);
  16184. i = i + 1;
  16185. }
  16186. }
  16187. }
  16188. },
  16189. /**
  16190. * Set the visibility of the graph
  16191. *
  16192. * @param vis {Boolean} True to show the series, false to hide. If UNDEFINED,
  16193. * the visibility is toggled.
  16194. */
  16195. setVisible: function (vis, redraw) {
  16196. var series = this,
  16197. chart = series.chart,
  16198. legendItem = series.legendItem,
  16199. showOrHide,
  16200. ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries,
  16201. oldVisibility = series.visible;
  16202. // if called without an argument, toggle visibility
  16203. series.visible = vis = series.userOptions.visible = vis === UNDEFINED ? !oldVisibility : vis;
  16204. showOrHide = vis ? 'show' : 'hide';
  16205. // show or hide elements
  16206. each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) {
  16207. if (series[key]) {
  16208. series[key][showOrHide]();
  16209. }
  16210. });
  16211. // hide tooltip (#1361)
  16212. if (chart.hoverSeries === series || (chart.hoverPoint && chart.hoverPoint.series) === series) {
  16213. series.onMouseOut();
  16214. }
  16215. if (legendItem) {
  16216. chart.legend.colorizeItem(series, vis);
  16217. }
  16218. // rescale or adapt to resized chart
  16219. series.isDirty = true;
  16220. // in a stack, all other series are affected
  16221. if (series.options.stacking) {
  16222. each(chart.series, function (otherSeries) {
  16223. if (otherSeries.options.stacking && otherSeries.visible) {
  16224. otherSeries.isDirty = true;
  16225. }
  16226. });
  16227. }
  16228. // show or hide linked series
  16229. each(series.linkedSeries, function (otherSeries) {
  16230. otherSeries.setVisible(vis, false);
  16231. });
  16232. if (ignoreHiddenSeries) {
  16233. chart.isDirtyBox = true;
  16234. }
  16235. if (redraw !== false) {
  16236. chart.redraw();
  16237. }
  16238. fireEvent(series, showOrHide);
  16239. },
  16240. /**
  16241. * Show the graph
  16242. */
  16243. show: function () {
  16244. this.setVisible(true);
  16245. },
  16246. /**
  16247. * Hide the graph
  16248. */
  16249. hide: function () {
  16250. this.setVisible(false);
  16251. },
  16252. /**
  16253. * Set the selected state of the graph
  16254. *
  16255. * @param selected {Boolean} True to select the series, false to unselect. If
  16256. * UNDEFINED, the selection state is toggled.
  16257. */
  16258. select: function (selected) {
  16259. var series = this;
  16260. // if called without an argument, toggle
  16261. series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected;
  16262. if (series.checkbox) {
  16263. series.checkbox.checked = selected;
  16264. }
  16265. fireEvent(series, selected ? 'select' : 'unselect');
  16266. },
  16267. drawTracker: TrackerMixin.drawTrackerGraph
  16268. });
  16269. // global variables
  16270. extend(Highcharts, {
  16271. // Constructors
  16272. Color: Color,
  16273. Point: Point,
  16274. Tick: Tick,
  16275. Renderer: Renderer,
  16276. SVGElement: SVGElement,
  16277. SVGRenderer: SVGRenderer,
  16278. // Various
  16279. arrayMin: arrayMin,
  16280. arrayMax: arrayMax,
  16281. charts: charts,
  16282. dateFormat: dateFormat,
  16283. error: error,
  16284. format: format,
  16285. pathAnim: pathAnim,
  16286. getOptions: getOptions,
  16287. hasBidiBug: hasBidiBug,
  16288. isTouchDevice: isTouchDevice,
  16289. setOptions: setOptions,
  16290. addEvent: addEvent,
  16291. removeEvent: removeEvent,
  16292. createElement: createElement,
  16293. discardElement: discardElement,
  16294. css: css,
  16295. each: each,
  16296. map: map,
  16297. merge: merge,
  16298. splat: splat,
  16299. extendClass: extendClass,
  16300. pInt: pInt,
  16301. svg: hasSVG,
  16302. canvas: useCanVG,
  16303. vml: !hasSVG && !useCanVG,
  16304. product: PRODUCT,
  16305. version: VERSION
  16306. });
  16307. }());