highcharts.src.js 722 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853
  1. // ==ClosureCompiler==
  2. // @compilation_level SIMPLE_OPTIMIZATIONS
  3. /**
  4. * @license Highcharts JS v4.2.7 (2016-09-21)
  5. *
  6. * (c) 2009-2016 Torstein Honsi
  7. *
  8. * License: www.highcharts.com/license
  9. */
  10. (function (root, factory) {
  11. if (typeof module === 'object' && module.exports) {
  12. module.exports = root.document ?
  13. factory(root) :
  14. factory;
  15. } else {
  16. root.Highcharts = factory(root);
  17. }
  18. }(typeof window !== 'undefined' ? window : this, function (win) { // eslint-disable-line no-undef
  19. // encapsulated variables
  20. var UNDEFINED,
  21. doc = win.document,
  22. math = Math,
  23. mathRound = math.round,
  24. mathFloor = math.floor,
  25. mathCeil = math.ceil,
  26. mathMax = math.max,
  27. mathMin = math.min,
  28. mathAbs = math.abs,
  29. mathCos = math.cos,
  30. mathSin = math.sin,
  31. mathPI = math.PI,
  32. deg2rad = mathPI * 2 / 360,
  33. // some variables
  34. userAgent = (win.navigator && win.navigator.userAgent) || '',
  35. isOpera = win.opera,
  36. isMS = /(msie|trident|edge)/i.test(userAgent) && !isOpera,
  37. docMode8 = doc && doc.documentMode === 8,
  38. isWebKit = !isMS && /AppleWebKit/.test(userAgent),
  39. isFirefox = /Firefox/.test(userAgent),
  40. isTouchDevice = /(Mobile|Android|Windows Phone)/.test(userAgent),
  41. SVG_NS = 'http://www.w3.org/2000/svg',
  42. hasSVG = doc && doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect,
  43. hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4, // issue #38
  44. useCanVG = doc && !hasSVG && !isMS && !!doc.createElement('canvas').getContext,
  45. Renderer,
  46. hasTouch,
  47. symbolSizes = {},
  48. idCounter = 0,
  49. garbageBin,
  50. defaultOptions,
  51. dateFormat, // function
  52. pathAnim,
  53. timeUnits,
  54. noop = function () {},
  55. charts = [],
  56. chartCount = 0,
  57. PRODUCT = 'Highcharts',
  58. VERSION = '4.2.7',
  59. // some constants for frequently used strings
  60. DIV = 'div',
  61. ABSOLUTE = 'absolute',
  62. RELATIVE = 'relative',
  63. HIDDEN = 'hidden',
  64. PREFIX = 'highcharts-',
  65. VISIBLE = 'visible',
  66. PX = 'px',
  67. NONE = 'none',
  68. M = 'M',
  69. L = 'L',
  70. numRegex = /[0-9]/g,
  71. NORMAL_STATE = '',
  72. HOVER_STATE = 'hover',
  73. SELECT_STATE = 'select',
  74. marginNames = ['plotTop', 'marginRight', 'marginBottom', 'plotLeft'],
  75. // Object for extending Axis
  76. AxisPlotLineOrBandExtension,
  77. // constants for attributes
  78. STROKE_WIDTH = 'stroke-width',
  79. // time methods, changed based on whether or not UTC is used
  80. Date, // Allow using a different Date class
  81. makeTime,
  82. timezoneOffset,
  83. getTimezoneOffset,
  84. getMinutes,
  85. getHours,
  86. getDay,
  87. getDate,
  88. getMonth,
  89. getFullYear,
  90. setMilliseconds,
  91. setSeconds,
  92. setMinutes,
  93. setHours,
  94. setDate,
  95. setMonth,
  96. setFullYear,
  97. // lookup over the types and the associated classes
  98. seriesTypes = {},
  99. Highcharts;
  100. /**
  101. * Provide error messages for debugging, with links to online explanation
  102. */
  103. function error(code, stop) {
  104. var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code;
  105. if (stop) {
  106. throw new Error(msg);
  107. }
  108. // else ...
  109. if (win.console) {
  110. console.log(msg); // eslint-disable-line no-console
  111. }
  112. }
  113. // The Highcharts namespace
  114. Highcharts = win.Highcharts ? error(16, true) : { win: win };
  115. Highcharts.seriesTypes = seriesTypes;
  116. var timers = [],
  117. getStyle,
  118. // Previous adapter functions
  119. inArray,
  120. each,
  121. grep,
  122. offset,
  123. map,
  124. addEvent,
  125. removeEvent,
  126. fireEvent,
  127. animate,
  128. stop;
  129. /**
  130. * An animator object. One instance applies to one property (attribute or style prop)
  131. * on one element.
  132. *
  133. * @param {object} elem The element to animate. May be a DOM element or a Highcharts SVGElement wrapper.
  134. * @param {object} options Animation options, including duration, easing, step and complete.
  135. * @param {object} prop The property to animate.
  136. */
  137. function Fx(elem, options, prop) {
  138. this.options = options;
  139. this.elem = elem;
  140. this.prop = prop;
  141. }
  142. Fx.prototype = {
  143. /**
  144. * Animating a path definition on SVGElement
  145. * @returns {undefined}
  146. */
  147. dSetter: function () {
  148. var start = this.paths[0],
  149. end = this.paths[1],
  150. ret = [],
  151. now = this.now,
  152. i = start.length,
  153. startVal;
  154. if (now === 1) { // land on the final path without adjustment points appended in the ends
  155. ret = this.toD;
  156. } else if (i === end.length && now < 1) {
  157. while (i--) {
  158. startVal = parseFloat(start[i]);
  159. ret[i] =
  160. isNaN(startVal) ? // a letter instruction like M or L
  161. start[i] :
  162. now * (parseFloat(end[i] - startVal)) + startVal;
  163. }
  164. } else { // if animation is finished or length not matching, land on right value
  165. ret = end;
  166. }
  167. this.elem.attr('d', ret);
  168. },
  169. /**
  170. * Update the element with the current animation step
  171. * @returns {undefined}
  172. */
  173. update: function () {
  174. var elem = this.elem,
  175. prop = this.prop, // if destroyed, it is null
  176. now = this.now,
  177. step = this.options.step;
  178. // Animation setter defined from outside
  179. if (this[prop + 'Setter']) {
  180. this[prop + 'Setter']();
  181. // Other animations on SVGElement
  182. } else if (elem.attr) {
  183. if (elem.element) {
  184. elem.attr(prop, now);
  185. }
  186. // HTML styles, raw HTML content like container size
  187. } else {
  188. elem.style[prop] = now + this.unit;
  189. }
  190. if (step) {
  191. step.call(elem, now, this);
  192. }
  193. },
  194. /**
  195. * Run an animation
  196. */
  197. run: function (from, to, unit) {
  198. var self = this,
  199. timer = function (gotoEnd) {
  200. return timer.stopped ? false : self.step(gotoEnd);
  201. },
  202. i;
  203. this.startTime = +new Date();
  204. this.start = from;
  205. this.end = to;
  206. this.unit = unit;
  207. this.now = this.start;
  208. this.pos = 0;
  209. timer.elem = this.elem;
  210. if (timer() && timers.push(timer) === 1) {
  211. timer.timerId = setInterval(function () {
  212. for (i = 0; i < timers.length; i++) {
  213. if (!timers[i]()) {
  214. timers.splice(i--, 1);
  215. }
  216. }
  217. if (!timers.length) {
  218. clearInterval(timer.timerId);
  219. }
  220. }, 13);
  221. }
  222. },
  223. /**
  224. * Run a single step in the animation
  225. * @param {Boolean} gotoEnd Whether to go to then endpoint of the animation after abort
  226. * @returns {Boolean} True if animation continues
  227. */
  228. step: function (gotoEnd) {
  229. var t = +new Date(),
  230. ret,
  231. done,
  232. options = this.options,
  233. elem = this.elem,
  234. complete = options.complete,
  235. duration = options.duration,
  236. curAnim = options.curAnim,
  237. i;
  238. if (elem.attr && !elem.element) { // #2616, element including flag is destroyed
  239. ret = false;
  240. } else if (gotoEnd || t >= duration + this.startTime) {
  241. this.now = this.end;
  242. this.pos = 1;
  243. this.update();
  244. curAnim[this.prop] = true;
  245. done = true;
  246. for (i in curAnim) {
  247. if (curAnim[i] !== true) {
  248. done = false;
  249. }
  250. }
  251. if (done && complete) {
  252. complete.call(elem);
  253. }
  254. ret = false;
  255. } else {
  256. this.pos = options.easing((t - this.startTime) / duration);
  257. this.now = this.start + ((this.end - this.start) * this.pos);
  258. this.update();
  259. ret = true;
  260. }
  261. return ret;
  262. },
  263. /**
  264. * Prepare start and end values so that the path can be animated one to one
  265. */
  266. initPath: function (elem, fromD, toD) {
  267. fromD = fromD || '';
  268. var shift,
  269. startX = elem.startX,
  270. endX = elem.endX,
  271. bezier = fromD.indexOf('C') > -1,
  272. numParams = bezier ? 7 : 3,
  273. fullLength,
  274. slice,
  275. i,
  276. start = fromD.split(' '),
  277. end = toD.slice(), // copy
  278. isArea = elem.isArea,
  279. positionFactor = isArea ? 2 : 1,
  280. reverse;
  281. /**
  282. * In splines make move points have six parameters like bezier curves
  283. */
  284. function sixify(arr) {
  285. i = arr.length;
  286. while (i--) {
  287. if (arr[i] === M || arr[i] === L) {
  288. arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]);
  289. }
  290. }
  291. }
  292. /**
  293. * Insert an array at the given position of another array
  294. */
  295. function insertSlice(arr, subArr, index) {
  296. [].splice.apply(
  297. arr,
  298. [index, 0].concat(subArr)
  299. );
  300. }
  301. /**
  302. * If shifting points, prepend a dummy point to the end path.
  303. */
  304. function prepend(arr, other) {
  305. while (arr.length < fullLength) {
  306. // Move to, line to or curve to?
  307. arr[0] = other[fullLength - arr.length];
  308. // Prepend a copy of the first point
  309. insertSlice(arr, arr.slice(0, numParams), 0);
  310. // For areas, the bottom path goes back again to the left, so we need
  311. // to append a copy of the last point.
  312. if (isArea) {
  313. insertSlice(arr, arr.slice(arr.length - numParams), arr.length);
  314. i--;
  315. }
  316. }
  317. arr[0] = 'M';
  318. }
  319. /**
  320. * Copy and append last point until the length matches the end length
  321. */
  322. function append(arr, other) {
  323. var i = (fullLength - arr.length) / numParams;
  324. while (i > 0 && i--) {
  325. // Pull out the slice that is going to be appended or inserted. In a line graph,
  326. // the positionFactor is 1, and the last point is sliced out. In an area graph,
  327. // the positionFactor is 2, causing the middle two points to be sliced out, since
  328. // an area path starts at left, follows the upper path then turns and follows the
  329. // bottom back.
  330. slice = arr.slice().splice(
  331. (arr.length / positionFactor) - numParams,
  332. numParams * positionFactor
  333. );
  334. // Move to, line to or curve to?
  335. slice[0] = other[fullLength - numParams - (i * numParams)];
  336. // Disable first control point
  337. if (bezier) {
  338. slice[numParams - 6] = slice[numParams - 2];
  339. slice[numParams - 5] = slice[numParams - 1];
  340. }
  341. // Now insert the slice, either in the middle (for areas) or at the end (for lines)
  342. insertSlice(arr, slice, arr.length / positionFactor);
  343. if (isArea) {
  344. i--;
  345. }
  346. }
  347. }
  348. if (bezier) {
  349. sixify(start);
  350. sixify(end);
  351. }
  352. // For sideways animation, find out how much we need to shift to get the start path Xs
  353. // to match the end path Xs.
  354. if (startX && endX) {
  355. for (i = 0; i < startX.length; i++) {
  356. if (startX[i] === endX[0]) { // Moving left, new points coming in on right
  357. shift = i;
  358. break;
  359. } else if (startX[0] === endX[endX.length - startX.length + i]) { // Moving right
  360. shift = i;
  361. reverse = true;
  362. break;
  363. }
  364. }
  365. if (shift === undefined) {
  366. start = [];
  367. }
  368. }
  369. if (start.length && Highcharts.isNumber(shift)) {
  370. // The common target length for the start and end array, where both
  371. // arrays are padded in opposite ends
  372. fullLength = end.length + shift * positionFactor * numParams;
  373. if (!reverse) {
  374. prepend(end, start);
  375. append(start, end);
  376. } else {
  377. prepend(start, end);
  378. append(end, start);
  379. }
  380. }
  381. return [start, end];
  382. }
  383. }; // End of Fx prototype
  384. /**
  385. * Extend an object with the members of another
  386. * @param {Object} a The object to be extended
  387. * @param {Object} b The object to add to the first one
  388. */
  389. var extend = Highcharts.extend = function (a, b) {
  390. var n;
  391. if (!a) {
  392. a = {};
  393. }
  394. for (n in b) {
  395. a[n] = b[n];
  396. }
  397. return a;
  398. };
  399. /**
  400. * Deep merge two or more objects and return a third object. If the first argument is
  401. * true, the contents of the second object is copied into the first object.
  402. * Previously this function redirected to jQuery.extend(true), but this had two limitations.
  403. * First, it deep merged arrays, which lead to workarounds in Highcharts. Second,
  404. * it copied properties from extended prototypes.
  405. */
  406. function merge() {
  407. var i,
  408. args = arguments,
  409. len,
  410. ret = {},
  411. doCopy = function (copy, original) {
  412. var value, key;
  413. // An object is replacing a primitive
  414. if (typeof copy !== 'object') {
  415. copy = {};
  416. }
  417. for (key in original) {
  418. if (original.hasOwnProperty(key)) {
  419. value = original[key];
  420. // Copy the contents of objects, but not arrays or DOM nodes
  421. if (Highcharts.isObject(value, true) &&
  422. key !== 'renderTo' && typeof value.nodeType !== 'number') {
  423. copy[key] = doCopy(copy[key] || {}, value);
  424. // Primitives and arrays are copied over directly
  425. } else {
  426. copy[key] = original[key];
  427. }
  428. }
  429. }
  430. return copy;
  431. };
  432. // If first argument is true, copy into the existing object. Used in setOptions.
  433. if (args[0] === true) {
  434. ret = args[1];
  435. args = Array.prototype.slice.call(args, 2);
  436. }
  437. // For each argument, extend the return
  438. len = args.length;
  439. for (i = 0; i < len; i++) {
  440. ret = doCopy(ret, args[i]);
  441. }
  442. return ret;
  443. }
  444. /**
  445. * Shortcut for parseInt
  446. * @param {Object} s
  447. * @param {Number} mag Magnitude
  448. */
  449. function pInt(s, mag) {
  450. return parseInt(s, mag || 10);
  451. }
  452. /**
  453. * Check for string
  454. * @param {Object} s
  455. */
  456. function isString(s) {
  457. return typeof s === 'string';
  458. }
  459. /**
  460. * Check for array
  461. * @param {Object} obj
  462. */
  463. function isArray(obj) {
  464. var str = Object.prototype.toString.call(obj);
  465. return str === '[object Array]' || str === '[object Array Iterator]';
  466. }
  467. /**
  468. * Check for object
  469. * @param {Object} obj
  470. * @param {Boolean} strict Also checks that the object is not an array
  471. */
  472. var isObject = Highcharts.isObject = function (obj, strict) {
  473. //debugger;
  474. return obj && typeof obj === 'object' && (!strict || !isArray(obj));
  475. };
  476. /**
  477. * Check for number
  478. * @param {Object} n
  479. */
  480. var isNumber = Highcharts.isNumber = function isNumber(n) {
  481. return typeof n === 'number' && !isNaN(n);
  482. };
  483. /**
  484. * Remove last occurence of an item from an array
  485. * @param {Array} arr
  486. * @param {Mixed} item
  487. */
  488. function erase(arr, item) {
  489. var i = arr.length;
  490. while (i--) {
  491. if (arr[i] === item) {
  492. arr.splice(i, 1);
  493. break;
  494. }
  495. }
  496. //return arr;
  497. }
  498. /**
  499. * Returns true if the object is not null or undefined.
  500. * @param {Object} obj
  501. */
  502. function defined(obj) {
  503. return obj !== UNDEFINED && obj !== null;
  504. }
  505. /**
  506. * Set or get an attribute or an object of attributes. Can't use jQuery attr because
  507. * it attempts to set expando properties on the SVG element, which is not allowed.
  508. *
  509. * @param {Object} elem The DOM element to receive the attribute(s)
  510. * @param {String|Object} prop The property or an abject of key-value pairs
  511. * @param {String} value The value if a single property is set
  512. */
  513. function attr(elem, prop, value) {
  514. var key,
  515. ret;
  516. // if the prop is a string
  517. if (isString(prop)) {
  518. // set the value
  519. if (defined(value)) {
  520. elem.setAttribute(prop, value);
  521. // get the value
  522. } else if (elem && elem.getAttribute) { // elem not defined when printing pie demo...
  523. ret = elem.getAttribute(prop);
  524. }
  525. // else if prop is defined, it is a hash of key/value pairs
  526. } else if (defined(prop) && isObject(prop)) {
  527. for (key in prop) {
  528. elem.setAttribute(key, prop[key]);
  529. }
  530. }
  531. return ret;
  532. }
  533. /**
  534. * Check if an element is an array, and if not, make it into an array.
  535. */
  536. function splat(obj) {
  537. return isArray(obj) ? obj : [obj];
  538. }
  539. /**
  540. * Set a timeout if the delay is given, otherwise perform the function synchronously
  541. * @param {Function} fn The function to perform
  542. * @param {Number} delay Delay in milliseconds
  543. * @param {Ojbect} context The context
  544. * @returns {Nubmer} An identifier for the timeout
  545. */
  546. function syncTimeout(fn, delay, context) {
  547. if (delay) {
  548. return setTimeout(fn, delay, context);
  549. }
  550. fn.call(0, context);
  551. }
  552. /**
  553. * Return the first value that is defined.
  554. */
  555. var pick = Highcharts.pick = function () {
  556. var args = arguments,
  557. i,
  558. arg,
  559. length = args.length;
  560. for (i = 0; i < length; i++) {
  561. arg = args[i];
  562. if (arg !== UNDEFINED && arg !== null) {
  563. return arg;
  564. }
  565. }
  566. };
  567. /**
  568. * Set CSS on a given element
  569. * @param {Object} el
  570. * @param {Object} styles Style object with camel case property names
  571. */
  572. function css(el, styles) {
  573. if (isMS && !hasSVG) { // #2686
  574. if (styles && styles.opacity !== UNDEFINED) {
  575. styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')';
  576. }
  577. }
  578. extend(el.style, styles);
  579. }
  580. /**
  581. * Utility function to create element with attributes and styles
  582. * @param {Object} tag
  583. * @param {Object} attribs
  584. * @param {Object} styles
  585. * @param {Object} parent
  586. * @param {Object} nopad
  587. */
  588. function createElement(tag, attribs, styles, parent, nopad) {
  589. var el = doc.createElement(tag);
  590. if (attribs) {
  591. extend(el, attribs);
  592. }
  593. if (nopad) {
  594. css(el, { padding: 0, border: 'none', margin: 0 });
  595. }
  596. if (styles) {
  597. css(el, styles);
  598. }
  599. if (parent) {
  600. parent.appendChild(el);
  601. }
  602. return el;
  603. }
  604. /**
  605. * Extend a prototyped class by new members
  606. * @param {Object} parent
  607. * @param {Object} members
  608. */
  609. function extendClass(Parent, members) {
  610. var object = function () {
  611. };
  612. object.prototype = new Parent();
  613. extend(object.prototype, members);
  614. return object;
  615. }
  616. /**
  617. * Pad a string to a given length by adding 0 to the beginning
  618. * @param {Number} number
  619. * @param {Number} length
  620. */
  621. function pad(number, length, padder) {
  622. return new Array((length || 2) + 1 - String(number).length).join(padder || 0) + number;
  623. }
  624. /**
  625. * Return a length based on either the integer value, or a percentage of a base.
  626. */
  627. function relativeLength(value, base) {
  628. return (/%$/).test(value) ? base * parseFloat(value) / 100 : parseFloat(value);
  629. }
  630. /**
  631. * Wrap a method with extended functionality, preserving the original function
  632. * @param {Object} obj The context object that the method belongs to
  633. * @param {String} method The name of the method to extend
  634. * @param {Function} func A wrapper function callback. This function is called with the same arguments
  635. * as the original function, except that the original function is unshifted and passed as the first
  636. * argument.
  637. */
  638. var wrap = Highcharts.wrap = function (obj, method, func) {
  639. var proceed = obj[method];
  640. obj[method] = function () {
  641. var args = Array.prototype.slice.call(arguments);
  642. args.unshift(proceed);
  643. return func.apply(this, args);
  644. };
  645. };
  646. function getTZOffset(timestamp) {
  647. return ((getTimezoneOffset && getTimezoneOffset(timestamp)) || timezoneOffset || 0) * 60000;
  648. }
  649. /**
  650. * Based on http://www.php.net/manual/en/function.strftime.php
  651. * @param {String} format
  652. * @param {Number} timestamp
  653. * @param {Boolean} capitalize
  654. */
  655. dateFormat = function (format, timestamp, capitalize) {
  656. if (!defined(timestamp) || isNaN(timestamp)) {
  657. return defaultOptions.lang.invalidDate || '';
  658. }
  659. format = pick(format, '%Y-%m-%d %H:%M:%S');
  660. var date = new Date(timestamp - getTZOffset(timestamp)),
  661. key, // used in for constuct below
  662. // get the basic time values
  663. hours = date[getHours](),
  664. day = date[getDay](),
  665. dayOfMonth = date[getDate](),
  666. month = date[getMonth](),
  667. fullYear = date[getFullYear](),
  668. lang = defaultOptions.lang,
  669. langWeekdays = lang.weekdays,
  670. shortWeekdays = lang.shortWeekdays,
  671. // List all format keys. Custom formats can be added from the outside.
  672. replacements = extend({
  673. // Day
  674. 'a': shortWeekdays ? shortWeekdays[day] : langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon'
  675. 'A': langWeekdays[day], // Long weekday, like 'Monday'
  676. 'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31
  677. 'e': pad(dayOfMonth, 2, ' '), // Day of the month, 1 through 31
  678. 'w': day,
  679. // Week (none implemented)
  680. //'W': weekNumber(),
  681. // Month
  682. 'b': lang.shortMonths[month], // Short month, like 'Jan'
  683. 'B': lang.months[month], // Long month, like 'January'
  684. 'm': pad(month + 1), // Two digit month number, 01 through 12
  685. // Year
  686. 'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009
  687. 'Y': fullYear, // Four digits year, like 2009
  688. // Time
  689. 'H': pad(hours), // Two digits hours in 24h format, 00 through 23
  690. 'k': hours, // Hours in 24h format, 0 through 23
  691. 'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11
  692. 'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12
  693. 'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59
  694. 'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM
  695. 'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM
  696. 'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59
  697. 'L': pad(mathRound(timestamp % 1000), 3) // Milliseconds (naming from Ruby)
  698. }, Highcharts.dateFormats);
  699. // do the replaces
  700. for (key in replacements) {
  701. while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster
  702. format = format.replace('%' + key, typeof replacements[key] === 'function' ? replacements[key](timestamp) : replacements[key]);
  703. }
  704. }
  705. // Optionally capitalize the string and return
  706. return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format;
  707. };
  708. /**
  709. * Format a single variable. Similar to sprintf, without the % prefix.
  710. */
  711. function formatSingle(format, val) {
  712. var floatRegex = /f$/,
  713. decRegex = /\.([0-9])/,
  714. lang = defaultOptions.lang,
  715. decimals;
  716. if (floatRegex.test(format)) { // float
  717. decimals = format.match(decRegex);
  718. decimals = decimals ? decimals[1] : -1;
  719. if (val !== null) {
  720. val = Highcharts.numberFormat(
  721. val,
  722. decimals,
  723. lang.decimalPoint,
  724. format.indexOf(',') > -1 ? lang.thousandsSep : ''
  725. );
  726. }
  727. } else {
  728. val = dateFormat(format, val);
  729. }
  730. return val;
  731. }
  732. /**
  733. * Format a string according to a subset of the rules of Python's String.format method.
  734. */
  735. function format(str, ctx) {
  736. var splitter = '{',
  737. isInside = false,
  738. segment,
  739. valueAndFormat,
  740. path,
  741. i,
  742. len,
  743. ret = [],
  744. val,
  745. index;
  746. while ((index = str.indexOf(splitter)) !== -1) {
  747. segment = str.slice(0, index);
  748. if (isInside) { // we're on the closing bracket looking back
  749. valueAndFormat = segment.split(':');
  750. path = valueAndFormat.shift().split('.'); // get first and leave format
  751. len = path.length;
  752. val = ctx;
  753. // Assign deeper paths
  754. for (i = 0; i < len; i++) {
  755. val = val[path[i]];
  756. }
  757. // Format the replacement
  758. if (valueAndFormat.length) {
  759. val = formatSingle(valueAndFormat.join(':'), val);
  760. }
  761. // Push the result and advance the cursor
  762. ret.push(val);
  763. } else {
  764. ret.push(segment);
  765. }
  766. str = str.slice(index + 1); // the rest
  767. isInside = !isInside; // toggle
  768. splitter = isInside ? '}' : '{'; // now look for next matching bracket
  769. }
  770. ret.push(str);
  771. return ret.join('');
  772. }
  773. /**
  774. * Get the magnitude of a number
  775. */
  776. function getMagnitude(num) {
  777. return math.pow(10, mathFloor(math.log(num) / math.LN10));
  778. }
  779. /**
  780. * Take an interval and normalize it to multiples of 1, 2, 2.5 and 5
  781. * @param {Number} interval
  782. * @param {Array} multiples
  783. * @param {Number} magnitude
  784. * @param {Object} options
  785. */
  786. function normalizeTickInterval(interval, multiples, magnitude, allowDecimals, preventExceed) {
  787. var normalized,
  788. i,
  789. retInterval = interval;
  790. // round to a tenfold of 1, 2, 2.5 or 5
  791. magnitude = pick(magnitude, 1);
  792. normalized = interval / magnitude;
  793. // multiples for a linear scale
  794. if (!multiples) {
  795. multiples = [1, 2, 2.5, 5, 10];
  796. // the allowDecimals option
  797. if (allowDecimals === false) {
  798. if (magnitude === 1) {
  799. multiples = [1, 2, 5, 10];
  800. } else if (magnitude <= 0.1) {
  801. multiples = [1 / magnitude];
  802. }
  803. }
  804. }
  805. // normalize the interval to the nearest multiple
  806. for (i = 0; i < multiples.length; i++) {
  807. retInterval = multiples[i];
  808. if ((preventExceed && retInterval * magnitude >= interval) || // only allow tick amounts smaller than natural
  809. (!preventExceed && (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2))) {
  810. break;
  811. }
  812. }
  813. // multiply back to the correct magnitude
  814. retInterval *= magnitude;
  815. return retInterval;
  816. }
  817. /**
  818. * Utility method that sorts an object array and keeping the order of equal items.
  819. * ECMA script standard does not specify the behaviour when items are equal.
  820. */
  821. function stableSort(arr, sortFunction) {
  822. var length = arr.length,
  823. sortValue,
  824. i;
  825. // Add index to each item
  826. for (i = 0; i < length; i++) {
  827. arr[i].safeI = i; // stable sort index
  828. }
  829. arr.sort(function (a, b) {
  830. sortValue = sortFunction(a, b);
  831. return sortValue === 0 ? a.safeI - b.safeI : sortValue;
  832. });
  833. // Remove index from items
  834. for (i = 0; i < length; i++) {
  835. delete arr[i].safeI; // stable sort index
  836. }
  837. }
  838. /**
  839. * Non-recursive method to find the lowest member of an array. Math.min raises a maximum
  840. * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
  841. * method is slightly slower, but safe.
  842. */
  843. function arrayMin(data) {
  844. var i = data.length,
  845. min = data[0];
  846. while (i--) {
  847. if (data[i] < min) {
  848. min = data[i];
  849. }
  850. }
  851. return min;
  852. }
  853. /**
  854. * Non-recursive method to find the lowest member of an array. Math.min raises a maximum
  855. * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
  856. * method is slightly slower, but safe.
  857. */
  858. function arrayMax(data) {
  859. var i = data.length,
  860. max = data[0];
  861. while (i--) {
  862. if (data[i] > max) {
  863. max = data[i];
  864. }
  865. }
  866. return max;
  867. }
  868. /**
  869. * Utility method that destroys any SVGElement or VMLElement that are properties on the given object.
  870. * It loops all properties and invokes destroy if there is a destroy method. The property is
  871. * then delete'ed.
  872. * @param {Object} The object to destroy properties on
  873. * @param {Object} Exception, do not destroy this property, only delete it.
  874. */
  875. function destroyObjectProperties(obj, except) {
  876. var n;
  877. for (n in obj) {
  878. // If the object is non-null and destroy is defined
  879. if (obj[n] && obj[n] !== except && obj[n].destroy) {
  880. // Invoke the destroy
  881. obj[n].destroy();
  882. }
  883. // Delete the property from the object.
  884. delete obj[n];
  885. }
  886. }
  887. /**
  888. * Discard an element by moving it to the bin and delete
  889. * @param {Object} The HTML node to discard
  890. */
  891. function discardElement(element) {
  892. // create a garbage bin element, not part of the DOM
  893. if (!garbageBin) {
  894. garbageBin = createElement(DIV);
  895. }
  896. // move the node and empty bin
  897. if (element) {
  898. garbageBin.appendChild(element);
  899. }
  900. garbageBin.innerHTML = '';
  901. }
  902. /**
  903. * Fix JS round off float errors
  904. * @param {Number} num
  905. */
  906. function correctFloat(num, prec) {
  907. return parseFloat(
  908. num.toPrecision(prec || 14)
  909. );
  910. }
  911. /**
  912. * Set the global animation to either a given value, or fall back to the
  913. * given chart's animation option
  914. * @param {Object} animation
  915. * @param {Object} chart
  916. */
  917. function setAnimation(animation, chart) {
  918. chart.renderer.globalAnimation = pick(animation, chart.animation);
  919. }
  920. /**
  921. * Get the animation in object form, where a disabled animation is always
  922. * returned with duration: 0
  923. */
  924. function animObject(animation) {
  925. return isObject(animation) ? merge(animation) : { duration: animation ? 500 : 0 };
  926. }
  927. /**
  928. * The time unit lookup
  929. */
  930. timeUnits = {
  931. millisecond: 1,
  932. second: 1000,
  933. minute: 60000,
  934. hour: 3600000,
  935. day: 24 * 3600000,
  936. week: 7 * 24 * 3600000,
  937. month: 28 * 24 * 3600000,
  938. year: 364 * 24 * 3600000
  939. };
  940. /**
  941. * Format a number and return a string based on input settings
  942. * @param {Number} number The input number to format
  943. * @param {Number} decimals The amount of decimals
  944. * @param {String} decimalPoint The decimal point, defaults to the one given in the lang options
  945. * @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options
  946. */
  947. Highcharts.numberFormat = function (number, decimals, decimalPoint, thousandsSep) {
  948. number = +number || 0;
  949. decimals = +decimals;
  950. var lang = defaultOptions.lang,
  951. origDec = (number.toString().split('.')[1] || '').length,
  952. decimalComponent,
  953. strinteger,
  954. thousands,
  955. absNumber = Math.abs(number),
  956. ret;
  957. if (decimals === -1) {
  958. decimals = Math.min(origDec, 20); // Preserve decimals. Not huge numbers (#3793).
  959. } else if (!isNumber(decimals)) {
  960. decimals = 2;
  961. }
  962. // A string containing the positive integer component of the number
  963. strinteger = String(pInt(absNumber.toFixed(decimals)));
  964. // Leftover after grouping into thousands. Can be 0, 1 or 3.
  965. thousands = strinteger.length > 3 ? strinteger.length % 3 : 0;
  966. // Language
  967. decimalPoint = pick(decimalPoint, lang.decimalPoint);
  968. thousandsSep = pick(thousandsSep, lang.thousandsSep);
  969. // Start building the return
  970. ret = number < 0 ? '-' : '';
  971. // Add the leftover after grouping into thousands. For example, in the number 42 000 000,
  972. // this line adds 42.
  973. ret += thousands ? strinteger.substr(0, thousands) + thousandsSep : '';
  974. // Add the remaining thousands groups, joined by the thousands separator
  975. ret += strinteger.substr(thousands).replace(/(\d{3})(?=\d)/g, '$1' + thousandsSep);
  976. // Add the decimal point and the decimal component
  977. if (decimals) {
  978. // Get the decimal component, and add power to avoid rounding errors with float numbers (#4573)
  979. decimalComponent = Math.abs(absNumber - strinteger + Math.pow(10, -Math.max(decimals, origDec) - 1));
  980. ret += decimalPoint + decimalComponent.toFixed(decimals).slice(2);
  981. }
  982. return ret;
  983. };
  984. /**
  985. * Easing definition
  986. * @param {Number} pos Current position, ranging from 0 to 1
  987. */
  988. Math.easeInOutSine = function (pos) {
  989. return -0.5 * (Math.cos(Math.PI * pos) - 1);
  990. };
  991. /**
  992. * Internal method to return CSS value for given element and property
  993. */
  994. getStyle = function (el, prop) {
  995. var style;
  996. // For width and height, return the actual inner pixel size (#4913)
  997. if (prop === 'width') {
  998. return Math.min(el.offsetWidth, el.scrollWidth) - getStyle(el, 'padding-left') - getStyle(el, 'padding-right');
  999. } else if (prop === 'height') {
  1000. return Math.min(el.offsetHeight, el.scrollHeight) - getStyle(el, 'padding-top') - getStyle(el, 'padding-bottom');
  1001. }
  1002. // Otherwise, get the computed style
  1003. style = win.getComputedStyle(el, undefined);
  1004. return style && pInt(style.getPropertyValue(prop));
  1005. };
  1006. /**
  1007. * Return the index of an item in an array, or -1 if not found
  1008. */
  1009. inArray = function (item, arr) {
  1010. return arr.indexOf ? arr.indexOf(item) : [].indexOf.call(arr, item);
  1011. };
  1012. /**
  1013. * Filter an array
  1014. */
  1015. grep = function (elements, callback) {
  1016. return [].filter.call(elements, callback);
  1017. };
  1018. /**
  1019. * Map an array
  1020. */
  1021. map = function (arr, fn) {
  1022. var results = [],
  1023. i = 0,
  1024. len = arr.length;
  1025. for (; i < len; i++) {
  1026. results[i] = fn.call(arr[i], arr[i], i, arr);
  1027. }
  1028. return results;
  1029. };
  1030. /**
  1031. * Get the element's offset position, corrected by overflow:auto.
  1032. */
  1033. offset = function (el) {
  1034. var docElem = doc.documentElement,
  1035. box = el.getBoundingClientRect();
  1036. return {
  1037. top: box.top + (win.pageYOffset || docElem.scrollTop) - (docElem.clientTop || 0),
  1038. left: box.left + (win.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || 0)
  1039. };
  1040. };
  1041. /**
  1042. * Stop running animation.
  1043. * A possible extension to this would be to stop a single property, when
  1044. * we want to continue animating others. Then assign the prop to the timer
  1045. * in the Fx.run method, and check for the prop here. This would be an improvement
  1046. * in all cases where we stop the animation from .attr. Instead of stopping
  1047. * everything, we can just stop the actual attributes we're setting.
  1048. */
  1049. stop = function (el) {
  1050. var i = timers.length;
  1051. // Remove timers related to this element (#4519)
  1052. while (i--) {
  1053. if (timers[i].elem === el) {
  1054. timers[i].stopped = true; // #4667
  1055. }
  1056. }
  1057. };
  1058. /**
  1059. * Utility for iterating over an array.
  1060. * @param {Array} arr
  1061. * @param {Function} fn
  1062. */
  1063. each = function (arr, fn) { // modern browsers
  1064. return Array.prototype.forEach.call(arr, fn);
  1065. };
  1066. /**
  1067. * Add an event listener
  1068. */
  1069. addEvent = function (el, type, fn) {
  1070. var events = el.hcEvents = el.hcEvents || {};
  1071. function wrappedFn(e) {
  1072. e.target = e.srcElement || win; // #2820
  1073. fn.call(el, e);
  1074. }
  1075. // Handle DOM events in modern browsers
  1076. if (el.addEventListener) {
  1077. el.addEventListener(type, fn, false);
  1078. // Handle old IE implementation
  1079. } else if (el.attachEvent) {
  1080. if (!el.hcEventsIE) {
  1081. el.hcEventsIE = {};
  1082. }
  1083. // Link wrapped fn with original fn, so we can get this in removeEvent
  1084. el.hcEventsIE[fn.toString()] = wrappedFn;
  1085. el.attachEvent('on' + type, wrappedFn);
  1086. }
  1087. if (!events[type]) {
  1088. events[type] = [];
  1089. }
  1090. events[type].push(fn);
  1091. };
  1092. /**
  1093. * Remove event added with addEvent
  1094. */
  1095. removeEvent = function (el, type, fn) {
  1096. var events,
  1097. hcEvents = el.hcEvents,
  1098. index;
  1099. function removeOneEvent(type, fn) {
  1100. if (el.removeEventListener) {
  1101. el.removeEventListener(type, fn, false);
  1102. } else if (el.attachEvent) {
  1103. fn = el.hcEventsIE[fn.toString()];
  1104. el.detachEvent('on' + type, fn);
  1105. }
  1106. }
  1107. function removeAllEvents() {
  1108. var types,
  1109. len,
  1110. n;
  1111. if (!el.nodeName) {
  1112. return; // break on non-DOM events
  1113. }
  1114. if (type) {
  1115. types = {};
  1116. types[type] = true;
  1117. } else {
  1118. types = hcEvents;
  1119. }
  1120. for (n in types) {
  1121. if (hcEvents[n]) {
  1122. len = hcEvents[n].length;
  1123. while (len--) {
  1124. removeOneEvent(n, hcEvents[n][len]);
  1125. }
  1126. }
  1127. }
  1128. }
  1129. if (hcEvents) {
  1130. if (type) {
  1131. events = hcEvents[type] || [];
  1132. if (fn) {
  1133. index = inArray(fn, events);
  1134. if (index > -1) {
  1135. events.splice(index, 1);
  1136. hcEvents[type] = events;
  1137. }
  1138. removeOneEvent(type, fn);
  1139. } else {
  1140. removeAllEvents();
  1141. hcEvents[type] = [];
  1142. }
  1143. } else {
  1144. removeAllEvents();
  1145. el.hcEvents = {};
  1146. }
  1147. }
  1148. };
  1149. /**
  1150. * Fire an event on a custom object
  1151. */
  1152. fireEvent = function (el, type, eventArguments, defaultFunction) {
  1153. var e,
  1154. hcEvents = el.hcEvents,
  1155. events,
  1156. len,
  1157. i,
  1158. fn;
  1159. eventArguments = eventArguments || {};
  1160. if (doc.createEvent && (el.dispatchEvent || el.fireEvent)) {
  1161. e = doc.createEvent('Events');
  1162. e.initEvent(type, true, true);
  1163. e.target = el;
  1164. extend(e, eventArguments);
  1165. if (el.dispatchEvent) {
  1166. el.dispatchEvent(e);
  1167. } else {
  1168. el.fireEvent(type, e);
  1169. }
  1170. } else if (hcEvents) {
  1171. events = hcEvents[type] || [];
  1172. len = events.length;
  1173. // Attach a simple preventDefault function to skip default handler if called.
  1174. // The built-in defaultPrevented property is not overwritable (#5112)
  1175. if (!eventArguments.preventDefault) {
  1176. eventArguments.preventDefault = function () {
  1177. eventArguments.defaultPrevented = true;
  1178. };
  1179. }
  1180. eventArguments.target = el;
  1181. // If the type is not set, we're running a custom event (#2297). If it is set,
  1182. // we're running a browser event, and setting it will cause en error in
  1183. // IE8 (#2465).
  1184. if (!eventArguments.type) {
  1185. eventArguments.type = type;
  1186. }
  1187. for (i = 0; i < len; i++) {
  1188. fn = events[i];
  1189. // If the event handler return false, prevent the default handler from executing
  1190. if (fn && fn.call(el, eventArguments) === false) {
  1191. eventArguments.preventDefault();
  1192. }
  1193. }
  1194. }
  1195. // Run the default if not prevented
  1196. if (defaultFunction && !eventArguments.defaultPrevented) {
  1197. defaultFunction(eventArguments);
  1198. }
  1199. };
  1200. /**
  1201. * The global animate method, which uses Fx to create individual animators.
  1202. */
  1203. animate = function (el, params, opt) {
  1204. var start,
  1205. unit = '',
  1206. end,
  1207. fx,
  1208. args,
  1209. prop;
  1210. if (!isObject(opt)) { // Number or undefined/null
  1211. args = arguments;
  1212. opt = {
  1213. duration: args[2],
  1214. easing: args[3],
  1215. complete: args[4]
  1216. };
  1217. }
  1218. if (!isNumber(opt.duration)) {
  1219. opt.duration = 400;
  1220. }
  1221. opt.easing = typeof opt.easing === 'function' ? opt.easing : (Math[opt.easing] || Math.easeInOutSine);
  1222. opt.curAnim = merge(params);
  1223. for (prop in params) {
  1224. fx = new Fx(el, opt, prop);
  1225. end = null;
  1226. if (prop === 'd') {
  1227. fx.paths = fx.initPath(
  1228. el,
  1229. el.d,
  1230. params.d
  1231. );
  1232. fx.toD = params.d;
  1233. start = 0;
  1234. end = 1;
  1235. } else if (el.attr) {
  1236. start = el.attr(prop);
  1237. } else {
  1238. start = parseFloat(getStyle(el, prop)) || 0;
  1239. if (prop !== 'opacity') {
  1240. unit = 'px';
  1241. }
  1242. }
  1243. if (!end) {
  1244. end = params[prop];
  1245. }
  1246. if (end.match && end.match('px')) {
  1247. end = end.replace(/px/g, ''); // #4351
  1248. }
  1249. fx.run(start, end, unit);
  1250. }
  1251. };
  1252. /**
  1253. * Register Highcharts as a plugin in jQuery
  1254. */
  1255. if (win.jQuery) {
  1256. win.jQuery.fn.highcharts = function () {
  1257. var args = [].slice.call(arguments);
  1258. if (this[0]) { // this[0] is the renderTo div
  1259. // Create the chart
  1260. if (args[0]) {
  1261. new Highcharts[ // eslint-disable-line no-new
  1262. isString(args[0]) ? args.shift() : 'Chart' // Constructor defaults to Chart
  1263. ](this[0], args[0], args[1]);
  1264. return this;
  1265. }
  1266. // When called without parameters or with the return argument, return an existing chart
  1267. return charts[attr(this[0], 'data-highcharts-chart')];
  1268. }
  1269. };
  1270. }
  1271. /**
  1272. * Compatibility section to add support for legacy IE. This can be removed if old IE
  1273. * support is not needed.
  1274. */
  1275. if (doc && !doc.defaultView) {
  1276. getStyle = function (el, prop) {
  1277. var val,
  1278. alias = { width: 'clientWidth', height: 'clientHeight' }[prop];
  1279. if (el.style[prop]) {
  1280. return pInt(el.style[prop]);
  1281. }
  1282. if (prop === 'opacity') {
  1283. prop = 'filter';
  1284. }
  1285. // Getting the rendered width and height
  1286. if (alias) {
  1287. el.style.zoom = 1;
  1288. return Math.max(el[alias] - 2 * getStyle(el, 'padding'), 0);
  1289. }
  1290. val = el.currentStyle[prop.replace(/\-(\w)/g, function (a, b) {
  1291. return b.toUpperCase();
  1292. })];
  1293. if (prop === 'filter') {
  1294. val = val.replace(
  1295. /alpha\(opacity=([0-9]+)\)/,
  1296. function (a, b) {
  1297. return b / 100;
  1298. }
  1299. );
  1300. }
  1301. return val === '' ? 1 : pInt(val);
  1302. };
  1303. }
  1304. if (!Array.prototype.forEach) {
  1305. each = function (arr, fn) { // legacy
  1306. var i = 0,
  1307. len = arr.length;
  1308. for (; i < len; i++) {
  1309. if (fn.call(arr[i], arr[i], i, arr) === false) {
  1310. return i;
  1311. }
  1312. }
  1313. };
  1314. }
  1315. if (!Array.prototype.indexOf) {
  1316. inArray = function (item, arr) {
  1317. var len,
  1318. i = 0;
  1319. if (arr) {
  1320. len = arr.length;
  1321. for (; i < len; i++) {
  1322. if (arr[i] === item) {
  1323. return i;
  1324. }
  1325. }
  1326. }
  1327. return -1;
  1328. };
  1329. }
  1330. if (!Array.prototype.filter) {
  1331. grep = function (elements, fn) {
  1332. var ret = [],
  1333. i = 0,
  1334. length = elements.length;
  1335. for (; i < length; i++) {
  1336. if (fn(elements[i], i)) {
  1337. ret.push(elements[i]);
  1338. }
  1339. }
  1340. return ret;
  1341. };
  1342. }
  1343. //--- End compatibility section ---
  1344. // Expose utilities
  1345. Highcharts.Fx = Fx;
  1346. Highcharts.inArray = inArray;
  1347. Highcharts.each = each;
  1348. Highcharts.grep = grep;
  1349. Highcharts.offset = offset;
  1350. Highcharts.map = map;
  1351. Highcharts.addEvent = addEvent;
  1352. Highcharts.removeEvent = removeEvent;
  1353. Highcharts.fireEvent = fireEvent;
  1354. Highcharts.animate = animate;
  1355. Highcharts.animObject = animObject;
  1356. Highcharts.stop = stop;
  1357. /* ****************************************************************************
  1358. * Handle the options *
  1359. *****************************************************************************/
  1360. defaultOptions = {
  1361. colors: ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c',
  1362. '#8085e9', '#f15c80', '#e4d354', '#2b908f', '#f45b5b', '#91e8e1'],
  1363. symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'],
  1364. lang: {
  1365. loading: 'Loading...',
  1366. months: ['January', 'February', 'March', 'April', 'May', 'June', 'July',
  1367. 'August', 'September', 'October', 'November', 'December'],
  1368. shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  1369. weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  1370. // invalidDate: '',
  1371. decimalPoint: '.',
  1372. numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels
  1373. resetZoom: 'Reset zoom',
  1374. resetZoomTitle: 'Reset zoom level 1:1',
  1375. thousandsSep: ' '
  1376. },
  1377. global: {
  1378. useUTC: true,
  1379. //timezoneOffset: 0,
  1380. canvasToolsURL: 'http://code.highcharts.com/modules/canvas-tools.js',
  1381. VMLRadialGradientURL: 'http://code.highcharts.com/4.2.7/gfx/vml-radial-gradient.png'
  1382. },
  1383. chart: {
  1384. //animation: true,
  1385. //alignTicks: false,
  1386. //reflow: true,
  1387. //className: null,
  1388. //events: { load, selection },
  1389. //margin: [null],
  1390. //marginTop: null,
  1391. //marginRight: null,
  1392. //marginBottom: null,
  1393. //marginLeft: null,
  1394. borderColor: '#4572A7',
  1395. //borderWidth: 0,
  1396. borderRadius: 0,
  1397. defaultSeriesType: 'line',
  1398. ignoreHiddenSeries: true,
  1399. //inverted: false,
  1400. //shadow: false,
  1401. spacing: [10, 10, 15, 10],
  1402. //spacingTop: 10,
  1403. //spacingRight: 10,
  1404. //spacingBottom: 15,
  1405. //spacingLeft: 10,
  1406. //style: {
  1407. // fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font
  1408. // fontSize: '12px'
  1409. //},
  1410. backgroundColor: '#FFFFFF',
  1411. //plotBackgroundColor: null,
  1412. plotBorderColor: '#C0C0C0',
  1413. //plotBorderWidth: 0,
  1414. //plotShadow: false,
  1415. //zoomType: ''
  1416. resetZoomButton: {
  1417. theme: {
  1418. zIndex: 20
  1419. },
  1420. position: {
  1421. align: 'right',
  1422. x: -10,
  1423. //verticalAlign: 'top',
  1424. y: 10
  1425. }
  1426. // relativeTo: 'plot'
  1427. },
  1428. width: null,
  1429. height: null
  1430. },
  1431. title: {
  1432. text: 'Chart title',
  1433. align: 'center',
  1434. // floating: false,
  1435. margin: 15,
  1436. // x: 0,
  1437. // verticalAlign: 'top',
  1438. // y: null,
  1439. style: {
  1440. color: '#333333',
  1441. fontSize: '18px'
  1442. },
  1443. widthAdjust: -44
  1444. },
  1445. subtitle: {
  1446. text: '',
  1447. align: 'center',
  1448. // floating: false
  1449. // x: 0,
  1450. // verticalAlign: 'top',
  1451. // y: null,
  1452. style: {
  1453. color: '#555555'
  1454. },
  1455. widthAdjust: -44
  1456. },
  1457. plotOptions: {
  1458. line: { // base series options
  1459. allowPointSelect: false,
  1460. showCheckbox: false,
  1461. animation: {
  1462. duration: 1000
  1463. },
  1464. //connectNulls: false,
  1465. //cursor: 'default',
  1466. //clip: true,
  1467. //dashStyle: null,
  1468. //enableMouseTracking: true,
  1469. events: {},
  1470. //legendIndex: 0,
  1471. //linecap: 'round',
  1472. lineWidth: 2,
  1473. //shadow: false,
  1474. // stacking: null,
  1475. marker: {
  1476. //enabled: true,
  1477. //symbol: null,
  1478. lineWidth: 0,
  1479. radius: 4,
  1480. lineColor: '#FFFFFF',
  1481. //fillColor: null,
  1482. states: { // states for a single point
  1483. hover: {
  1484. enabled: true,
  1485. lineWidthPlus: 1,
  1486. radiusPlus: 2
  1487. },
  1488. select: {
  1489. fillColor: '#FFFFFF',
  1490. lineColor: '#000000',
  1491. lineWidth: 2
  1492. }
  1493. }
  1494. },
  1495. point: {
  1496. events: {}
  1497. },
  1498. dataLabels: {
  1499. align: 'center',
  1500. // defer: true,
  1501. // enabled: false,
  1502. formatter: function () {
  1503. return this.y === null ? '' : Highcharts.numberFormat(this.y, -1);
  1504. },
  1505. style: {
  1506. color: 'contrast',
  1507. fontSize: '11px',
  1508. fontWeight: 'bold',
  1509. textShadow: '0 0 6px contrast, 0 0 3px contrast'
  1510. },
  1511. verticalAlign: 'bottom', // above singular point
  1512. x: 0,
  1513. y: 0,
  1514. // backgroundColor: undefined,
  1515. // borderColor: undefined,
  1516. // borderRadius: undefined,
  1517. // borderWidth: undefined,
  1518. padding: 5
  1519. // shadow: false
  1520. },
  1521. cropThreshold: 300, // draw points outside the plot area when the number of points is less than this
  1522. pointRange: 0,
  1523. //pointStart: 0,
  1524. //pointInterval: 1,
  1525. //showInLegend: null, // auto: true for standalone series, false for linked series
  1526. softThreshold: true,
  1527. states: { // states for the entire series
  1528. hover: {
  1529. //enabled: false,
  1530. lineWidthPlus: 1,
  1531. marker: {
  1532. // lineWidth: base + 1,
  1533. // radius: base + 1
  1534. },
  1535. halo: {
  1536. size: 10,
  1537. opacity: 0.25
  1538. }
  1539. },
  1540. select: {
  1541. marker: {}
  1542. }
  1543. },
  1544. stickyTracking: true,
  1545. //tooltip: {
  1546. //pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b>'
  1547. //valueDecimals: null,
  1548. //xDateFormat: '%A, %b %e, %Y',
  1549. //valuePrefix: '',
  1550. //ySuffix: ''
  1551. //}
  1552. turboThreshold: 1000
  1553. // zIndex: null
  1554. }
  1555. },
  1556. labels: {
  1557. //items: [],
  1558. style: {
  1559. //font: defaultFont,
  1560. position: ABSOLUTE,
  1561. color: '#3E576F'
  1562. }
  1563. },
  1564. legend: {
  1565. enabled: true,
  1566. align: 'center',
  1567. //floating: false,
  1568. layout: 'horizontal',
  1569. labelFormatter: function () {
  1570. return this.name;
  1571. },
  1572. //borderWidth: 0,
  1573. borderColor: '#909090',
  1574. borderRadius: 0,
  1575. navigation: {
  1576. // animation: true,
  1577. activeColor: '#274b6d',
  1578. // arrowSize: 12
  1579. inactiveColor: '#CCC'
  1580. // style: {} // text styles
  1581. },
  1582. // margin: 20,
  1583. // reversed: false,
  1584. shadow: false,
  1585. // backgroundColor: null,
  1586. /*style: {
  1587. padding: '5px'
  1588. },*/
  1589. itemStyle: {
  1590. color: '#333333',
  1591. fontSize: '12px',
  1592. fontWeight: 'bold'
  1593. },
  1594. itemHoverStyle: {
  1595. //cursor: 'pointer', removed as of #601
  1596. color: '#000'
  1597. },
  1598. itemHiddenStyle: {
  1599. color: '#CCC'
  1600. },
  1601. itemCheckboxStyle: {
  1602. position: ABSOLUTE,
  1603. width: '13px', // for IE precision
  1604. height: '13px'
  1605. },
  1606. // itemWidth: undefined,
  1607. // symbolRadius: 0,
  1608. // symbolWidth: 16,
  1609. symbolPadding: 5,
  1610. verticalAlign: 'bottom',
  1611. // width: undefined,
  1612. x: 0,
  1613. y: 0,
  1614. title: {
  1615. //text: null,
  1616. style: {
  1617. fontWeight: 'bold'
  1618. }
  1619. }
  1620. },
  1621. loading: {
  1622. // hideDuration: 100,
  1623. labelStyle: {
  1624. fontWeight: 'bold',
  1625. position: RELATIVE,
  1626. top: '45%'
  1627. },
  1628. // showDuration: 0,
  1629. style: {
  1630. position: ABSOLUTE,
  1631. backgroundColor: 'white',
  1632. opacity: 0.5,
  1633. textAlign: 'center'
  1634. }
  1635. },
  1636. tooltip: {
  1637. enabled: true,
  1638. animation: hasSVG,
  1639. //crosshairs: null,
  1640. backgroundColor: 'rgba(249, 249, 249, .85)',
  1641. borderWidth: 1,
  1642. borderRadius: 3,
  1643. dateTimeLabelFormats: {
  1644. millisecond: '%A, %b %e, %H:%M:%S.%L',
  1645. second: '%A, %b %e, %H:%M:%S',
  1646. minute: '%A, %b %e, %H:%M',
  1647. hour: '%A, %b %e, %H:%M',
  1648. day: '%A, %b %e, %Y',
  1649. week: 'Week from %A, %b %e, %Y',
  1650. month: '%B %Y',
  1651. year: '%Y'
  1652. },
  1653. footerFormat: '',
  1654. //formatter: defaultFormatter,
  1655. headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>',
  1656. pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b><br/>',
  1657. shadow: true,
  1658. //shape: 'callout',
  1659. //shared: false,
  1660. snap: isTouchDevice ? 25 : 10,
  1661. style: {
  1662. color: '#333333',
  1663. cursor: 'default',
  1664. fontSize: '12px',
  1665. padding: '8px',
  1666. pointerEvents: 'none', // #1686 http://caniuse.com/#feat=pointer-events
  1667. whiteSpace: 'nowrap'
  1668. }
  1669. //xDateFormat: '%A, %b %e, %Y',
  1670. //valueDecimals: null,
  1671. //valuePrefix: '',
  1672. //valueSuffix: ''
  1673. },
  1674. credits: {
  1675. enabled: true,
  1676. text: 'Highcharts.com',
  1677. href: 'http://www.highcharts.com',
  1678. position: {
  1679. align: 'right',
  1680. x: -10,
  1681. verticalAlign: 'bottom',
  1682. y: -5
  1683. },
  1684. style: {
  1685. cursor: 'pointer',
  1686. color: '#909090',
  1687. fontSize: '9px'
  1688. }
  1689. }
  1690. };
  1691. /**
  1692. * Set the time methods globally based on the useUTC option. Time method can be either
  1693. * local time or UTC (default).
  1694. */
  1695. function setTimeMethods() {
  1696. var globalOptions = defaultOptions.global,
  1697. useUTC = globalOptions.useUTC,
  1698. GET = useUTC ? 'getUTC' : 'get',
  1699. SET = useUTC ? 'setUTC' : 'set';
  1700. Date = globalOptions.Date || win.Date;
  1701. timezoneOffset = useUTC && globalOptions.timezoneOffset;
  1702. getTimezoneOffset = useUTC && globalOptions.getTimezoneOffset;
  1703. makeTime = function (year, month, date, hours, minutes, seconds) {
  1704. var d;
  1705. if (useUTC) {
  1706. d = Date.UTC.apply(0, arguments);
  1707. d += getTZOffset(d);
  1708. } else {
  1709. d = new Date(
  1710. year,
  1711. month,
  1712. pick(date, 1),
  1713. pick(hours, 0),
  1714. pick(minutes, 0),
  1715. pick(seconds, 0)
  1716. ).getTime();
  1717. }
  1718. return d;
  1719. };
  1720. getMinutes = GET + 'Minutes';
  1721. getHours = GET + 'Hours';
  1722. getDay = GET + 'Day';
  1723. getDate = GET + 'Date';
  1724. getMonth = GET + 'Month';
  1725. getFullYear = GET + 'FullYear';
  1726. setMilliseconds = SET + 'Milliseconds';
  1727. setSeconds = SET + 'Seconds';
  1728. setMinutes = SET + 'Minutes';
  1729. setHours = SET + 'Hours';
  1730. setDate = SET + 'Date';
  1731. setMonth = SET + 'Month';
  1732. setFullYear = SET + 'FullYear';
  1733. }
  1734. /**
  1735. * Merge the default options with custom options and return the new options structure
  1736. * @param {Object} options The new custom options
  1737. */
  1738. function setOptions(options) {
  1739. // Copy in the default options
  1740. defaultOptions = merge(true, defaultOptions, options);
  1741. // Apply UTC
  1742. setTimeMethods();
  1743. return defaultOptions;
  1744. }
  1745. /**
  1746. * Get the updated default options. Until 3.0.7, merely exposing defaultOptions for outside modules
  1747. * wasn't enough because the setOptions method created a new object.
  1748. */
  1749. function getOptions() {
  1750. return defaultOptions;
  1751. }
  1752. // Series defaults
  1753. var defaultPlotOptions = defaultOptions.plotOptions,
  1754. defaultSeriesOptions = defaultPlotOptions.line;
  1755. // set the default time methods
  1756. setTimeMethods();
  1757. /**
  1758. * Handle color operations. The object methods are chainable.
  1759. * @param {String} input The input color in either rbga or hex format
  1760. */
  1761. function Color(input) {
  1762. // Backwards compatibility, allow instanciation without new
  1763. if (!(this instanceof Color)) {
  1764. return new Color(input);
  1765. }
  1766. // Initialize
  1767. this.init(input);
  1768. }
  1769. Color.prototype = {
  1770. // Collection of parsers. This can be extended from the outside by pushing parsers
  1771. // to Highcharts.Colors.prototype.parsers.
  1772. parsers: [{
  1773. // RGBA color
  1774. regex: /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*\)/,
  1775. parse: function (result) {
  1776. return [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)];
  1777. }
  1778. }, {
  1779. // HEX color
  1780. regex: /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/,
  1781. parse: function (result) {
  1782. return [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1];
  1783. }
  1784. }, {
  1785. // RGB color
  1786. regex: /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/,
  1787. parse: function (result) {
  1788. return [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1];
  1789. }
  1790. }],
  1791. /**
  1792. * Parse the input color to rgba array
  1793. * @param {String} input
  1794. */
  1795. init: function (input) {
  1796. var result,
  1797. rgba,
  1798. i,
  1799. parser;
  1800. this.input = input;
  1801. // Gradients
  1802. if (input && input.stops) {
  1803. this.stops = map(input.stops, function (stop) {
  1804. return new Color(stop[1]);
  1805. });
  1806. // Solid colors
  1807. } else {
  1808. i = this.parsers.length;
  1809. while (i-- && !rgba) {
  1810. parser = this.parsers[i];
  1811. result = parser.regex.exec(input);
  1812. if (result) {
  1813. rgba = parser.parse(result);
  1814. }
  1815. }
  1816. }
  1817. this.rgba = rgba || [];
  1818. },
  1819. /**
  1820. * Return the color a specified format
  1821. * @param {String} format
  1822. */
  1823. get: function (format) {
  1824. var input = this.input,
  1825. rgba = this.rgba,
  1826. ret;
  1827. if (this.stops) {
  1828. ret = merge(input);
  1829. ret.stops = [].concat(ret.stops);
  1830. each(this.stops, function (stop, i) {
  1831. ret.stops[i] = [ret.stops[i][0], stop.get(format)];
  1832. });
  1833. // it's NaN if gradient colors on a column chart
  1834. } else if (rgba && isNumber(rgba[0])) {
  1835. if (format === 'rgb' || (!format && rgba[3] === 1)) {
  1836. ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')';
  1837. } else if (format === 'a') {
  1838. ret = rgba[3];
  1839. } else {
  1840. ret = 'rgba(' + rgba.join(',') + ')';
  1841. }
  1842. } else {
  1843. ret = input;
  1844. }
  1845. return ret;
  1846. },
  1847. /**
  1848. * Brighten the color
  1849. * @param {Number} alpha
  1850. */
  1851. brighten: function (alpha) {
  1852. var i,
  1853. rgba = this.rgba;
  1854. if (this.stops) {
  1855. each(this.stops, function (stop) {
  1856. stop.brighten(alpha);
  1857. });
  1858. } else if (isNumber(alpha) && alpha !== 0) {
  1859. for (i = 0; i < 3; i++) {
  1860. rgba[i] += pInt(alpha * 255);
  1861. if (rgba[i] < 0) {
  1862. rgba[i] = 0;
  1863. }
  1864. if (rgba[i] > 255) {
  1865. rgba[i] = 255;
  1866. }
  1867. }
  1868. }
  1869. return this;
  1870. },
  1871. /**
  1872. * Set the color's opacity to a given alpha value
  1873. * @param {Number} alpha
  1874. */
  1875. setOpacity: function (alpha) {
  1876. this.rgba[3] = alpha;
  1877. return this;
  1878. }
  1879. };
  1880. /**
  1881. * A wrapper object for SVG elements
  1882. */
  1883. function SVGElement() {}
  1884. SVGElement.prototype = {
  1885. // Default base for animation
  1886. opacity: 1,
  1887. // For labels, these CSS properties are applied to the <text> node directly
  1888. textProps: ['direction', 'fontSize', 'fontWeight', 'fontFamily', 'fontStyle', 'color',
  1889. 'lineHeight', 'width', 'textDecoration', 'textOverflow', 'textShadow'],
  1890. /**
  1891. * Initialize the SVG renderer
  1892. * @param {Object} renderer
  1893. * @param {String} nodeName
  1894. */
  1895. init: function (renderer, nodeName) {
  1896. var wrapper = this;
  1897. wrapper.element = nodeName === 'span' ?
  1898. createElement(nodeName) :
  1899. doc.createElementNS(SVG_NS, nodeName);
  1900. wrapper.renderer = renderer;
  1901. },
  1902. /**
  1903. * Animate a given attribute
  1904. * @param {Object} params
  1905. * @param {Number} options Options include duration, easing, step and complete
  1906. * @param {Function} complete Function to perform at the end of animation
  1907. */
  1908. animate: function (params, options, complete) {
  1909. var animOptions = pick(options, this.renderer.globalAnimation, true);
  1910. stop(this); // stop regardless of animation actually running, or reverting to .attr (#607)
  1911. if (animOptions) {
  1912. if (complete) { // allows using a callback with the global animation without overwriting it
  1913. animOptions.complete = complete;
  1914. }
  1915. animate(this, params, animOptions);
  1916. } else {
  1917. this.attr(params, null, complete);
  1918. }
  1919. return this;
  1920. },
  1921. /**
  1922. * Build an SVG gradient out of a common JavaScript configuration object
  1923. */
  1924. colorGradient: function (color, prop, elem) {
  1925. var renderer = this.renderer,
  1926. colorObject,
  1927. gradName,
  1928. gradAttr,
  1929. radAttr,
  1930. gradients,
  1931. gradientObject,
  1932. stops,
  1933. stopColor,
  1934. stopOpacity,
  1935. radialReference,
  1936. n,
  1937. id,
  1938. key = [],
  1939. value;
  1940. // Apply linear or radial gradients
  1941. if (color.linearGradient) {
  1942. gradName = 'linearGradient';
  1943. } else if (color.radialGradient) {
  1944. gradName = 'radialGradient';
  1945. }
  1946. if (gradName) {
  1947. gradAttr = color[gradName];
  1948. gradients = renderer.gradients;
  1949. stops = color.stops;
  1950. radialReference = elem.radialReference;
  1951. // Keep < 2.2 kompatibility
  1952. if (isArray(gradAttr)) {
  1953. color[gradName] = gradAttr = {
  1954. x1: gradAttr[0],
  1955. y1: gradAttr[1],
  1956. x2: gradAttr[2],
  1957. y2: gradAttr[3],
  1958. gradientUnits: 'userSpaceOnUse'
  1959. };
  1960. }
  1961. // Correct the radial gradient for the radial reference system
  1962. if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) {
  1963. radAttr = gradAttr; // Save the radial attributes for updating
  1964. gradAttr = merge(gradAttr,
  1965. renderer.getRadialAttr(radialReference, radAttr),
  1966. { gradientUnits: 'userSpaceOnUse' }
  1967. );
  1968. }
  1969. // Build the unique key to detect whether we need to create a new element (#1282)
  1970. for (n in gradAttr) {
  1971. if (n !== 'id') {
  1972. key.push(n, gradAttr[n]);
  1973. }
  1974. }
  1975. for (n in stops) {
  1976. key.push(stops[n]);
  1977. }
  1978. key = key.join(',');
  1979. // Check if a gradient object with the same config object is created within this renderer
  1980. if (gradients[key]) {
  1981. id = gradients[key].attr('id');
  1982. } else {
  1983. // Set the id and create the element
  1984. gradAttr.id = id = PREFIX + idCounter++;
  1985. gradients[key] = gradientObject = renderer.createElement(gradName)
  1986. .attr(gradAttr)
  1987. .add(renderer.defs);
  1988. gradientObject.radAttr = radAttr;
  1989. // The gradient needs to keep a list of stops to be able to destroy them
  1990. gradientObject.stops = [];
  1991. each(stops, function (stop) {
  1992. var stopObject;
  1993. if (stop[1].indexOf('rgba') === 0) {
  1994. colorObject = Color(stop[1]);
  1995. stopColor = colorObject.get('rgb');
  1996. stopOpacity = colorObject.get('a');
  1997. } else {
  1998. stopColor = stop[1];
  1999. stopOpacity = 1;
  2000. }
  2001. stopObject = renderer.createElement('stop').attr({
  2002. offset: stop[0],
  2003. 'stop-color': stopColor,
  2004. 'stop-opacity': stopOpacity
  2005. }).add(gradientObject);
  2006. // Add the stop element to the gradient
  2007. gradientObject.stops.push(stopObject);
  2008. });
  2009. }
  2010. // Set the reference to the gradient object
  2011. value = 'url(' + renderer.url + '#' + id + ')';
  2012. elem.setAttribute(prop, value);
  2013. elem.gradient = key;
  2014. // Allow the color to be concatenated into tooltips formatters etc. (#2995)
  2015. color.toString = function () {
  2016. return value;
  2017. };
  2018. }
  2019. },
  2020. /**
  2021. * Apply a polyfill to the text-stroke CSS property, by copying the text element
  2022. * and apply strokes to the copy.
  2023. *
  2024. * Contrast checks at http://jsfiddle.net/highcharts/43soe9m1/2/
  2025. */
  2026. applyTextShadow: function (textShadow) {
  2027. var elem = this.element,
  2028. tspans,
  2029. hasContrast = textShadow.indexOf('contrast') !== -1,
  2030. styles = {},
  2031. forExport = this.renderer.forExport,
  2032. // IE10 and IE11 report textShadow in elem.style even though it doesn't work. Check
  2033. // this again with new IE release. In exports, the rendering is passed to PhantomJS.
  2034. supports = forExport || (elem.style.textShadow !== UNDEFINED && !isMS);
  2035. // When the text shadow is set to contrast, use dark stroke for light text and vice versa
  2036. if (hasContrast) {
  2037. styles.textShadow = textShadow = textShadow.replace(/contrast/g, this.renderer.getContrast(elem.style.fill));
  2038. }
  2039. // Safari with retina displays as well as PhantomJS bug (#3974). Firefox does not tolerate this,
  2040. // it removes the text shadows.
  2041. if (isWebKit || forExport) {
  2042. styles.textRendering = 'geometricPrecision';
  2043. }
  2044. /* Selective side-by-side testing in supported browser (http://jsfiddle.net/highcharts/73L1ptrh/)
  2045. if (elem.textContent.indexOf('2.') === 0) {
  2046. elem.style['text-shadow'] = 'none';
  2047. supports = false;
  2048. }
  2049. // */
  2050. // No reason to polyfill, we've got native support
  2051. if (supports) {
  2052. this.css(styles); // Apply altered textShadow or textRendering workaround
  2053. } else {
  2054. this.fakeTS = true; // Fake text shadow
  2055. // In order to get the right y position of the clones,
  2056. // copy over the y setter
  2057. this.ySetter = this.xSetter;
  2058. tspans = [].slice.call(elem.getElementsByTagName('tspan'));
  2059. each(textShadow.split(/\s?,\s?/g), function (textShadow) {
  2060. var firstChild = elem.firstChild,
  2061. color,
  2062. strokeWidth;
  2063. textShadow = textShadow.split(' ');
  2064. color = textShadow[textShadow.length - 1];
  2065. // Approximately tune the settings to the text-shadow behaviour
  2066. strokeWidth = textShadow[textShadow.length - 2];
  2067. if (strokeWidth) {
  2068. each(tspans, function (tspan, y) {
  2069. var clone;
  2070. // Let the first line start at the correct X position
  2071. if (y === 0) {
  2072. tspan.setAttribute('x', elem.getAttribute('x'));
  2073. y = elem.getAttribute('y');
  2074. tspan.setAttribute('y', y || 0);
  2075. if (y === null) {
  2076. elem.setAttribute('y', 0);
  2077. }
  2078. }
  2079. // Create the clone and apply shadow properties
  2080. clone = tspan.cloneNode(1);
  2081. attr(clone, {
  2082. 'class': PREFIX + 'text-shadow',
  2083. 'fill': color,
  2084. 'stroke': color,
  2085. 'stroke-opacity': 1 / mathMax(pInt(strokeWidth), 3),
  2086. 'stroke-width': strokeWidth,
  2087. 'stroke-linejoin': 'round'
  2088. });
  2089. elem.insertBefore(clone, firstChild);
  2090. });
  2091. }
  2092. });
  2093. }
  2094. },
  2095. /**
  2096. * Set or get a given attribute
  2097. * @param {Object|String} hash
  2098. * @param {Mixed|Undefined} val
  2099. */
  2100. attr: function (hash, val, complete) {
  2101. var key,
  2102. value,
  2103. element = this.element,
  2104. hasSetSymbolSize,
  2105. ret = this,
  2106. skipAttr,
  2107. setter;
  2108. // single key-value pair
  2109. if (typeof hash === 'string' && val !== UNDEFINED) {
  2110. key = hash;
  2111. hash = {};
  2112. hash[key] = val;
  2113. }
  2114. // used as a getter: first argument is a string, second is undefined
  2115. if (typeof hash === 'string') {
  2116. ret = (this[hash + 'Getter'] || this._defaultGetter).call(this, hash, element);
  2117. // setter
  2118. } else {
  2119. for (key in hash) {
  2120. value = hash[key];
  2121. skipAttr = false;
  2122. if (this.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) {
  2123. if (!hasSetSymbolSize) {
  2124. this.symbolAttr(hash);
  2125. hasSetSymbolSize = true;
  2126. }
  2127. skipAttr = true;
  2128. }
  2129. if (this.rotation && (key === 'x' || key === 'y')) {
  2130. this.doTransform = true;
  2131. }
  2132. if (!skipAttr) {
  2133. setter = this[key + 'Setter'] || this._defaultSetter;
  2134. setter.call(this, value, key, element);
  2135. // Let the shadow follow the main element
  2136. if (this.shadows && /^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(key)) {
  2137. this.updateShadows(key, value, setter);
  2138. }
  2139. }
  2140. }
  2141. // Update transform. Do this outside the loop to prevent redundant updating for batch setting
  2142. // of attributes.
  2143. if (this.doTransform) {
  2144. this.updateTransform();
  2145. this.doTransform = false;
  2146. }
  2147. }
  2148. // In accordance with animate, run a complete callback
  2149. if (complete) {
  2150. complete();
  2151. }
  2152. return ret;
  2153. },
  2154. /**
  2155. * Update the shadow elements with new attributes
  2156. * @param {String} key The attribute name
  2157. * @param {String|Number} value The value of the attribute
  2158. * @param {Function} setter The setter function, inherited from the parent wrapper
  2159. * @returns {undefined}
  2160. */
  2161. updateShadows: function (key, value, setter) {
  2162. var shadows = this.shadows,
  2163. i = shadows.length;
  2164. while (i--) {
  2165. setter.call(
  2166. shadows[i],
  2167. key === 'height' ?
  2168. Math.max(value - (shadows[i].cutHeight || 0), 0) :
  2169. key === 'd' ? this.d : value,
  2170. key,
  2171. shadows[i]
  2172. );
  2173. }
  2174. },
  2175. /**
  2176. * Add a class name to an element
  2177. */
  2178. addClass: function (className) {
  2179. var element = this.element,
  2180. currentClassName = attr(element, 'class') || '';
  2181. if (currentClassName.indexOf(className) === -1) {
  2182. attr(element, 'class', currentClassName + ' ' + className);
  2183. }
  2184. return this;
  2185. },
  2186. /* hasClass and removeClass are not (yet) needed
  2187. hasClass: function (className) {
  2188. return attr(this.element, 'class').indexOf(className) !== -1;
  2189. },
  2190. removeClass: function (className) {
  2191. attr(this.element, 'class', attr(this.element, 'class').replace(className, ''));
  2192. return this;
  2193. },
  2194. */
  2195. /**
  2196. * If one of the symbol size affecting parameters are changed,
  2197. * check all the others only once for each call to an element's
  2198. * .attr() method
  2199. * @param {Object} hash
  2200. */
  2201. symbolAttr: function (hash) {
  2202. var wrapper = this;
  2203. each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function (key) {
  2204. wrapper[key] = pick(hash[key], wrapper[key]);
  2205. });
  2206. wrapper.attr({
  2207. d: wrapper.renderer.symbols[wrapper.symbolName](
  2208. wrapper.x,
  2209. wrapper.y,
  2210. wrapper.width,
  2211. wrapper.height,
  2212. wrapper
  2213. )
  2214. });
  2215. },
  2216. /**
  2217. * Apply a clipping path to this object
  2218. * @param {String} id
  2219. */
  2220. clip: function (clipRect) {
  2221. return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : NONE);
  2222. },
  2223. /**
  2224. * Calculate the coordinates needed for drawing a rectangle crisply and return the
  2225. * calculated attributes
  2226. * @param {Number} strokeWidth
  2227. * @param {Number} x
  2228. * @param {Number} y
  2229. * @param {Number} width
  2230. * @param {Number} height
  2231. */
  2232. crisp: function (rect) {
  2233. var wrapper = this,
  2234. key,
  2235. attribs = {},
  2236. normalizer,
  2237. strokeWidth = wrapper.strokeWidth || 0;
  2238. normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors
  2239. // normalize for crisp edges
  2240. rect.x = mathFloor(rect.x || wrapper.x || 0) + normalizer;
  2241. rect.y = mathFloor(rect.y || wrapper.y || 0) + normalizer;
  2242. rect.width = mathFloor((rect.width || wrapper.width || 0) - 2 * normalizer);
  2243. rect.height = mathFloor((rect.height || wrapper.height || 0) - 2 * normalizer);
  2244. rect.strokeWidth = strokeWidth;
  2245. for (key in rect) {
  2246. if (wrapper[key] !== rect[key]) { // only set attribute if changed
  2247. wrapper[key] = attribs[key] = rect[key];
  2248. }
  2249. }
  2250. return attribs;
  2251. },
  2252. /**
  2253. * Set styles for the element
  2254. * @param {Object} styles
  2255. */
  2256. css: function (styles) {
  2257. var elemWrapper = this,
  2258. oldStyles = elemWrapper.styles,
  2259. newStyles = {},
  2260. elem = elemWrapper.element,
  2261. textWidth,
  2262. n,
  2263. serializedCss = '',
  2264. hyphenate,
  2265. hasNew = !oldStyles;
  2266. // convert legacy
  2267. if (styles && styles.color) {
  2268. styles.fill = styles.color;
  2269. }
  2270. // Filter out existing styles to increase performance (#2640)
  2271. if (oldStyles) {
  2272. for (n in styles) {
  2273. if (styles[n] !== oldStyles[n]) {
  2274. newStyles[n] = styles[n];
  2275. hasNew = true;
  2276. }
  2277. }
  2278. }
  2279. if (hasNew) {
  2280. textWidth = elemWrapper.textWidth =
  2281. (styles && styles.width && elem.nodeName.toLowerCase() === 'text' && pInt(styles.width)) ||
  2282. elemWrapper.textWidth; // #3501
  2283. // Merge the new styles with the old ones
  2284. if (oldStyles) {
  2285. styles = extend(
  2286. oldStyles,
  2287. newStyles
  2288. );
  2289. }
  2290. // store object
  2291. elemWrapper.styles = styles;
  2292. if (textWidth && (useCanVG || (!hasSVG && elemWrapper.renderer.forExport))) {
  2293. delete styles.width;
  2294. }
  2295. // serialize and set style attribute
  2296. if (isMS && !hasSVG) {
  2297. css(elemWrapper.element, styles);
  2298. } else {
  2299. hyphenate = function (a, b) {
  2300. return '-' + b.toLowerCase();
  2301. };
  2302. for (n in styles) {
  2303. serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';';
  2304. }
  2305. attr(elem, 'style', serializedCss); // #1881
  2306. }
  2307. // re-build text
  2308. if (textWidth && elemWrapper.added) {
  2309. elemWrapper.renderer.buildText(elemWrapper);
  2310. }
  2311. }
  2312. return elemWrapper;
  2313. },
  2314. /**
  2315. * Add an event listener
  2316. * @param {String} eventType
  2317. * @param {Function} handler
  2318. */
  2319. on: function (eventType, handler) {
  2320. var svgElement = this,
  2321. element = svgElement.element;
  2322. // touch
  2323. if (hasTouch && eventType === 'click') {
  2324. element.ontouchstart = function (e) {
  2325. svgElement.touchEventFired = Date.now();
  2326. e.preventDefault();
  2327. handler.call(element, e);
  2328. };
  2329. element.onclick = function (e) {
  2330. if (userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { // #2269
  2331. handler.call(element, e);
  2332. }
  2333. };
  2334. } else {
  2335. // simplest possible event model for internal use
  2336. element['on' + eventType] = handler;
  2337. }
  2338. return this;
  2339. },
  2340. /**
  2341. * Set the coordinates needed to draw a consistent radial gradient across
  2342. * pie slices regardless of positioning inside the chart. The format is
  2343. * [centerX, centerY, diameter] in pixels.
  2344. */
  2345. setRadialReference: function (coordinates) {
  2346. var existingGradient = this.renderer.gradients[this.element.gradient];
  2347. this.element.radialReference = coordinates;
  2348. // On redrawing objects with an existing gradient, the gradient needs
  2349. // to be repositioned (#3801)
  2350. if (existingGradient && existingGradient.radAttr) {
  2351. existingGradient.animate(
  2352. this.renderer.getRadialAttr(
  2353. coordinates,
  2354. existingGradient.radAttr
  2355. )
  2356. );
  2357. }
  2358. return this;
  2359. },
  2360. /**
  2361. * Move an object and its children by x and y values
  2362. * @param {Number} x
  2363. * @param {Number} y
  2364. */
  2365. translate: function (x, y) {
  2366. return this.attr({
  2367. translateX: x,
  2368. translateY: y
  2369. });
  2370. },
  2371. /**
  2372. * Invert a group, rotate and flip
  2373. */
  2374. invert: function () {
  2375. var wrapper = this;
  2376. wrapper.inverted = true;
  2377. wrapper.updateTransform();
  2378. return wrapper;
  2379. },
  2380. /**
  2381. * Private method to update the transform attribute based on internal
  2382. * properties
  2383. */
  2384. updateTransform: function () {
  2385. var wrapper = this,
  2386. translateX = wrapper.translateX || 0,
  2387. translateY = wrapper.translateY || 0,
  2388. scaleX = wrapper.scaleX,
  2389. scaleY = wrapper.scaleY,
  2390. inverted = wrapper.inverted,
  2391. rotation = wrapper.rotation,
  2392. element = wrapper.element,
  2393. transform;
  2394. // flipping affects translate as adjustment for flipping around the group's axis
  2395. if (inverted) {
  2396. translateX += wrapper.attr('width');
  2397. translateY += wrapper.attr('height');
  2398. }
  2399. // Apply translate. Nearly all transformed elements have translation, so instead
  2400. // of checking for translate = 0, do it always (#1767, #1846).
  2401. transform = ['translate(' + translateX + ',' + translateY + ')'];
  2402. // apply rotation
  2403. if (inverted) {
  2404. transform.push('rotate(90) scale(-1,1)');
  2405. } else if (rotation) { // text rotation
  2406. transform.push('rotate(' + rotation + ' ' + (element.getAttribute('x') || 0) + ' ' + (element.getAttribute('y') || 0) + ')');
  2407. // Delete bBox memo when the rotation changes
  2408. //delete wrapper.bBox;
  2409. }
  2410. // apply scale
  2411. if (defined(scaleX) || defined(scaleY)) {
  2412. transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')');
  2413. }
  2414. if (transform.length) {
  2415. element.setAttribute('transform', transform.join(' '));
  2416. }
  2417. },
  2418. /**
  2419. * Bring the element to the front
  2420. */
  2421. toFront: function () {
  2422. var element = this.element;
  2423. element.parentNode.appendChild(element);
  2424. return this;
  2425. },
  2426. /**
  2427. * Break down alignment options like align, verticalAlign, x and y
  2428. * to x and y relative to the chart.
  2429. *
  2430. * @param {Object} alignOptions
  2431. * @param {Boolean} alignByTranslate
  2432. * @param {String[Object} box The box to align to, needs a width and height. When the
  2433. * box is a string, it refers to an object in the Renderer. For example, when
  2434. * box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height
  2435. * x and y properties.
  2436. *
  2437. */
  2438. align: function (alignOptions, alignByTranslate, box) {
  2439. var align,
  2440. vAlign,
  2441. x,
  2442. y,
  2443. attribs = {},
  2444. alignTo,
  2445. renderer = this.renderer,
  2446. alignedObjects = renderer.alignedObjects;
  2447. // First call on instanciate
  2448. if (alignOptions) {
  2449. this.alignOptions = alignOptions;
  2450. this.alignByTranslate = alignByTranslate;
  2451. if (!box || isString(box)) { // boxes other than renderer handle this internally
  2452. this.alignTo = alignTo = box || 'renderer';
  2453. erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize
  2454. alignedObjects.push(this);
  2455. box = null; // reassign it below
  2456. }
  2457. // When called on resize, no arguments are supplied
  2458. } else {
  2459. alignOptions = this.alignOptions;
  2460. alignByTranslate = this.alignByTranslate;
  2461. alignTo = this.alignTo;
  2462. }
  2463. box = pick(box, renderer[alignTo], renderer);
  2464. // Assign variables
  2465. align = alignOptions.align;
  2466. vAlign = alignOptions.verticalAlign;
  2467. x = (box.x || 0) + (alignOptions.x || 0); // default: left align
  2468. y = (box.y || 0) + (alignOptions.y || 0); // default: top align
  2469. // Align
  2470. if (align === 'right' || align === 'center') {
  2471. x += (box.width - (alignOptions.width || 0)) /
  2472. { right: 1, center: 2 }[align];
  2473. }
  2474. attribs[alignByTranslate ? 'translateX' : 'x'] = mathRound(x);
  2475. // Vertical align
  2476. if (vAlign === 'bottom' || vAlign === 'middle') {
  2477. y += (box.height - (alignOptions.height || 0)) /
  2478. ({ bottom: 1, middle: 2 }[vAlign] || 1);
  2479. }
  2480. attribs[alignByTranslate ? 'translateY' : 'y'] = mathRound(y);
  2481. // Animate only if already placed
  2482. this[this.placed ? 'animate' : 'attr'](attribs);
  2483. this.placed = true;
  2484. this.alignAttr = attribs;
  2485. return this;
  2486. },
  2487. /**
  2488. * Get the bounding box (width, height, x and y) for the element
  2489. */
  2490. getBBox: function (reload, rot) {
  2491. var wrapper = this,
  2492. bBox, // = wrapper.bBox,
  2493. renderer = wrapper.renderer,
  2494. width,
  2495. height,
  2496. rotation,
  2497. rad,
  2498. element = wrapper.element,
  2499. styles = wrapper.styles,
  2500. textStr = wrapper.textStr,
  2501. textShadow,
  2502. elemStyle = element.style,
  2503. toggleTextShadowShim,
  2504. cache = renderer.cache,
  2505. cacheKeys = renderer.cacheKeys,
  2506. cacheKey;
  2507. rotation = pick(rot, wrapper.rotation);
  2508. rad = rotation * deg2rad;
  2509. if (textStr !== UNDEFINED) {
  2510. cacheKey =
  2511. // Since numbers are monospaced, and numerical labels appear a lot in a chart,
  2512. // we assume that a label of n characters has the same bounding box as others
  2513. // of the same length.
  2514. textStr.toString().replace(numRegex, '0') +
  2515. // Properties that affect bounding box
  2516. ['', rotation || 0, styles && styles.fontSize, element.style.width].join(',');
  2517. }
  2518. if (cacheKey && !reload) {
  2519. bBox = cache[cacheKey];
  2520. }
  2521. // No cache found
  2522. if (!bBox) {
  2523. // SVG elements
  2524. if (element.namespaceURI === SVG_NS || renderer.forExport) {
  2525. try { // Fails in Firefox if the container has display: none.
  2526. // When the text shadow shim is used, we need to hide the fake shadows
  2527. // to get the correct bounding box (#3872)
  2528. toggleTextShadowShim = this.fakeTS && function (display) {
  2529. each(element.querySelectorAll('.' + PREFIX + 'text-shadow'), function (tspan) {
  2530. tspan.style.display = display;
  2531. });
  2532. };
  2533. // Workaround for #3842, Firefox reporting wrong bounding box for shadows
  2534. if (isFirefox && elemStyle.textShadow) {
  2535. textShadow = elemStyle.textShadow;
  2536. elemStyle.textShadow = '';
  2537. } else if (toggleTextShadowShim) {
  2538. toggleTextShadowShim(NONE);
  2539. }
  2540. bBox = element.getBBox ?
  2541. // SVG: use extend because IE9 is not allowed to change width and height in case
  2542. // of rotation (below)
  2543. extend({}, element.getBBox()) :
  2544. // Canvas renderer and legacy IE in export mode
  2545. {
  2546. width: element.offsetWidth,
  2547. height: element.offsetHeight
  2548. };
  2549. // #3842
  2550. if (textShadow) {
  2551. elemStyle.textShadow = textShadow;
  2552. } else if (toggleTextShadowShim) {
  2553. toggleTextShadowShim('');
  2554. }
  2555. } catch (e) {}
  2556. // If the bBox is not set, the try-catch block above failed. The other condition
  2557. // is for Opera that returns a width of -Infinity on hidden elements.
  2558. if (!bBox || bBox.width < 0) {
  2559. bBox = { width: 0, height: 0 };
  2560. }
  2561. // VML Renderer or useHTML within SVG
  2562. } else {
  2563. bBox = wrapper.htmlGetBBox();
  2564. }
  2565. // True SVG elements as well as HTML elements in modern browsers using the .useHTML option
  2566. // need to compensated for rotation
  2567. if (renderer.isSVG) {
  2568. width = bBox.width;
  2569. height = bBox.height;
  2570. // Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669, #2568)
  2571. if (isMS && styles && styles.fontSize === '11px' && height.toPrecision(3) === '16.9') {
  2572. bBox.height = height = 14;
  2573. }
  2574. // Adjust for rotated text
  2575. if (rotation) {
  2576. bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad));
  2577. bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad));
  2578. }
  2579. }
  2580. // Cache it. When loading a chart in a hidden iframe in Firefox and IE/Edge, the
  2581. // bounding box height is 0, so don't cache it (#5620).
  2582. if (cacheKey && bBox.height > 0) {
  2583. // Rotate (#4681)
  2584. while (cacheKeys.length > 250) {
  2585. delete cache[cacheKeys.shift()];
  2586. }
  2587. if (!cache[cacheKey]) {
  2588. cacheKeys.push(cacheKey);
  2589. }
  2590. cache[cacheKey] = bBox;
  2591. }
  2592. }
  2593. return bBox;
  2594. },
  2595. /**
  2596. * Show the element
  2597. */
  2598. show: function (inherit) {
  2599. return this.attr({ visibility: inherit ? 'inherit' : VISIBLE });
  2600. },
  2601. /**
  2602. * Hide the element
  2603. */
  2604. hide: function () {
  2605. return this.attr({ visibility: HIDDEN });
  2606. },
  2607. fadeOut: function (duration) {
  2608. var elemWrapper = this;
  2609. elemWrapper.animate({
  2610. opacity: 0
  2611. }, {
  2612. duration: duration || 150,
  2613. complete: function () {
  2614. elemWrapper.attr({ y: -9999 }); // #3088, assuming we're only using this for tooltips
  2615. }
  2616. });
  2617. },
  2618. /**
  2619. * Add the element
  2620. * @param {Object|Undefined} parent Can be an element, an element wrapper or undefined
  2621. * to append the element to the renderer.box.
  2622. */
  2623. add: function (parent) {
  2624. var renderer = this.renderer,
  2625. element = this.element,
  2626. inserted;
  2627. if (parent) {
  2628. this.parentGroup = parent;
  2629. }
  2630. // mark as inverted
  2631. this.parentInverted = parent && parent.inverted;
  2632. // build formatted text
  2633. if (this.textStr !== undefined) {
  2634. renderer.buildText(this);
  2635. }
  2636. // Mark as added
  2637. this.added = true;
  2638. // If we're adding to renderer root, or other elements in the group
  2639. // have a z index, we need to handle it
  2640. if (!parent || parent.handleZ || this.zIndex) {
  2641. inserted = this.zIndexSetter();
  2642. }
  2643. // If zIndex is not handled, append at the end
  2644. if (!inserted) {
  2645. (parent ? parent.element : renderer.box).appendChild(element);
  2646. }
  2647. // fire an event for internal hooks
  2648. if (this.onAdd) {
  2649. this.onAdd();
  2650. }
  2651. return this;
  2652. },
  2653. /**
  2654. * Removes a child either by removeChild or move to garbageBin.
  2655. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not.
  2656. */
  2657. safeRemoveChild: function (element) {
  2658. var parentNode = element.parentNode;
  2659. if (parentNode) {
  2660. parentNode.removeChild(element);
  2661. }
  2662. },
  2663. /**
  2664. * Destroy the element and element wrapper
  2665. */
  2666. destroy: function () {
  2667. var wrapper = this,
  2668. element = wrapper.element || {},
  2669. shadows = wrapper.shadows,
  2670. parentToClean = wrapper.renderer.isSVG && element.nodeName === 'SPAN' && wrapper.parentGroup,
  2671. grandParent,
  2672. key,
  2673. i;
  2674. // remove events
  2675. element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null;
  2676. stop(wrapper); // stop running animations
  2677. if (wrapper.clipPath) {
  2678. wrapper.clipPath = wrapper.clipPath.destroy();
  2679. }
  2680. // Destroy stops in case this is a gradient object
  2681. if (wrapper.stops) {
  2682. for (i = 0; i < wrapper.stops.length; i++) {
  2683. wrapper.stops[i] = wrapper.stops[i].destroy();
  2684. }
  2685. wrapper.stops = null;
  2686. }
  2687. // remove element
  2688. wrapper.safeRemoveChild(element);
  2689. // destroy shadows
  2690. if (shadows) {
  2691. each(shadows, function (shadow) {
  2692. wrapper.safeRemoveChild(shadow);
  2693. });
  2694. }
  2695. // In case of useHTML, clean up empty containers emulating SVG groups (#1960, #2393, #2697).
  2696. while (parentToClean && parentToClean.div && parentToClean.div.childNodes.length === 0) {
  2697. grandParent = parentToClean.parentGroup;
  2698. wrapper.safeRemoveChild(parentToClean.div);
  2699. delete parentToClean.div;
  2700. parentToClean = grandParent;
  2701. }
  2702. // remove from alignObjects
  2703. if (wrapper.alignTo) {
  2704. erase(wrapper.renderer.alignedObjects, wrapper);
  2705. }
  2706. for (key in wrapper) {
  2707. delete wrapper[key];
  2708. }
  2709. return null;
  2710. },
  2711. /**
  2712. * Add a shadow to the element. Must be done after the element is added to the DOM
  2713. * @param {Boolean|Object} shadowOptions
  2714. */
  2715. shadow: function (shadowOptions, group, cutOff) {
  2716. var shadows = [],
  2717. i,
  2718. shadow,
  2719. element = this.element,
  2720. strokeWidth,
  2721. shadowWidth,
  2722. shadowElementOpacity,
  2723. // compensate for inverted plot area
  2724. transform;
  2725. if (shadowOptions) {
  2726. shadowWidth = pick(shadowOptions.width, 3);
  2727. shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth;
  2728. transform = this.parentInverted ?
  2729. '(-1,-1)' :
  2730. '(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')';
  2731. for (i = 1; i <= shadowWidth; i++) {
  2732. shadow = element.cloneNode(0);
  2733. strokeWidth = (shadowWidth * 2) + 1 - (2 * i);
  2734. attr(shadow, {
  2735. 'isShadow': 'true',
  2736. 'stroke': shadowOptions.color || 'black',
  2737. 'stroke-opacity': shadowElementOpacity * i,
  2738. 'stroke-width': strokeWidth,
  2739. 'transform': 'translate' + transform,
  2740. 'fill': NONE
  2741. });
  2742. if (cutOff) {
  2743. attr(shadow, 'height', mathMax(attr(shadow, 'height') - strokeWidth, 0));
  2744. shadow.cutHeight = strokeWidth;
  2745. }
  2746. if (group) {
  2747. group.element.appendChild(shadow);
  2748. } else {
  2749. element.parentNode.insertBefore(shadow, element);
  2750. }
  2751. shadows.push(shadow);
  2752. }
  2753. this.shadows = shadows;
  2754. }
  2755. return this;
  2756. },
  2757. xGetter: function (key) {
  2758. if (this.element.nodeName === 'circle') {
  2759. key = { x: 'cx', y: 'cy' }[key] || key;
  2760. }
  2761. return this._defaultGetter(key);
  2762. },
  2763. /**
  2764. * Get the current value of an attribute or pseudo attribute, used mainly
  2765. * for animation.
  2766. */
  2767. _defaultGetter: function (key) {
  2768. var ret = pick(this[key], this.element ? this.element.getAttribute(key) : null, 0);
  2769. if (/^[\-0-9\.]+$/.test(ret)) { // is numerical
  2770. ret = parseFloat(ret);
  2771. }
  2772. return ret;
  2773. },
  2774. dSetter: function (value, key, element) {
  2775. if (value && value.join) { // join path
  2776. value = value.join(' ');
  2777. }
  2778. if (/(NaN| {2}|^$)/.test(value)) {
  2779. value = 'M 0 0';
  2780. }
  2781. element.setAttribute(key, value);
  2782. this[key] = value;
  2783. },
  2784. dashstyleSetter: function (value) {
  2785. var i,
  2786. strokeWidth = this['stroke-width'];
  2787. // If "inherit", like maps in IE, assume 1 (#4981). With HC5 and the new strokeWidth
  2788. // function, we should be able to use that instead.
  2789. if (strokeWidth === 'inherit') {
  2790. strokeWidth = 1;
  2791. }
  2792. value = value && value.toLowerCase();
  2793. if (value) {
  2794. value = value
  2795. .replace('shortdashdotdot', '3,1,1,1,1,1,')
  2796. .replace('shortdashdot', '3,1,1,1')
  2797. .replace('shortdot', '1,1,')
  2798. .replace('shortdash', '3,1,')
  2799. .replace('longdash', '8,3,')
  2800. .replace(/dot/g, '1,3,')
  2801. .replace('dash', '4,3,')
  2802. .replace(/,$/, '')
  2803. .split(','); // ending comma
  2804. i = value.length;
  2805. while (i--) {
  2806. value[i] = pInt(value[i]) * strokeWidth;
  2807. }
  2808. value = value.join(',')
  2809. .replace(/NaN/g, 'none'); // #3226
  2810. this.element.setAttribute('stroke-dasharray', value);
  2811. }
  2812. },
  2813. alignSetter: function (value) {
  2814. this.element.setAttribute('text-anchor', { left: 'start', center: 'middle', right: 'end' }[value]);
  2815. },
  2816. titleSetter: function (value) {
  2817. var titleNode = this.element.getElementsByTagName('title')[0];
  2818. if (!titleNode) {
  2819. titleNode = doc.createElementNS(SVG_NS, 'title');
  2820. this.element.appendChild(titleNode);
  2821. }
  2822. // Remove text content if it exists
  2823. if (titleNode.firstChild) {
  2824. titleNode.removeChild(titleNode.firstChild);
  2825. }
  2826. titleNode.appendChild(
  2827. doc.createTextNode(
  2828. (String(pick(value), '')).replace(/<[^>]*>/g, '') // #3276, #3895
  2829. )
  2830. );
  2831. },
  2832. textSetter: function (value) {
  2833. if (value !== this.textStr) {
  2834. // Delete bBox memo when the text changes
  2835. delete this.bBox;
  2836. this.textStr = value;
  2837. if (this.added) {
  2838. this.renderer.buildText(this);
  2839. }
  2840. }
  2841. },
  2842. fillSetter: function (value, key, element) {
  2843. if (typeof value === 'string') {
  2844. element.setAttribute(key, value);
  2845. } else if (value) {
  2846. this.colorGradient(value, key, element);
  2847. }
  2848. },
  2849. visibilitySetter: function (value, key, element) {
  2850. // IE9-11 doesn't handle visibilty:inherit well, so we remove the attribute instead (#2881, #3909)
  2851. if (value === 'inherit') {
  2852. element.removeAttribute(key);
  2853. } else {
  2854. element.setAttribute(key, value);
  2855. }
  2856. },
  2857. zIndexSetter: function (value, key) {
  2858. var renderer = this.renderer,
  2859. parentGroup = this.parentGroup,
  2860. parentWrapper = parentGroup || renderer,
  2861. parentNode = parentWrapper.element || renderer.box,
  2862. childNodes,
  2863. otherElement,
  2864. otherZIndex,
  2865. element = this.element,
  2866. inserted,
  2867. run = this.added,
  2868. i;
  2869. if (defined(value)) {
  2870. element.zIndex = value; // So we can read it for other elements in the group
  2871. value = +value;
  2872. if (this[key] === value) { // Only update when needed (#3865)
  2873. run = false;
  2874. }
  2875. this[key] = value;
  2876. }
  2877. // Insert according to this and other elements' zIndex. Before .add() is called,
  2878. // nothing is done. Then on add, or by later calls to zIndexSetter, the node
  2879. // is placed on the right place in the DOM.
  2880. if (run) {
  2881. value = this.zIndex;
  2882. if (value && parentGroup) {
  2883. parentGroup.handleZ = true;
  2884. }
  2885. childNodes = parentNode.childNodes;
  2886. for (i = 0; i < childNodes.length && !inserted; i++) {
  2887. otherElement = childNodes[i];
  2888. otherZIndex = otherElement.zIndex;
  2889. if (otherElement !== element && (
  2890. // Insert before the first element with a higher zIndex
  2891. pInt(otherZIndex) > value ||
  2892. // If no zIndex given, insert before the first element with a zIndex
  2893. (!defined(value) && defined(otherZIndex))
  2894. )) {
  2895. parentNode.insertBefore(element, otherElement);
  2896. inserted = true;
  2897. }
  2898. }
  2899. if (!inserted) {
  2900. parentNode.appendChild(element);
  2901. }
  2902. }
  2903. return inserted;
  2904. },
  2905. _defaultSetter: function (value, key, element) {
  2906. element.setAttribute(key, value);
  2907. }
  2908. };
  2909. // Some shared setters and getters
  2910. SVGElement.prototype.yGetter = SVGElement.prototype.xGetter;
  2911. SVGElement.prototype.translateXSetter = SVGElement.prototype.translateYSetter =
  2912. SVGElement.prototype.rotationSetter = SVGElement.prototype.verticalAlignSetter =
  2913. SVGElement.prototype.scaleXSetter = SVGElement.prototype.scaleYSetter = function (value, key) {
  2914. this[key] = value;
  2915. this.doTransform = true;
  2916. };
  2917. // These setters both set the key on the instance itself plus as an attribute
  2918. SVGElement.prototype.opacitySetter = SVGElement.prototype.displaySetter = function (value, key, element) {
  2919. this[key] = value;
  2920. element.setAttribute(key, value);
  2921. };
  2922. // WebKit and Batik have problems with a stroke-width of zero, so in this case we remove the
  2923. // stroke attribute altogether. #1270, #1369, #3065, #3072.
  2924. SVGElement.prototype['stroke-widthSetter'] = SVGElement.prototype.strokeSetter = function (value, key, element) {
  2925. this[key] = value;
  2926. // Only apply the stroke attribute if the stroke width is defined and larger than 0
  2927. if (this.stroke && this['stroke-width']) {
  2928. this.strokeWidth = this['stroke-width'];
  2929. SVGElement.prototype.fillSetter.call(this, this.stroke, 'stroke', element); // use prototype as instance may be overridden
  2930. element.setAttribute('stroke-width', this['stroke-width']);
  2931. this.hasStroke = true;
  2932. } else if (key === 'stroke-width' && value === 0 && this.hasStroke) {
  2933. element.removeAttribute('stroke');
  2934. this.hasStroke = false;
  2935. }
  2936. };
  2937. /**
  2938. * The default SVG renderer
  2939. */
  2940. var SVGRenderer = function () {
  2941. this.init.apply(this, arguments);
  2942. };
  2943. SVGRenderer.prototype = {
  2944. Element: SVGElement,
  2945. /**
  2946. * Initialize the SVGRenderer
  2947. * @param {Object} container
  2948. * @param {Number} width
  2949. * @param {Number} height
  2950. * @param {Boolean} forExport
  2951. */
  2952. init: function (container, width, height, style, forExport, allowHTML) {
  2953. var renderer = this,
  2954. boxWrapper,
  2955. element,
  2956. desc;
  2957. boxWrapper = renderer.createElement('svg')
  2958. .attr({
  2959. version: '1.1'
  2960. })
  2961. .css(this.getStyle(style));
  2962. element = boxWrapper.element;
  2963. container.appendChild(element);
  2964. // For browsers other than IE, add the namespace attribute (#1978)
  2965. if (container.innerHTML.indexOf('xmlns') === -1) {
  2966. attr(element, 'xmlns', SVG_NS);
  2967. }
  2968. // object properties
  2969. renderer.isSVG = true;
  2970. renderer.box = element;
  2971. renderer.boxWrapper = boxWrapper;
  2972. renderer.alignedObjects = [];
  2973. // Page url used for internal references. #24, #672, #1070
  2974. renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ?
  2975. win.location.href
  2976. .replace(/#.*?$/, '') // remove the hash
  2977. .replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes
  2978. .replace(/ /g, '%20') : // replace spaces (needed for Safari only)
  2979. '';
  2980. // Add description
  2981. desc = this.createElement('desc').add();
  2982. desc.element.appendChild(doc.createTextNode('Created with ' + PRODUCT + ' ' + VERSION));
  2983. renderer.defs = this.createElement('defs').add();
  2984. renderer.allowHTML = allowHTML;
  2985. renderer.forExport = forExport;
  2986. renderer.gradients = {}; // Object where gradient SvgElements are stored
  2987. renderer.cache = {}; // Cache for numerical bounding boxes
  2988. renderer.cacheKeys = [];
  2989. renderer.imgCount = 0;
  2990. renderer.setSize(width, height, false);
  2991. // Issue 110 workaround:
  2992. // In Firefox, if a div is positioned by percentage, its pixel position may land
  2993. // between pixels. The container itself doesn't display this, but an SVG element
  2994. // inside this container will be drawn at subpixel precision. In order to draw
  2995. // sharp lines, this must be compensated for. This doesn't seem to work inside
  2996. // iframes though (like in jsFiddle).
  2997. var subPixelFix, rect;
  2998. if (isFirefox && container.getBoundingClientRect) {
  2999. renderer.subPixelFix = subPixelFix = function () {
  3000. css(container, { left: 0, top: 0 });
  3001. rect = container.getBoundingClientRect();
  3002. css(container, {
  3003. left: (mathCeil(rect.left) - rect.left) + PX,
  3004. top: (mathCeil(rect.top) - rect.top) + PX
  3005. });
  3006. };
  3007. // run the fix now
  3008. subPixelFix();
  3009. // run it on resize
  3010. addEvent(win, 'resize', subPixelFix);
  3011. }
  3012. },
  3013. getStyle: function (style) {
  3014. this.style = extend({
  3015. fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif', // default font
  3016. fontSize: '12px'
  3017. }, style);
  3018. return this.style;
  3019. },
  3020. /**
  3021. * Detect whether the renderer is hidden. This happens when one of the parent elements
  3022. * has display: none. #608.
  3023. */
  3024. isHidden: function () {
  3025. return !this.boxWrapper.getBBox().width;
  3026. },
  3027. /**
  3028. * Destroys the renderer and its allocated members.
  3029. */
  3030. destroy: function () {
  3031. var renderer = this,
  3032. rendererDefs = renderer.defs;
  3033. renderer.box = null;
  3034. renderer.boxWrapper = renderer.boxWrapper.destroy();
  3035. // Call destroy on all gradient elements
  3036. destroyObjectProperties(renderer.gradients || {});
  3037. renderer.gradients = null;
  3038. // Defs are null in VMLRenderer
  3039. // Otherwise, destroy them here.
  3040. if (rendererDefs) {
  3041. renderer.defs = rendererDefs.destroy();
  3042. }
  3043. // Remove sub pixel fix handler
  3044. // We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed
  3045. // See issue #982
  3046. if (renderer.subPixelFix) {
  3047. removeEvent(win, 'resize', renderer.subPixelFix);
  3048. }
  3049. renderer.alignedObjects = null;
  3050. return null;
  3051. },
  3052. /**
  3053. * Create a wrapper for an SVG element
  3054. * @param {Object} nodeName
  3055. */
  3056. createElement: function (nodeName) {
  3057. var wrapper = new this.Element();
  3058. wrapper.init(this, nodeName);
  3059. return wrapper;
  3060. },
  3061. /**
  3062. * Dummy function for use in canvas renderer
  3063. */
  3064. draw: function () {},
  3065. /**
  3066. * Get converted radial gradient attributes
  3067. */
  3068. getRadialAttr: function (radialReference, gradAttr) {
  3069. return {
  3070. cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2],
  3071. cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2],
  3072. r: gradAttr.r * radialReference[2]
  3073. };
  3074. },
  3075. /**
  3076. * Parse a simple HTML string into SVG tspans
  3077. *
  3078. * @param {Object} textNode The parent text SVG node
  3079. */
  3080. buildText: function (wrapper) {
  3081. var textNode = wrapper.element,
  3082. renderer = this,
  3083. forExport = renderer.forExport,
  3084. textStr = pick(wrapper.textStr, '').toString(),
  3085. hasMarkup = textStr.indexOf('<') !== -1,
  3086. lines,
  3087. childNodes = textNode.childNodes,
  3088. styleRegex,
  3089. hrefRegex,
  3090. wasTooLong,
  3091. parentX = attr(textNode, 'x'),
  3092. textStyles = wrapper.styles,
  3093. width = wrapper.textWidth,
  3094. textLineHeight = textStyles && textStyles.lineHeight,
  3095. textShadow = textStyles && textStyles.textShadow,
  3096. ellipsis = textStyles && textStyles.textOverflow === 'ellipsis',
  3097. i = childNodes.length,
  3098. tempParent = width && !wrapper.added && this.box,
  3099. getLineHeight = function (tspan) {
  3100. return textLineHeight ?
  3101. pInt(textLineHeight) :
  3102. renderer.fontMetrics(
  3103. /(px|em)$/.test(tspan && tspan.style.fontSize) ?
  3104. tspan.style.fontSize :
  3105. ((textStyles && textStyles.fontSize) || renderer.style.fontSize || 12),
  3106. tspan
  3107. ).h;
  3108. },
  3109. unescapeAngleBrackets = function (inputStr) {
  3110. return inputStr.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
  3111. };
  3112. /// remove old text
  3113. while (i--) {
  3114. textNode.removeChild(childNodes[i]);
  3115. }
  3116. // Skip tspans, add text directly to text node. The forceTSpan is a hook
  3117. // used in text outline hack.
  3118. if (!hasMarkup && !textShadow && !ellipsis && !width && textStr.indexOf(' ') === -1) {
  3119. textNode.appendChild(doc.createTextNode(unescapeAngleBrackets(textStr)));
  3120. // Complex strings, add more logic
  3121. } else {
  3122. styleRegex = /<.*style="([^"]+)".*>/;
  3123. hrefRegex = /<.*href="(http[^"]+)".*>/;
  3124. if (tempParent) {
  3125. tempParent.appendChild(textNode); // attach it to the DOM to read offset width
  3126. }
  3127. if (hasMarkup) {
  3128. lines = textStr
  3129. .replace(/<(b|strong)>/g, '<span style="font-weight:bold">')
  3130. .replace(/<(i|em)>/g, '<span style="font-style:italic">')
  3131. .replace(/<a/g, '<span')
  3132. .replace(/<\/(b|strong|i|em|a)>/g, '</span>')
  3133. .split(/<br.*?>/g);
  3134. } else {
  3135. lines = [textStr];
  3136. }
  3137. // Trim empty lines (#5261)
  3138. lines = grep(lines, function (line) {
  3139. return line !== '';
  3140. });
  3141. // build the lines
  3142. each(lines, function buildTextLines(line, lineNo) {
  3143. var spans,
  3144. spanNo = 0;
  3145. line = line
  3146. .replace(/^\s+|\s+$/g, '') // Trim to prevent useless/costly process on the spaces (#5258)
  3147. .replace(/<span/g, '|||<span')
  3148. .replace(/<\/span>/g, '</span>|||');
  3149. spans = line.split('|||');
  3150. each(spans, function buildTextSpans(span) {
  3151. if (span !== '' || spans.length === 1) {
  3152. var attributes = {},
  3153. tspan = doc.createElementNS(SVG_NS, 'tspan'),
  3154. spanStyle; // #390
  3155. if (styleRegex.test(span)) {
  3156. spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2');
  3157. attr(tspan, 'style', spanStyle);
  3158. }
  3159. if (hrefRegex.test(span) && !forExport) { // Not for export - #1529
  3160. attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"');
  3161. css(tspan, { cursor: 'pointer' });
  3162. }
  3163. span = unescapeAngleBrackets(span.replace(/<(.|\n)*?>/g, '') || ' ');
  3164. // Nested tags aren't supported, and cause crash in Safari (#1596)
  3165. if (span !== ' ') {
  3166. // add the text node
  3167. tspan.appendChild(doc.createTextNode(span));
  3168. if (!spanNo) { // first span in a line, align it to the left
  3169. if (lineNo && parentX !== null) {
  3170. attributes.x = parentX;
  3171. }
  3172. } else {
  3173. attributes.dx = 0; // #16
  3174. }
  3175. // add attributes
  3176. attr(tspan, attributes);
  3177. // Append it
  3178. textNode.appendChild(tspan);
  3179. // first span on subsequent line, add the line height
  3180. if (!spanNo && lineNo) {
  3181. // allow getting the right offset height in exporting in IE
  3182. if (!hasSVG && forExport) {
  3183. css(tspan, { display: 'block' });
  3184. }
  3185. // Set the line height based on the font size of either
  3186. // the text element or the tspan element
  3187. attr(
  3188. tspan,
  3189. 'dy',
  3190. getLineHeight(tspan)
  3191. );
  3192. }
  3193. /*if (width) {
  3194. renderer.breakText(wrapper, width);
  3195. }*/
  3196. // Check width and apply soft breaks or ellipsis
  3197. if (width) {
  3198. var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273
  3199. noWrap = textStyles.whiteSpace === 'nowrap',
  3200. hasWhiteSpace = spans.length > 1 || lineNo || (words.length > 1 && !noWrap),
  3201. tooLong,
  3202. actualWidth,
  3203. rest = [],
  3204. dy = getLineHeight(tspan),
  3205. softLineNo = 1,
  3206. rotation = wrapper.rotation,
  3207. wordStr = span, // for ellipsis
  3208. cursor = wordStr.length, // binary search cursor
  3209. bBox;
  3210. while ((hasWhiteSpace || ellipsis) && (words.length || rest.length)) {
  3211. wrapper.rotation = 0; // discard rotation when computing box
  3212. bBox = wrapper.getBBox(true);
  3213. actualWidth = bBox.width;
  3214. // Old IE cannot measure the actualWidth for SVG elements (#2314)
  3215. if (!hasSVG && renderer.forExport) {
  3216. actualWidth = renderer.measureSpanWidth(tspan.firstChild.data, wrapper.styles);
  3217. }
  3218. tooLong = actualWidth > width;
  3219. // For ellipsis, do a binary search for the correct string length
  3220. if (wasTooLong === undefined) {
  3221. wasTooLong = tooLong; // First time
  3222. }
  3223. if (ellipsis && wasTooLong) {
  3224. cursor /= 2;
  3225. if (wordStr === '' || (!tooLong && cursor < 0.5)) {
  3226. words = []; // All ok, break out
  3227. } else {
  3228. wordStr = span.substring(0, wordStr.length + (tooLong ? -1 : 1) * mathCeil(cursor));
  3229. words = [wordStr + (width > 3 ? '\u2026' : '')];
  3230. tspan.removeChild(tspan.firstChild);
  3231. }
  3232. // Looping down, this is the first word sequence that is not too long,
  3233. // so we can move on to build the next line.
  3234. } else if (!tooLong || words.length === 1) {
  3235. words = rest;
  3236. rest = [];
  3237. if (words.length && !noWrap) {
  3238. softLineNo++;
  3239. tspan = doc.createElementNS(SVG_NS, 'tspan');
  3240. attr(tspan, {
  3241. dy: dy,
  3242. x: parentX
  3243. });
  3244. if (spanStyle) { // #390
  3245. attr(tspan, 'style', spanStyle);
  3246. }
  3247. textNode.appendChild(tspan);
  3248. }
  3249. if (actualWidth > width) { // a single word is pressing it out
  3250. width = actualWidth;
  3251. }
  3252. } else { // append to existing line tspan
  3253. tspan.removeChild(tspan.firstChild);
  3254. rest.unshift(words.pop());
  3255. }
  3256. if (words.length) {
  3257. tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-')));
  3258. }
  3259. }
  3260. wrapper.rotation = rotation;
  3261. }
  3262. spanNo++;
  3263. }
  3264. }
  3265. });
  3266. });
  3267. if (wasTooLong) {
  3268. wrapper.attr('title', wrapper.textStr);
  3269. }
  3270. if (tempParent) {
  3271. tempParent.removeChild(textNode); // attach it to the DOM to read offset width
  3272. }
  3273. // Apply the text shadow
  3274. if (textShadow && wrapper.applyTextShadow) {
  3275. wrapper.applyTextShadow(textShadow);
  3276. }
  3277. }
  3278. },
  3279. /*
  3280. breakText: function (wrapper, width) {
  3281. var bBox = wrapper.getBBox(),
  3282. node = wrapper.element,
  3283. textLength = node.textContent.length,
  3284. pos = mathRound(width * textLength / bBox.width), // try this position first, based on average character width
  3285. increment = 0,
  3286. finalPos;
  3287. if (bBox.width > width) {
  3288. while (finalPos === undefined) {
  3289. textLength = node.getSubStringLength(0, pos);
  3290. if (textLength <= width) {
  3291. if (increment === -1) {
  3292. finalPos = pos;
  3293. } else {
  3294. increment = 1;
  3295. }
  3296. } else {
  3297. if (increment === 1) {
  3298. finalPos = pos - 1;
  3299. } else {
  3300. increment = -1;
  3301. }
  3302. }
  3303. pos += increment;
  3304. }
  3305. }
  3306. console.log('width', width, 'stringWidth', node.getSubStringLength(0, finalPos))
  3307. },
  3308. */
  3309. /**
  3310. * Returns white for dark colors and black for bright colors
  3311. */
  3312. getContrast: function (color) {
  3313. color = Color(color).rgba;
  3314. return color[0] + color[1] + color[2] > 384 ? '#000000' : '#FFFFFF';
  3315. },
  3316. /**
  3317. * Create a button with preset states
  3318. * @param {String} text
  3319. * @param {Number} x
  3320. * @param {Number} y
  3321. * @param {Function} callback
  3322. * @param {Object} normalState
  3323. * @param {Object} hoverState
  3324. * @param {Object} pressedState
  3325. */
  3326. button: function (text, x, y, callback, normalState, hoverState, pressedState, disabledState, shape) {
  3327. var label = this.label(text, x, y, shape, null, null, null, null, 'button'),
  3328. curState = 0,
  3329. stateOptions,
  3330. stateStyle,
  3331. normalStyle,
  3332. hoverStyle,
  3333. pressedStyle,
  3334. disabledStyle,
  3335. verticalGradient = { x1: 0, y1: 0, x2: 0, y2: 1 };
  3336. // Normal state - prepare the attributes
  3337. normalState = merge({
  3338. 'stroke-width': 1,
  3339. stroke: '#CCCCCC',
  3340. fill: {
  3341. linearGradient: verticalGradient,
  3342. stops: [
  3343. [0, '#FEFEFE'],
  3344. [1, '#F6F6F6']
  3345. ]
  3346. },
  3347. r: 2,
  3348. padding: 5,
  3349. style: {
  3350. color: 'black'
  3351. }
  3352. }, normalState);
  3353. normalStyle = normalState.style;
  3354. delete normalState.style;
  3355. // Hover state
  3356. hoverState = merge(normalState, {
  3357. stroke: '#68A',
  3358. fill: {
  3359. linearGradient: verticalGradient,
  3360. stops: [
  3361. [0, '#FFF'],
  3362. [1, '#ACF']
  3363. ]
  3364. }
  3365. }, hoverState);
  3366. hoverStyle = hoverState.style;
  3367. delete hoverState.style;
  3368. // Pressed state
  3369. pressedState = merge(normalState, {
  3370. stroke: '#68A',
  3371. fill: {
  3372. linearGradient: verticalGradient,
  3373. stops: [
  3374. [0, '#9BD'],
  3375. [1, '#CDF']
  3376. ]
  3377. }
  3378. }, pressedState);
  3379. pressedStyle = pressedState.style;
  3380. delete pressedState.style;
  3381. // Disabled state
  3382. disabledState = merge(normalState, {
  3383. style: {
  3384. color: '#CCC'
  3385. }
  3386. }, disabledState);
  3387. disabledStyle = disabledState.style;
  3388. delete disabledState.style;
  3389. // Add the events. IE9 and IE10 need mouseover and mouseout to funciton (#667).
  3390. addEvent(label.element, isMS ? 'mouseover' : 'mouseenter', function () {
  3391. if (curState !== 3) {
  3392. label.attr(hoverState)
  3393. .css(hoverStyle);
  3394. }
  3395. });
  3396. addEvent(label.element, isMS ? 'mouseout' : 'mouseleave', function () {
  3397. if (curState !== 3) {
  3398. stateOptions = [normalState, hoverState, pressedState][curState];
  3399. stateStyle = [normalStyle, hoverStyle, pressedStyle][curState];
  3400. label.attr(stateOptions)
  3401. .css(stateStyle);
  3402. }
  3403. });
  3404. label.setState = function (state) {
  3405. label.state = curState = state;
  3406. if (!state) {
  3407. label.attr(normalState)
  3408. .css(normalStyle);
  3409. } else if (state === 2) {
  3410. label.attr(pressedState)
  3411. .css(pressedStyle);
  3412. } else if (state === 3) {
  3413. label.attr(disabledState)
  3414. .css(disabledStyle);
  3415. }
  3416. };
  3417. return label
  3418. .on('click', function (e) {
  3419. if (curState !== 3) {
  3420. callback.call(label, e);
  3421. }
  3422. })
  3423. .attr(normalState)
  3424. .css(extend({ cursor: 'default' }, normalStyle));
  3425. },
  3426. /**
  3427. * Make a straight line crisper by not spilling out to neighbour pixels
  3428. * @param {Array} points
  3429. * @param {Number} width
  3430. */
  3431. crispLine: function (points, width) {
  3432. // points format: [M, 0, 0, L, 100, 0]
  3433. // normalize to a crisp line
  3434. if (points[1] === points[4]) {
  3435. // Substract due to #1129. Now bottom and left axis gridlines behave the same.
  3436. points[1] = points[4] = mathRound(points[1]) - (width % 2 / 2);
  3437. }
  3438. if (points[2] === points[5]) {
  3439. points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2);
  3440. }
  3441. return points;
  3442. },
  3443. /**
  3444. * Draw a path
  3445. * @param {Array} path An SVG path in array form
  3446. */
  3447. path: function (path) {
  3448. var attr = {
  3449. fill: NONE
  3450. };
  3451. if (isArray(path)) {
  3452. attr.d = path;
  3453. } else if (isObject(path)) { // attributes
  3454. extend(attr, path);
  3455. }
  3456. return this.createElement('path').attr(attr);
  3457. },
  3458. /**
  3459. * Draw and return an SVG circle
  3460. * @param {Number} x The x position
  3461. * @param {Number} y The y position
  3462. * @param {Number} r The radius
  3463. */
  3464. circle: function (x, y, r) {
  3465. var attr = isObject(x) ? x : { x: x, y: y, r: r },
  3466. wrapper = this.createElement('circle');
  3467. // Setting x or y translates to cx and cy
  3468. wrapper.xSetter = wrapper.ySetter = function (value, key, element) {
  3469. element.setAttribute('c' + key, value);
  3470. };
  3471. return wrapper.attr(attr);
  3472. },
  3473. /**
  3474. * Draw and return an arc
  3475. * @param {Number} x X position
  3476. * @param {Number} y Y position
  3477. * @param {Number} r Radius
  3478. * @param {Number} innerR Inner radius like used in donut charts
  3479. * @param {Number} start Starting angle
  3480. * @param {Number} end Ending angle
  3481. */
  3482. arc: function (x, y, r, innerR, start, end) {
  3483. var arc;
  3484. if (isObject(x)) {
  3485. y = x.y;
  3486. r = x.r;
  3487. innerR = x.innerR;
  3488. start = x.start;
  3489. end = x.end;
  3490. x = x.x;
  3491. }
  3492. // Arcs are defined as symbols for the ability to set
  3493. // attributes in attr and animate
  3494. arc = this.symbol('arc', x || 0, y || 0, r || 0, r || 0, {
  3495. innerR: innerR || 0,
  3496. start: start || 0,
  3497. end: end || 0
  3498. });
  3499. arc.r = r; // #959
  3500. return arc;
  3501. },
  3502. /**
  3503. * Draw and return a rectangle
  3504. * @param {Number} x Left position
  3505. * @param {Number} y Top position
  3506. * @param {Number} width
  3507. * @param {Number} height
  3508. * @param {Number} r Border corner radius
  3509. * @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing
  3510. */
  3511. rect: function (x, y, width, height, r, strokeWidth) {
  3512. r = isObject(x) ? x.r : r;
  3513. var wrapper = this.createElement('rect'),
  3514. attribs = isObject(x) ? x : x === UNDEFINED ? {} : {
  3515. x: x,
  3516. y: y,
  3517. width: mathMax(width, 0),
  3518. height: mathMax(height, 0)
  3519. };
  3520. if (strokeWidth !== UNDEFINED) {
  3521. wrapper.strokeWidth = strokeWidth;
  3522. attribs = wrapper.crisp(attribs);
  3523. }
  3524. if (r) {
  3525. attribs.r = r;
  3526. }
  3527. wrapper.rSetter = function (value, key, element) {
  3528. attr(element, {
  3529. rx: value,
  3530. ry: value
  3531. });
  3532. };
  3533. return wrapper.attr(attribs);
  3534. },
  3535. /**
  3536. * Resize the box and re-align all aligned elements
  3537. * @param {Object} width
  3538. * @param {Object} height
  3539. * @param {Boolean} animate
  3540. *
  3541. */
  3542. setSize: function (width, height, animate) {
  3543. var renderer = this,
  3544. alignedObjects = renderer.alignedObjects,
  3545. i = alignedObjects.length;
  3546. renderer.width = width;
  3547. renderer.height = height;
  3548. renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({
  3549. width: width,
  3550. height: height
  3551. });
  3552. while (i--) {
  3553. alignedObjects[i].align();
  3554. }
  3555. },
  3556. /**
  3557. * Create a group
  3558. * @param {String} name The group will be given a class name of 'highcharts-{name}'.
  3559. * This can be used for styling and scripting.
  3560. */
  3561. g: function (name) {
  3562. var elem = this.createElement('g');
  3563. return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem;
  3564. },
  3565. /**
  3566. * Display an image
  3567. * @param {String} src
  3568. * @param {Number} x
  3569. * @param {Number} y
  3570. * @param {Number} width
  3571. * @param {Number} height
  3572. */
  3573. image: function (src, x, y, width, height) {
  3574. var attribs = {
  3575. preserveAspectRatio: NONE
  3576. },
  3577. elemWrapper;
  3578. // optional properties
  3579. if (arguments.length > 1) {
  3580. extend(attribs, {
  3581. x: x,
  3582. y: y,
  3583. width: width,
  3584. height: height
  3585. });
  3586. }
  3587. elemWrapper = this.createElement('image').attr(attribs);
  3588. // set the href in the xlink namespace
  3589. if (elemWrapper.element.setAttributeNS) {
  3590. elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink',
  3591. 'href', src);
  3592. } else {
  3593. // could be exporting in IE
  3594. // using href throws "not supported" in ie7 and under, requries regex shim to fix later
  3595. elemWrapper.element.setAttribute('hc-svg-href', src);
  3596. }
  3597. return elemWrapper;
  3598. },
  3599. /**
  3600. * Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object.
  3601. *
  3602. * @param {Object} symbol
  3603. * @param {Object} x
  3604. * @param {Object} y
  3605. * @param {Object} radius
  3606. * @param {Object} options
  3607. */
  3608. symbol: function (symbol, x, y, width, height, options) {
  3609. var ren = this,
  3610. obj,
  3611. // get the symbol definition function
  3612. symbolFn = this.symbols[symbol],
  3613. // check if there's a path defined for this symbol
  3614. path = symbolFn && symbolFn(
  3615. mathRound(x),
  3616. mathRound(y),
  3617. width,
  3618. height,
  3619. options
  3620. ),
  3621. imageRegex = /^url\((.*?)\)$/,
  3622. imageSrc,
  3623. imageSize,
  3624. centerImage;
  3625. if (path) {
  3626. obj = this.path(path);
  3627. // expando properties for use in animate and attr
  3628. extend(obj, {
  3629. symbolName: symbol,
  3630. x: x,
  3631. y: y,
  3632. width: width,
  3633. height: height
  3634. });
  3635. if (options) {
  3636. extend(obj, options);
  3637. }
  3638. // image symbols
  3639. } else if (imageRegex.test(symbol)) {
  3640. // On image load, set the size and position
  3641. centerImage = function (img, size) {
  3642. if (img.element) { // it may be destroyed in the meantime (#1390)
  3643. img.attr({
  3644. width: size[0],
  3645. height: size[1]
  3646. });
  3647. if (!img.alignByTranslate) { // #185
  3648. img.translate(
  3649. mathRound((width - size[0]) / 2), // #1378
  3650. mathRound((height - size[1]) / 2)
  3651. );
  3652. }
  3653. }
  3654. };
  3655. imageSrc = symbol.match(imageRegex)[1];
  3656. imageSize = symbolSizes[imageSrc] || (options && options.width && options.height && [options.width, options.height]);
  3657. // Ireate the image synchronously, add attribs async
  3658. obj = this.image(imageSrc)
  3659. .attr({
  3660. x: x,
  3661. y: y
  3662. });
  3663. obj.isImg = true;
  3664. if (imageSize) {
  3665. centerImage(obj, imageSize);
  3666. } else {
  3667. // Initialize image to be 0 size so export will still function if there's no cached sizes.
  3668. obj.attr({ width: 0, height: 0 });
  3669. // Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8,
  3670. // the created element must be assigned to a variable in order to load (#292).
  3671. createElement('img', {
  3672. onload: function () {
  3673. var chart = charts[ren.chartIndex];
  3674. // Special case for SVGs on IE11, the width is not accessible until the image is
  3675. // part of the DOM (#2854).
  3676. if (this.width === 0) {
  3677. css(this, {
  3678. position: ABSOLUTE,
  3679. top: '-999em'
  3680. });
  3681. doc.body.appendChild(this);
  3682. }
  3683. // Center the image
  3684. centerImage(obj, symbolSizes[imageSrc] = [this.width, this.height]);
  3685. // Clean up after #2854 workaround.
  3686. if (this.parentNode) {
  3687. this.parentNode.removeChild(this);
  3688. }
  3689. // Fire the load event when all external images are loaded
  3690. ren.imgCount--;
  3691. if (!ren.imgCount && chart && chart.onload) {
  3692. chart.onload();
  3693. }
  3694. },
  3695. src: imageSrc
  3696. });
  3697. this.imgCount++;
  3698. }
  3699. }
  3700. return obj;
  3701. },
  3702. /**
  3703. * An extendable collection of functions for defining symbol paths.
  3704. */
  3705. symbols: {
  3706. 'circle': function (x, y, w, h) {
  3707. var cpw = 0.166 * w;
  3708. return [
  3709. M, x + w / 2, y,
  3710. 'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h,
  3711. 'C', x - cpw, y + h, x - cpw, y, x + w / 2, y,
  3712. 'Z'
  3713. ];
  3714. },
  3715. 'square': function (x, y, w, h) {
  3716. return [
  3717. M, x, y,
  3718. L, x + w, y,
  3719. x + w, y + h,
  3720. x, y + h,
  3721. 'Z'
  3722. ];
  3723. },
  3724. 'triangle': function (x, y, w, h) {
  3725. return [
  3726. M, x + w / 2, y,
  3727. L, x + w, y + h,
  3728. x, y + h,
  3729. 'Z'
  3730. ];
  3731. },
  3732. 'triangle-down': function (x, y, w, h) {
  3733. return [
  3734. M, x, y,
  3735. L, x + w, y,
  3736. x + w / 2, y + h,
  3737. 'Z'
  3738. ];
  3739. },
  3740. 'diamond': function (x, y, w, h) {
  3741. return [
  3742. M, x + w / 2, y,
  3743. L, x + w, y + h / 2,
  3744. x + w / 2, y + h,
  3745. x, y + h / 2,
  3746. 'Z'
  3747. ];
  3748. },
  3749. 'arc': function (x, y, w, h, options) {
  3750. var start = options.start,
  3751. radius = options.r || w || h,
  3752. end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561)
  3753. innerRadius = options.innerR,
  3754. open = options.open,
  3755. cosStart = mathCos(start),
  3756. sinStart = mathSin(start),
  3757. cosEnd = mathCos(end),
  3758. sinEnd = mathSin(end),
  3759. longArc = options.end - start < mathPI ? 0 : 1;
  3760. return [
  3761. M,
  3762. x + radius * cosStart,
  3763. y + radius * sinStart,
  3764. 'A', // arcTo
  3765. radius, // x radius
  3766. radius, // y radius
  3767. 0, // slanting
  3768. longArc, // long or short arc
  3769. 1, // clockwise
  3770. x + radius * cosEnd,
  3771. y + radius * sinEnd,
  3772. open ? M : L,
  3773. x + innerRadius * cosEnd,
  3774. y + innerRadius * sinEnd,
  3775. 'A', // arcTo
  3776. innerRadius, // x radius
  3777. innerRadius, // y radius
  3778. 0, // slanting
  3779. longArc, // long or short arc
  3780. 0, // clockwise
  3781. x + innerRadius * cosStart,
  3782. y + innerRadius * sinStart,
  3783. open ? '' : 'Z' // close
  3784. ];
  3785. },
  3786. /**
  3787. * Callout shape used for default tooltips, also used for rounded rectangles in VML
  3788. */
  3789. callout: function (x, y, w, h, options) {
  3790. var arrowLength = 6,
  3791. halfDistance = 6,
  3792. r = mathMin((options && options.r) || 0, w, h),
  3793. safeDistance = r + halfDistance,
  3794. anchorX = options && options.anchorX,
  3795. anchorY = options && options.anchorY,
  3796. path;
  3797. path = [
  3798. 'M', x + r, y,
  3799. 'L', x + w - r, y, // top side
  3800. 'C', x + w, y, x + w, y, x + w, y + r, // top-right corner
  3801. 'L', x + w, y + h - r, // right side
  3802. 'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-right corner
  3803. 'L', x + r, y + h, // bottom side
  3804. 'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner
  3805. 'L', x, y + r, // left side
  3806. 'C', x, y, x, y, x + r, y // top-right corner
  3807. ];
  3808. if (anchorX && anchorX > w && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace right side
  3809. path.splice(13, 3,
  3810. 'L', x + w, anchorY - halfDistance,
  3811. x + w + arrowLength, anchorY,
  3812. x + w, anchorY + halfDistance,
  3813. x + w, y + h - r
  3814. );
  3815. } else if (anchorX && anchorX < 0 && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace left side
  3816. path.splice(33, 3,
  3817. 'L', x, anchorY + halfDistance,
  3818. x - arrowLength, anchorY,
  3819. x, anchorY - halfDistance,
  3820. x, y + r
  3821. );
  3822. } else if (anchorY && anchorY > h && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace bottom
  3823. path.splice(23, 3,
  3824. 'L', anchorX + halfDistance, y + h,
  3825. anchorX, y + h + arrowLength,
  3826. anchorX - halfDistance, y + h,
  3827. x + r, y + h
  3828. );
  3829. } else if (anchorY && anchorY < 0 && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace top
  3830. path.splice(3, 3,
  3831. 'L', anchorX - halfDistance, y,
  3832. anchorX, y - arrowLength,
  3833. anchorX + halfDistance, y,
  3834. w - r, y
  3835. );
  3836. }
  3837. return path;
  3838. }
  3839. },
  3840. /**
  3841. * Define a clipping rectangle
  3842. * @param {String} id
  3843. * @param {Number} x
  3844. * @param {Number} y
  3845. * @param {Number} width
  3846. * @param {Number} height
  3847. */
  3848. clipRect: function (x, y, width, height) {
  3849. var wrapper,
  3850. id = PREFIX + idCounter++,
  3851. clipPath = this.createElement('clipPath').attr({
  3852. id: id
  3853. }).add(this.defs);
  3854. wrapper = this.rect(x, y, width, height, 0).add(clipPath);
  3855. wrapper.id = id;
  3856. wrapper.clipPath = clipPath;
  3857. wrapper.count = 0;
  3858. return wrapper;
  3859. },
  3860. /**
  3861. * Add text to the SVG object
  3862. * @param {String} str
  3863. * @param {Number} x Left position
  3864. * @param {Number} y Top position
  3865. * @param {Boolean} useHTML Use HTML to render the text
  3866. */
  3867. text: function (str, x, y, useHTML) {
  3868. // declare variables
  3869. var renderer = this,
  3870. fakeSVG = useCanVG || (!hasSVG && renderer.forExport),
  3871. wrapper,
  3872. attr = {};
  3873. if (useHTML && (renderer.allowHTML || !renderer.forExport)) {
  3874. return renderer.html(str, x, y);
  3875. }
  3876. attr.x = Math.round(x || 0); // X is always needed for line-wrap logic
  3877. if (y) {
  3878. attr.y = Math.round(y);
  3879. }
  3880. if (str || str === 0) {
  3881. attr.text = str;
  3882. }
  3883. wrapper = renderer.createElement('text')
  3884. .attr(attr);
  3885. // Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063)
  3886. if (fakeSVG) {
  3887. wrapper.css({
  3888. position: ABSOLUTE
  3889. });
  3890. }
  3891. if (!useHTML) {
  3892. wrapper.xSetter = function (value, key, element) {
  3893. var tspans = element.getElementsByTagName('tspan'),
  3894. tspan,
  3895. parentVal = element.getAttribute(key),
  3896. i;
  3897. for (i = 0; i < tspans.length; i++) {
  3898. tspan = tspans[i];
  3899. // If the x values are equal, the tspan represents a linebreak
  3900. if (tspan.getAttribute(key) === parentVal) {
  3901. tspan.setAttribute(key, value);
  3902. }
  3903. }
  3904. element.setAttribute(key, value);
  3905. };
  3906. }
  3907. return wrapper;
  3908. },
  3909. /**
  3910. * Utility to return the baseline offset and total line height from the font size
  3911. */
  3912. fontMetrics: function (fontSize, elem) {
  3913. var lineHeight,
  3914. baseline,
  3915. style;
  3916. fontSize = fontSize || this.style.fontSize;
  3917. if (!fontSize && elem && win.getComputedStyle) {
  3918. elem = elem.element || elem; // SVGElement
  3919. style = win.getComputedStyle(elem, '');
  3920. fontSize = style && style.fontSize; // #4309, the style doesn't exist inside a hidden iframe in Firefox
  3921. }
  3922. fontSize = /px/.test(fontSize) ? pInt(fontSize) : /em/.test(fontSize) ? parseFloat(fontSize) * 12 : 12;
  3923. // Empirical values found by comparing font size and bounding box height.
  3924. // Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/
  3925. lineHeight = fontSize < 24 ? fontSize + 3 : mathRound(fontSize * 1.2);
  3926. baseline = mathRound(lineHeight * 0.8);
  3927. return {
  3928. h: lineHeight,
  3929. b: baseline,
  3930. f: fontSize
  3931. };
  3932. },
  3933. /**
  3934. * Correct X and Y positioning of a label for rotation (#1764)
  3935. */
  3936. rotCorr: function (baseline, rotation, alterY) {
  3937. var y = baseline;
  3938. if (rotation && alterY) {
  3939. y = mathMax(y * mathCos(rotation * deg2rad), 4);
  3940. }
  3941. return {
  3942. x: (-baseline / 3) * mathSin(rotation * deg2rad),
  3943. y: y
  3944. };
  3945. },
  3946. /**
  3947. * Add a label, a text item that can hold a colored or gradient background
  3948. * as well as a border and shadow.
  3949. * @param {string} str
  3950. * @param {Number} x
  3951. * @param {Number} y
  3952. * @param {String} shape
  3953. * @param {Number} anchorX In case the shape has a pointer, like a flag, this is the
  3954. * coordinates it should be pinned to
  3955. * @param {Number} anchorY
  3956. * @param {Boolean} baseline Whether to position the label relative to the text baseline,
  3957. * like renderer.text, or to the upper border of the rectangle.
  3958. * @param {String} className Class name for the group
  3959. */
  3960. label: function (str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) {
  3961. var renderer = this,
  3962. wrapper = renderer.g(className),
  3963. text = renderer.text('', 0, 0, useHTML)
  3964. .attr({
  3965. zIndex: 1
  3966. }),
  3967. //.add(wrapper),
  3968. box,
  3969. bBox,
  3970. alignFactor = 0,
  3971. padding = 3,
  3972. paddingLeft = 0,
  3973. width,
  3974. height,
  3975. wrapperX,
  3976. wrapperY,
  3977. crispAdjust = 0,
  3978. deferredAttr = {},
  3979. baselineOffset,
  3980. hasBGImage = /^url\((.*?)\)$/.test(shape),
  3981. needsBox = hasBGImage,
  3982. updateBoxSize,
  3983. updateTextPadding,
  3984. boxAttr;
  3985. /**
  3986. * This function runs after the label is added to the DOM (when the bounding box is
  3987. * available), and after the text of the label is updated to detect the new bounding
  3988. * box and reflect it in the border box.
  3989. */
  3990. updateBoxSize = function () {
  3991. var boxX,
  3992. boxY,
  3993. style = text.element.style;
  3994. bBox = (width === undefined || height === undefined || wrapper.styles.textAlign) && defined(text.textStr) &&
  3995. text.getBBox(); //#3295 && 3514 box failure when string equals 0
  3996. wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft;
  3997. wrapper.height = (height || bBox.height || 0) + 2 * padding;
  3998. // update the label-scoped y offset
  3999. baselineOffset = padding + renderer.fontMetrics(style && style.fontSize, text).b;
  4000. if (needsBox) {
  4001. if (!box) {
  4002. // create the border box if it is not already present
  4003. boxX = crispAdjust;
  4004. boxY = (baseline ? -baselineOffset : 0) + crispAdjust;
  4005. wrapper.box = box = renderer.symbols[shape] || hasBGImage ? // Symbol definition exists (#5324)
  4006. renderer.symbol(shape, boxX, boxY, wrapper.width, wrapper.height, deferredAttr) :
  4007. renderer.rect(boxX, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]);
  4008. if (!box.isImg) { // #4324, fill "none" causes it to be ignored by mouse events in IE
  4009. box.attr('fill', NONE);
  4010. }
  4011. box.add(wrapper);
  4012. }
  4013. // apply the box attributes
  4014. if (!box.isImg) { // #1630
  4015. box.attr(extend({
  4016. width: mathRound(wrapper.width),
  4017. height: mathRound(wrapper.height)
  4018. }, deferredAttr));
  4019. }
  4020. deferredAttr = null;
  4021. }
  4022. };
  4023. /**
  4024. * This function runs after setting text or padding, but only if padding is changed
  4025. */
  4026. updateTextPadding = function () {
  4027. var styles = wrapper.styles,
  4028. textAlign = styles && styles.textAlign,
  4029. x = paddingLeft + padding,
  4030. y;
  4031. // determin y based on the baseline
  4032. y = baseline ? 0 : baselineOffset;
  4033. // compensate for alignment
  4034. if (defined(width) && bBox && (textAlign === 'center' || textAlign === 'right')) {
  4035. x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width);
  4036. }
  4037. // update if anything changed
  4038. if (x !== text.x || y !== text.y) {
  4039. text.attr('x', x);
  4040. if (y !== UNDEFINED) {
  4041. text.attr('y', y);
  4042. }
  4043. }
  4044. // record current values
  4045. text.x = x;
  4046. text.y = y;
  4047. };
  4048. /**
  4049. * Set a box attribute, or defer it if the box is not yet created
  4050. * @param {Object} key
  4051. * @param {Object} value
  4052. */
  4053. boxAttr = function (key, value) {
  4054. if (box) {
  4055. box.attr(key, value);
  4056. } else {
  4057. deferredAttr[key] = value;
  4058. }
  4059. };
  4060. /**
  4061. * After the text element is added, get the desired size of the border box
  4062. * and add it before the text in the DOM.
  4063. */
  4064. wrapper.onAdd = function () {
  4065. text.add(wrapper);
  4066. wrapper.attr({
  4067. text: (str || str === 0) ? str : '', // alignment is available now // #3295: 0 not rendered if given as a value
  4068. x: x,
  4069. y: y
  4070. });
  4071. if (box && defined(anchorX)) {
  4072. wrapper.attr({
  4073. anchorX: anchorX,
  4074. anchorY: anchorY
  4075. });
  4076. }
  4077. };
  4078. /*
  4079. * Add specific attribute setters.
  4080. */
  4081. // only change local variables
  4082. wrapper.widthSetter = function (value) {
  4083. width = value;
  4084. };
  4085. wrapper.heightSetter = function (value) {
  4086. height = value;
  4087. };
  4088. wrapper.paddingSetter = function (value) {
  4089. if (defined(value) && value !== padding) {
  4090. padding = wrapper.padding = value;
  4091. updateTextPadding();
  4092. }
  4093. };
  4094. wrapper.paddingLeftSetter = function (value) {
  4095. if (defined(value) && value !== paddingLeft) {
  4096. paddingLeft = value;
  4097. updateTextPadding();
  4098. }
  4099. };
  4100. // change local variable and prevent setting attribute on the group
  4101. wrapper.alignSetter = function (value) {
  4102. value = { left: 0, center: 0.5, right: 1 }[value];
  4103. if (value !== alignFactor) {
  4104. alignFactor = value;
  4105. if (bBox) { // Bounding box exists, means we're dynamically changing
  4106. wrapper.attr({ x: wrapperX }); // #5134
  4107. }
  4108. }
  4109. };
  4110. // apply these to the box and the text alike
  4111. wrapper.textSetter = function (value) {
  4112. if (value !== UNDEFINED) {
  4113. text.textSetter(value);
  4114. }
  4115. updateBoxSize();
  4116. updateTextPadding();
  4117. };
  4118. // apply these to the box but not to the text
  4119. wrapper['stroke-widthSetter'] = function (value, key) {
  4120. if (value) {
  4121. needsBox = true;
  4122. }
  4123. crispAdjust = value % 2 / 2;
  4124. boxAttr(key, value);
  4125. };
  4126. wrapper.strokeSetter = wrapper.fillSetter = wrapper.rSetter = function (value, key) {
  4127. if (key === 'fill' && value) {
  4128. needsBox = true;
  4129. }
  4130. boxAttr(key, value);
  4131. };
  4132. wrapper.anchorXSetter = function (value, key) {
  4133. anchorX = value;
  4134. boxAttr(key, mathRound(value) - crispAdjust - wrapperX);
  4135. };
  4136. wrapper.anchorYSetter = function (value, key) {
  4137. anchorY = value;
  4138. boxAttr(key, value - wrapperY);
  4139. };
  4140. // rename attributes
  4141. wrapper.xSetter = function (value) {
  4142. wrapper.x = value; // for animation getter
  4143. if (alignFactor) {
  4144. value -= alignFactor * ((width || bBox.width) + 2 * padding);
  4145. }
  4146. wrapperX = mathRound(value);
  4147. wrapper.attr('translateX', wrapperX);
  4148. };
  4149. wrapper.ySetter = function (value) {
  4150. wrapperY = wrapper.y = mathRound(value);
  4151. wrapper.attr('translateY', wrapperY);
  4152. };
  4153. // Redirect certain methods to either the box or the text
  4154. var baseCss = wrapper.css;
  4155. return extend(wrapper, {
  4156. /**
  4157. * Pick up some properties and apply them to the text instead of the wrapper
  4158. */
  4159. css: function (styles) {
  4160. if (styles) {
  4161. var textStyles = {};
  4162. styles = merge(styles); // create a copy to avoid altering the original object (#537)
  4163. each(wrapper.textProps, function (prop) {
  4164. if (styles[prop] !== UNDEFINED) {
  4165. textStyles[prop] = styles[prop];
  4166. delete styles[prop];
  4167. }
  4168. });
  4169. text.css(textStyles);
  4170. }
  4171. return baseCss.call(wrapper, styles);
  4172. },
  4173. /**
  4174. * Return the bounding box of the box, not the group
  4175. */
  4176. getBBox: function () {
  4177. return {
  4178. width: bBox.width + 2 * padding,
  4179. height: bBox.height + 2 * padding,
  4180. x: bBox.x - padding,
  4181. y: bBox.y - padding
  4182. };
  4183. },
  4184. /**
  4185. * Apply the shadow to the box
  4186. */
  4187. shadow: function (b) {
  4188. if (box) {
  4189. box.shadow(b);
  4190. }
  4191. return wrapper;
  4192. },
  4193. /**
  4194. * Destroy and release memory.
  4195. */
  4196. destroy: function () {
  4197. // Added by button implementation
  4198. removeEvent(wrapper.element, 'mouseenter');
  4199. removeEvent(wrapper.element, 'mouseleave');
  4200. if (text) {
  4201. text = text.destroy();
  4202. }
  4203. if (box) {
  4204. box = box.destroy();
  4205. }
  4206. // Call base implementation to destroy the rest
  4207. SVGElement.prototype.destroy.call(wrapper);
  4208. // Release local pointers (#1298)
  4209. wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = null;
  4210. }
  4211. });
  4212. }
  4213. }; // end SVGRenderer
  4214. // general renderer
  4215. Renderer = SVGRenderer;
  4216. // extend SvgElement for useHTML option
  4217. extend(SVGElement.prototype, {
  4218. /**
  4219. * Apply CSS to HTML elements. This is used in text within SVG rendering and
  4220. * by the VML renderer
  4221. */
  4222. htmlCss: function (styles) {
  4223. var wrapper = this,
  4224. element = wrapper.element,
  4225. textWidth = styles && element.tagName === 'SPAN' && styles.width;
  4226. if (textWidth) {
  4227. delete styles.width;
  4228. wrapper.textWidth = textWidth;
  4229. wrapper.updateTransform();
  4230. }
  4231. if (styles && styles.textOverflow === 'ellipsis') {
  4232. styles.whiteSpace = 'nowrap';
  4233. styles.overflow = 'hidden';
  4234. }
  4235. wrapper.styles = extend(wrapper.styles, styles);
  4236. css(wrapper.element, styles);
  4237. return wrapper;
  4238. },
  4239. /**
  4240. * VML and useHTML method for calculating the bounding box based on offsets
  4241. * @param {Boolean} refresh Whether to force a fresh value from the DOM or to
  4242. * use the cached value
  4243. *
  4244. * @return {Object} A hash containing values for x, y, width and height
  4245. */
  4246. htmlGetBBox: function () {
  4247. var wrapper = this,
  4248. element = wrapper.element;
  4249. // faking getBBox in exported SVG in legacy IE
  4250. // faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?)
  4251. if (element.nodeName === 'text') {
  4252. element.style.position = ABSOLUTE;
  4253. }
  4254. return {
  4255. x: element.offsetLeft,
  4256. y: element.offsetTop,
  4257. width: element.offsetWidth,
  4258. height: element.offsetHeight
  4259. };
  4260. },
  4261. /**
  4262. * VML override private method to update elements based on internal
  4263. * properties based on SVG transform
  4264. */
  4265. htmlUpdateTransform: function () {
  4266. // aligning non added elements is expensive
  4267. if (!this.added) {
  4268. this.alignOnAdd = true;
  4269. return;
  4270. }
  4271. var wrapper = this,
  4272. renderer = wrapper.renderer,
  4273. elem = wrapper.element,
  4274. translateX = wrapper.translateX || 0,
  4275. translateY = wrapper.translateY || 0,
  4276. x = wrapper.x || 0,
  4277. y = wrapper.y || 0,
  4278. align = wrapper.textAlign || 'left',
  4279. alignCorrection = { left: 0, center: 0.5, right: 1 }[align],
  4280. shadows = wrapper.shadows,
  4281. styles = wrapper.styles;
  4282. // apply translate
  4283. css(elem, {
  4284. marginLeft: translateX,
  4285. marginTop: translateY
  4286. });
  4287. if (shadows) { // used in labels/tooltip
  4288. each(shadows, function (shadow) {
  4289. css(shadow, {
  4290. marginLeft: translateX + 1,
  4291. marginTop: translateY + 1
  4292. });
  4293. });
  4294. }
  4295. // apply inversion
  4296. if (wrapper.inverted) { // wrapper is a group
  4297. each(elem.childNodes, function (child) {
  4298. renderer.invertChild(child, elem);
  4299. });
  4300. }
  4301. if (elem.tagName === 'SPAN') {
  4302. var rotation = wrapper.rotation,
  4303. baseline,
  4304. textWidth = pInt(wrapper.textWidth),
  4305. whiteSpace = styles && styles.whiteSpace,
  4306. currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth, wrapper.textAlign].join(',');
  4307. if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed
  4308. baseline = renderer.fontMetrics(elem.style.fontSize).b;
  4309. // Renderer specific handling of span rotation
  4310. if (defined(rotation)) {
  4311. wrapper.setSpanRotation(rotation, alignCorrection, baseline);
  4312. }
  4313. // Reset multiline/ellipsis in order to read width (#4928, #5417)
  4314. css(elem, {
  4315. width: '',
  4316. whiteSpace: whiteSpace || 'nowrap'
  4317. });
  4318. // Update textWidth
  4319. if (elem.offsetWidth > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254
  4320. css(elem, {
  4321. width: textWidth + PX,
  4322. display: 'block',
  4323. whiteSpace: whiteSpace || 'normal' // #3331
  4324. });
  4325. }
  4326. wrapper.getSpanCorrection(elem.offsetWidth, baseline, alignCorrection, rotation, align);
  4327. }
  4328. // apply position with correction
  4329. css(elem, {
  4330. left: (x + (wrapper.xCorr || 0)) + PX,
  4331. top: (y + (wrapper.yCorr || 0)) + PX
  4332. });
  4333. // force reflow in webkit to apply the left and top on useHTML element (#1249)
  4334. if (isWebKit) {
  4335. baseline = elem.offsetHeight; // assigned to baseline for lint purpose
  4336. }
  4337. // record current text transform
  4338. wrapper.cTT = currentTextTransform;
  4339. }
  4340. },
  4341. /**
  4342. * Set the rotation of an individual HTML span
  4343. */
  4344. setSpanRotation: function (rotation, alignCorrection, baseline) {
  4345. var rotationStyle = {},
  4346. cssTransformKey = isMS ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : '';
  4347. rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)';
  4348. rotationStyle[cssTransformKey + (isFirefox ? 'Origin' : '-origin')] = rotationStyle.transformOrigin = (alignCorrection * 100) + '% ' + baseline + 'px';
  4349. css(this.element, rotationStyle);
  4350. },
  4351. /**
  4352. * Get the correction in X and Y positioning as the element is rotated.
  4353. */
  4354. getSpanCorrection: function (width, baseline, alignCorrection) {
  4355. this.xCorr = -width * alignCorrection;
  4356. this.yCorr = -baseline;
  4357. }
  4358. });
  4359. // Extend SvgRenderer for useHTML option.
  4360. extend(SVGRenderer.prototype, {
  4361. /**
  4362. * Create HTML text node. This is used by the VML renderer as well as the SVG
  4363. * renderer through the useHTML option.
  4364. *
  4365. * @param {String} str
  4366. * @param {Number} x
  4367. * @param {Number} y
  4368. */
  4369. html: function (str, x, y) {
  4370. var wrapper = this.createElement('span'),
  4371. element = wrapper.element,
  4372. renderer = wrapper.renderer,
  4373. isSVG = renderer.isSVG,
  4374. addSetters = function (element, style) {
  4375. // These properties are set as attributes on the SVG group, and as
  4376. // identical CSS properties on the div. (#3542)
  4377. each(['display', 'opacity', 'visibility'], function (prop) {
  4378. wrap(element, prop + 'Setter', function (proceed, value, key, elem) {
  4379. proceed.call(this, value, key, elem);
  4380. style[key] = value;
  4381. });
  4382. });
  4383. };
  4384. // Text setter
  4385. wrapper.textSetter = function (value) {
  4386. if (value !== element.innerHTML) {
  4387. delete this.bBox;
  4388. }
  4389. element.innerHTML = this.textStr = value;
  4390. wrapper.htmlUpdateTransform();
  4391. };
  4392. // Add setters for the element itself (#4938)
  4393. if (isSVG) { // #4938, only for HTML within SVG
  4394. addSetters(wrapper, wrapper.element.style);
  4395. }
  4396. // Various setters which rely on update transform
  4397. wrapper.xSetter = wrapper.ySetter = wrapper.alignSetter = wrapper.rotationSetter = function (value, key) {
  4398. if (key === 'align') {
  4399. key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML.
  4400. }
  4401. wrapper[key] = value;
  4402. wrapper.htmlUpdateTransform();
  4403. };
  4404. // Set the default attributes
  4405. wrapper
  4406. .attr({
  4407. text: str,
  4408. x: mathRound(x),
  4409. y: mathRound(y)
  4410. })
  4411. .css({
  4412. position: ABSOLUTE,
  4413. fontFamily: this.style.fontFamily,
  4414. fontSize: this.style.fontSize
  4415. });
  4416. // Keep the whiteSpace style outside the wrapper.styles collection
  4417. element.style.whiteSpace = 'nowrap';
  4418. // Use the HTML specific .css method
  4419. wrapper.css = wrapper.htmlCss;
  4420. // This is specific for HTML within SVG
  4421. if (isSVG) {
  4422. wrapper.add = function (svgGroupWrapper) {
  4423. var htmlGroup,
  4424. container = renderer.box.parentNode,
  4425. parentGroup,
  4426. parents = [];
  4427. this.parentGroup = svgGroupWrapper;
  4428. // Create a mock group to hold the HTML elements
  4429. if (svgGroupWrapper) {
  4430. htmlGroup = svgGroupWrapper.div;
  4431. if (!htmlGroup) {
  4432. // Read the parent chain into an array and read from top down
  4433. parentGroup = svgGroupWrapper;
  4434. while (parentGroup) {
  4435. parents.push(parentGroup);
  4436. // Move up to the next parent group
  4437. parentGroup = parentGroup.parentGroup;
  4438. }
  4439. // Ensure dynamically updating position when any parent is translated
  4440. each(parents.reverse(), function (parentGroup) {
  4441. var htmlGroupStyle,
  4442. cls = attr(parentGroup.element, 'class');
  4443. if (cls) {
  4444. cls = { className: cls };
  4445. } // else null
  4446. // Create a HTML div and append it to the parent div to emulate
  4447. // the SVG group structure
  4448. htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, cls, {
  4449. position: ABSOLUTE,
  4450. left: (parentGroup.translateX || 0) + PX,
  4451. top: (parentGroup.translateY || 0) + PX,
  4452. display: parentGroup.display,
  4453. opacity: parentGroup.opacity, // #5075
  4454. pointerEvents: parentGroup.styles && parentGroup.styles.pointerEvents // #5595
  4455. }, htmlGroup || container); // the top group is appended to container
  4456. // Shortcut
  4457. htmlGroupStyle = htmlGroup.style;
  4458. // Set listeners to update the HTML div's position whenever the SVG group
  4459. // position is changed
  4460. extend(parentGroup, {
  4461. translateXSetter: function (value, key) {
  4462. htmlGroupStyle.left = value + PX;
  4463. parentGroup[key] = value;
  4464. parentGroup.doTransform = true;
  4465. },
  4466. translateYSetter: function (value, key) {
  4467. htmlGroupStyle.top = value + PX;
  4468. parentGroup[key] = value;
  4469. parentGroup.doTransform = true;
  4470. }
  4471. });
  4472. addSetters(parentGroup, htmlGroupStyle);
  4473. });
  4474. }
  4475. } else {
  4476. htmlGroup = container;
  4477. }
  4478. htmlGroup.appendChild(element);
  4479. // Shared with VML:
  4480. wrapper.added = true;
  4481. if (wrapper.alignOnAdd) {
  4482. wrapper.htmlUpdateTransform();
  4483. }
  4484. return wrapper;
  4485. };
  4486. }
  4487. return wrapper;
  4488. }
  4489. });
  4490. /* ****************************************************************************
  4491. * *
  4492. * START OF INTERNET EXPLORER <= 8 SPECIFIC CODE *
  4493. * *
  4494. * For applications and websites that don't need IE support, like platform *
  4495. * targeted mobile apps and web apps, this code can be removed. *
  4496. * *
  4497. *****************************************************************************/
  4498. /**
  4499. * @constructor
  4500. */
  4501. var VMLRenderer, VMLElement;
  4502. if (!hasSVG && !useCanVG) {
  4503. /**
  4504. * The VML element wrapper.
  4505. */
  4506. VMLElement = {
  4507. /**
  4508. * Initialize a new VML element wrapper. It builds the markup as a string
  4509. * to minimize DOM traffic.
  4510. * @param {Object} renderer
  4511. * @param {Object} nodeName
  4512. */
  4513. init: function (renderer, nodeName) {
  4514. var wrapper = this,
  4515. markup = ['<', nodeName, ' filled="f" stroked="f"'],
  4516. style = ['position: ', ABSOLUTE, ';'],
  4517. isDiv = nodeName === DIV;
  4518. // divs and shapes need size
  4519. if (nodeName === 'shape' || isDiv) {
  4520. style.push('left:0;top:0;width:1px;height:1px;');
  4521. }
  4522. style.push('visibility: ', isDiv ? HIDDEN : VISIBLE);
  4523. markup.push(' style="', style.join(''), '"/>');
  4524. // create element with default attributes and style
  4525. if (nodeName) {
  4526. markup = isDiv || nodeName === 'span' || nodeName === 'img' ?
  4527. markup.join('') :
  4528. renderer.prepVML(markup);
  4529. wrapper.element = createElement(markup);
  4530. }
  4531. wrapper.renderer = renderer;
  4532. },
  4533. /**
  4534. * Add the node to the given parent
  4535. * @param {Object} parent
  4536. */
  4537. add: function (parent) {
  4538. var wrapper = this,
  4539. renderer = wrapper.renderer,
  4540. element = wrapper.element,
  4541. box = renderer.box,
  4542. inverted = parent && parent.inverted,
  4543. // get the parent node
  4544. parentNode = parent ?
  4545. parent.element || parent :
  4546. box;
  4547. if (parent) {
  4548. this.parentGroup = parent;
  4549. }
  4550. // if the parent group is inverted, apply inversion on all children
  4551. if (inverted) { // only on groups
  4552. renderer.invertChild(element, parentNode);
  4553. }
  4554. // append it
  4555. parentNode.appendChild(element);
  4556. // align text after adding to be able to read offset
  4557. wrapper.added = true;
  4558. if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) {
  4559. wrapper.updateTransform();
  4560. }
  4561. // fire an event for internal hooks
  4562. if (wrapper.onAdd) {
  4563. wrapper.onAdd();
  4564. }
  4565. return wrapper;
  4566. },
  4567. /**
  4568. * VML always uses htmlUpdateTransform
  4569. */
  4570. updateTransform: SVGElement.prototype.htmlUpdateTransform,
  4571. /**
  4572. * Set the rotation of a span with oldIE's filter
  4573. */
  4574. setSpanRotation: function () {
  4575. // Adjust for alignment and rotation. Rotation of useHTML content is not yet implemented
  4576. // but it can probably be implemented for Firefox 3.5+ on user request. FF3.5+
  4577. // has support for CSS3 transform. The getBBox method also needs to be updated
  4578. // to compensate for the rotation, like it currently does for SVG.
  4579. // Test case: http://jsfiddle.net/highcharts/Ybt44/
  4580. var rotation = this.rotation,
  4581. costheta = mathCos(rotation * deg2rad),
  4582. sintheta = mathSin(rotation * deg2rad);
  4583. css(this.element, {
  4584. filter: rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta,
  4585. ', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta,
  4586. ', sizingMethod=\'auto expand\')'].join('') : NONE
  4587. });
  4588. },
  4589. /**
  4590. * Get the positioning correction for the span after rotating.
  4591. */
  4592. getSpanCorrection: function (width, baseline, alignCorrection, rotation, align) {
  4593. var costheta = rotation ? mathCos(rotation * deg2rad) : 1,
  4594. sintheta = rotation ? mathSin(rotation * deg2rad) : 0,
  4595. height = pick(this.elemHeight, this.element.offsetHeight),
  4596. quad,
  4597. nonLeft = align && align !== 'left';
  4598. // correct x and y
  4599. this.xCorr = costheta < 0 && -width;
  4600. this.yCorr = sintheta < 0 && -height;
  4601. // correct for baseline and corners spilling out after rotation
  4602. quad = costheta * sintheta < 0;
  4603. this.xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection);
  4604. this.yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1);
  4605. // correct for the length/height of the text
  4606. if (nonLeft) {
  4607. this.xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1);
  4608. if (rotation) {
  4609. this.yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1);
  4610. }
  4611. css(this.element, {
  4612. textAlign: align
  4613. });
  4614. }
  4615. },
  4616. /**
  4617. * Converts a subset of an SVG path definition to its VML counterpart. Takes an array
  4618. * as the parameter and returns a string.
  4619. */
  4620. pathToVML: function (value) {
  4621. // convert paths
  4622. var i = value.length,
  4623. path = [];
  4624. while (i--) {
  4625. // Multiply by 10 to allow subpixel precision.
  4626. // Substracting half a pixel seems to make the coordinates
  4627. // align with SVG, but this hasn't been tested thoroughly
  4628. if (isNumber(value[i])) {
  4629. path[i] = mathRound(value[i] * 10) - 5;
  4630. } else if (value[i] === 'Z') { // close the path
  4631. path[i] = 'x';
  4632. } else {
  4633. path[i] = value[i];
  4634. // When the start X and end X coordinates of an arc are too close,
  4635. // they are rounded to the same value above. In this case, substract or
  4636. // add 1 from the end X and Y positions. #186, #760, #1371, #1410.
  4637. if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) {
  4638. // Start and end X
  4639. if (path[i + 5] === path[i + 7]) {
  4640. path[i + 7] += value[i + 7] > value[i + 5] ? 1 : -1;
  4641. }
  4642. // Start and end Y
  4643. if (path[i + 6] === path[i + 8]) {
  4644. path[i + 8] += value[i + 8] > value[i + 6] ? 1 : -1;
  4645. }
  4646. }
  4647. }
  4648. }
  4649. // Loop up again to handle path shortcuts (#2132)
  4650. /*while (i++ < path.length) {
  4651. if (path[i] === 'H') { // horizontal line to
  4652. path[i] = 'L';
  4653. path.splice(i + 2, 0, path[i - 1]);
  4654. } else if (path[i] === 'V') { // vertical line to
  4655. path[i] = 'L';
  4656. path.splice(i + 1, 0, path[i - 2]);
  4657. }
  4658. }*/
  4659. return path.join(' ') || 'x';
  4660. },
  4661. /**
  4662. * Set the element's clipping to a predefined rectangle
  4663. *
  4664. * @param {String} id The id of the clip rectangle
  4665. */
  4666. clip: function (clipRect) {
  4667. var wrapper = this,
  4668. clipMembers,
  4669. cssRet;
  4670. if (clipRect) {
  4671. clipMembers = clipRect.members;
  4672. erase(clipMembers, wrapper); // Ensure unique list of elements (#1258)
  4673. clipMembers.push(wrapper);
  4674. wrapper.destroyClip = function () {
  4675. erase(clipMembers, wrapper);
  4676. };
  4677. cssRet = clipRect.getCSS(wrapper);
  4678. } else {
  4679. if (wrapper.destroyClip) {
  4680. wrapper.destroyClip();
  4681. }
  4682. cssRet = { clip: docMode8 ? 'inherit' : 'rect(auto)' }; // #1214
  4683. }
  4684. return wrapper.css(cssRet);
  4685. },
  4686. /**
  4687. * Set styles for the element
  4688. * @param {Object} styles
  4689. */
  4690. css: SVGElement.prototype.htmlCss,
  4691. /**
  4692. * Removes a child either by removeChild or move to garbageBin.
  4693. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not.
  4694. */
  4695. safeRemoveChild: function (element) {
  4696. // discardElement will detach the node from its parent before attaching it
  4697. // to the garbage bin. Therefore it is important that the node is attached and have parent.
  4698. if (element.parentNode) {
  4699. discardElement(element);
  4700. }
  4701. },
  4702. /**
  4703. * Extend element.destroy by removing it from the clip members array
  4704. */
  4705. destroy: function () {
  4706. if (this.destroyClip) {
  4707. this.destroyClip();
  4708. }
  4709. return SVGElement.prototype.destroy.apply(this);
  4710. },
  4711. /**
  4712. * Add an event listener. VML override for normalizing event parameters.
  4713. * @param {String} eventType
  4714. * @param {Function} handler
  4715. */
  4716. on: function (eventType, handler) {
  4717. // simplest possible event model for internal use
  4718. this.element['on' + eventType] = function () {
  4719. var evt = win.event;
  4720. evt.target = evt.srcElement;
  4721. handler(evt);
  4722. };
  4723. return this;
  4724. },
  4725. /**
  4726. * In stacked columns, cut off the shadows so that they don't overlap
  4727. */
  4728. cutOffPath: function (path, length) {
  4729. var len;
  4730. path = path.split(/[ ,]/);
  4731. len = path.length;
  4732. if (len === 9 || len === 11) {
  4733. path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length;
  4734. }
  4735. return path.join(' ');
  4736. },
  4737. /**
  4738. * Apply a drop shadow by copying elements and giving them different strokes
  4739. * @param {Boolean|Object} shadowOptions
  4740. */
  4741. shadow: function (shadowOptions, group, cutOff) {
  4742. var shadows = [],
  4743. i,
  4744. element = this.element,
  4745. renderer = this.renderer,
  4746. shadow,
  4747. elemStyle = element.style,
  4748. markup,
  4749. path = element.path,
  4750. strokeWidth,
  4751. modifiedPath,
  4752. shadowWidth,
  4753. shadowElementOpacity;
  4754. // some times empty paths are not strings
  4755. if (path && typeof path.value !== 'string') {
  4756. path = 'x';
  4757. }
  4758. modifiedPath = path;
  4759. if (shadowOptions) {
  4760. shadowWidth = pick(shadowOptions.width, 3);
  4761. shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth;
  4762. for (i = 1; i <= 3; i++) {
  4763. strokeWidth = (shadowWidth * 2) + 1 - (2 * i);
  4764. // Cut off shadows for stacked column items
  4765. if (cutOff) {
  4766. modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5);
  4767. }
  4768. markup = ['<shape isShadow="true" strokeweight="', strokeWidth,
  4769. '" filled="false" path="', modifiedPath,
  4770. '" coordsize="10 10" style="', element.style.cssText, '" />'];
  4771. shadow = createElement(renderer.prepVML(markup),
  4772. null, {
  4773. left: pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1),
  4774. top: pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1)
  4775. }
  4776. );
  4777. if (cutOff) {
  4778. shadow.cutOff = strokeWidth + 1;
  4779. }
  4780. // apply the opacity
  4781. markup = ['<stroke color="', shadowOptions.color || 'black', '" opacity="', shadowElementOpacity * i, '"/>'];
  4782. createElement(renderer.prepVML(markup), null, null, shadow);
  4783. // insert it
  4784. if (group) {
  4785. group.element.appendChild(shadow);
  4786. } else {
  4787. element.parentNode.insertBefore(shadow, element);
  4788. }
  4789. // record it
  4790. shadows.push(shadow);
  4791. }
  4792. this.shadows = shadows;
  4793. }
  4794. return this;
  4795. },
  4796. updateShadows: noop, // Used in SVG only
  4797. setAttr: function (key, value) {
  4798. if (docMode8) { // IE8 setAttribute bug
  4799. this.element[key] = value;
  4800. } else {
  4801. this.element.setAttribute(key, value);
  4802. }
  4803. },
  4804. classSetter: function (value) {
  4805. // IE8 Standards mode has problems retrieving the className unless set like this
  4806. this.element.className = value;
  4807. },
  4808. dashstyleSetter: function (value, key, element) {
  4809. var strokeElem = element.getElementsByTagName('stroke')[0] ||
  4810. createElement(this.renderer.prepVML(['<stroke/>']), null, null, element);
  4811. strokeElem[key] = value || 'solid';
  4812. this[key] = value; /* because changing stroke-width will change the dash length
  4813. and cause an epileptic effect */
  4814. },
  4815. dSetter: function (value, key, element) {
  4816. var i,
  4817. shadows = this.shadows;
  4818. value = value || [];
  4819. this.d = value.join && value.join(' '); // used in getter for animation
  4820. element.path = value = this.pathToVML(value);
  4821. // update shadows
  4822. if (shadows) {
  4823. i = shadows.length;
  4824. while (i--) {
  4825. shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value;
  4826. }
  4827. }
  4828. this.setAttr(key, value);
  4829. },
  4830. fillSetter: function (value, key, element) {
  4831. var nodeName = element.nodeName;
  4832. if (nodeName === 'SPAN') { // text color
  4833. element.style.color = value;
  4834. } else if (nodeName !== 'IMG') { // #1336
  4835. element.filled = value !== NONE;
  4836. this.setAttr('fillcolor', this.renderer.color(value, element, key, this));
  4837. }
  4838. },
  4839. 'fill-opacitySetter': function (value, key, element) {
  4840. createElement(
  4841. this.renderer.prepVML(['<', key.split('-')[0], ' opacity="', value, '"/>']),
  4842. null,
  4843. null,
  4844. element
  4845. );
  4846. },
  4847. opacitySetter: noop, // Don't bother - animation is too slow and filters introduce artifacts
  4848. rotationSetter: function (value, key, element) {
  4849. var style = element.style;
  4850. this[key] = style[key] = value; // style is for #1873
  4851. // Correction for the 1x1 size of the shape container. Used in gauge needles.
  4852. style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX;
  4853. style.top = mathRound(mathCos(value * deg2rad)) + PX;
  4854. },
  4855. strokeSetter: function (value, key, element) {
  4856. this.setAttr('strokecolor', this.renderer.color(value, element, key, this));
  4857. },
  4858. 'stroke-widthSetter': function (value, key, element) {
  4859. element.stroked = !!value; // VML "stroked" attribute
  4860. this[key] = value; // used in getter, issue #113
  4861. if (isNumber(value)) {
  4862. value += PX;
  4863. }
  4864. this.setAttr('strokeweight', value);
  4865. },
  4866. titleSetter: function (value, key) {
  4867. this.setAttr(key, value);
  4868. },
  4869. visibilitySetter: function (value, key, element) {
  4870. // Handle inherited visibility
  4871. if (value === 'inherit') {
  4872. value = VISIBLE;
  4873. }
  4874. // Let the shadow follow the main element
  4875. if (this.shadows) {
  4876. each(this.shadows, function (shadow) {
  4877. shadow.style[key] = value;
  4878. });
  4879. }
  4880. // Instead of toggling the visibility CSS property, move the div out of the viewport.
  4881. // This works around #61 and #586
  4882. if (element.nodeName === 'DIV') {
  4883. value = value === HIDDEN ? '-999em' : 0;
  4884. // In order to redraw, IE7 needs the div to be visible when tucked away
  4885. // outside the viewport. So the visibility is actually opposite of
  4886. // the expected value. This applies to the tooltip only.
  4887. if (!docMode8) {
  4888. element.style[key] = value ? VISIBLE : HIDDEN;
  4889. }
  4890. key = 'top';
  4891. }
  4892. element.style[key] = value;
  4893. },
  4894. displaySetter: function (value, key, element) {
  4895. element.style[key] = value;
  4896. },
  4897. xSetter: function (value, key, element) {
  4898. this[key] = value; // used in getter
  4899. if (key === 'x') {
  4900. key = 'left';
  4901. } else if (key === 'y') {
  4902. key = 'top';
  4903. }/* else {
  4904. value = mathMax(0, value); // don't set width or height below zero (#311)
  4905. }*/
  4906. // clipping rectangle special
  4907. if (this.updateClipping) {
  4908. this[key] = value; // the key is now 'left' or 'top' for 'x' and 'y'
  4909. this.updateClipping();
  4910. } else {
  4911. // normal
  4912. element.style[key] = value;
  4913. }
  4914. },
  4915. zIndexSetter: function (value, key, element) {
  4916. element.style[key] = value;
  4917. }
  4918. };
  4919. VMLElement['stroke-opacitySetter'] = VMLElement['fill-opacitySetter'];
  4920. Highcharts.VMLElement = VMLElement = extendClass(SVGElement, VMLElement);
  4921. // Some shared setters
  4922. VMLElement.prototype.ySetter =
  4923. VMLElement.prototype.widthSetter =
  4924. VMLElement.prototype.heightSetter =
  4925. VMLElement.prototype.xSetter;
  4926. /**
  4927. * The VML renderer
  4928. */
  4929. var VMLRendererExtension = { // inherit SVGRenderer
  4930. Element: VMLElement,
  4931. isIE8: userAgent.indexOf('MSIE 8.0') > -1,
  4932. /**
  4933. * Initialize the VMLRenderer
  4934. * @param {Object} container
  4935. * @param {Number} width
  4936. * @param {Number} height
  4937. */
  4938. init: function (container, width, height, style) {
  4939. var renderer = this,
  4940. boxWrapper,
  4941. box,
  4942. css;
  4943. renderer.alignedObjects = [];
  4944. boxWrapper = renderer.createElement(DIV)
  4945. .css(extend(this.getStyle(style), { position: 'relative' }));
  4946. box = boxWrapper.element;
  4947. container.appendChild(boxWrapper.element);
  4948. // generate the containing box
  4949. renderer.isVML = true;
  4950. renderer.box = box;
  4951. renderer.boxWrapper = boxWrapper;
  4952. renderer.gradients = {};
  4953. renderer.cache = {}; // Cache for numerical bounding boxes
  4954. renderer.cacheKeys = [];
  4955. renderer.imgCount = 0;
  4956. renderer.setSize(width, height, false);
  4957. // The only way to make IE6 and IE7 print is to use a global namespace. However,
  4958. // with IE8 the only way to make the dynamic shapes visible in screen and print mode
  4959. // seems to be to add the xmlns attribute and the behaviour style inline.
  4960. if (!doc.namespaces.hcv) {
  4961. doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml');
  4962. // Setup default CSS (#2153, #2368, #2384)
  4963. css = 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' +
  4964. '{ behavior:url(#default#VML); display: inline-block; } ';
  4965. try {
  4966. doc.createStyleSheet().cssText = css;
  4967. } catch (e) {
  4968. doc.styleSheets[0].cssText += css;
  4969. }
  4970. }
  4971. },
  4972. /**
  4973. * Detect whether the renderer is hidden. This happens when one of the parent elements
  4974. * has display: none
  4975. */
  4976. isHidden: function () {
  4977. return !this.box.offsetWidth;
  4978. },
  4979. /**
  4980. * Define a clipping rectangle. In VML it is accomplished by storing the values
  4981. * for setting the CSS style to all associated members.
  4982. *
  4983. * @param {Number} x
  4984. * @param {Number} y
  4985. * @param {Number} width
  4986. * @param {Number} height
  4987. */
  4988. clipRect: function (x, y, width, height) {
  4989. // create a dummy element
  4990. var clipRect = this.createElement(),
  4991. isObj = isObject(x);
  4992. // mimic a rectangle with its style object for automatic updating in attr
  4993. return extend(clipRect, {
  4994. members: [],
  4995. count: 0,
  4996. left: (isObj ? x.x : x) + 1,
  4997. top: (isObj ? x.y : y) + 1,
  4998. width: (isObj ? x.width : width) - 1,
  4999. height: (isObj ? x.height : height) - 1,
  5000. getCSS: function (wrapper) {
  5001. var element = wrapper.element,
  5002. nodeName = element.nodeName,
  5003. isShape = nodeName === 'shape',
  5004. inverted = wrapper.inverted,
  5005. rect = this,
  5006. top = rect.top - (isShape ? element.offsetTop : 0),
  5007. left = rect.left,
  5008. right = left + rect.width,
  5009. bottom = top + rect.height,
  5010. ret = {
  5011. clip: 'rect(' +
  5012. mathRound(inverted ? left : top) + 'px,' +
  5013. mathRound(inverted ? bottom : right) + 'px,' +
  5014. mathRound(inverted ? right : bottom) + 'px,' +
  5015. mathRound(inverted ? top : left) + 'px)'
  5016. };
  5017. // issue 74 workaround
  5018. if (!inverted && docMode8 && nodeName === 'DIV') {
  5019. extend(ret, {
  5020. width: right + PX,
  5021. height: bottom + PX
  5022. });
  5023. }
  5024. return ret;
  5025. },
  5026. // used in attr and animation to update the clipping of all members
  5027. updateClipping: function () {
  5028. each(clipRect.members, function (member) {
  5029. if (member.element) { // Deleted series, like in stock/members/series-remove demo. Should be removed from members, but this will do.
  5030. member.css(clipRect.getCSS(member));
  5031. }
  5032. });
  5033. }
  5034. });
  5035. },
  5036. /**
  5037. * Take a color and return it if it's a string, make it a gradient if it's a
  5038. * gradient configuration object, and apply opacity.
  5039. *
  5040. * @param {Object} color The color or config object
  5041. */
  5042. color: function (color, elem, prop, wrapper) {
  5043. var renderer = this,
  5044. colorObject,
  5045. regexRgba = /^rgba/,
  5046. markup,
  5047. fillType,
  5048. ret = NONE;
  5049. // Check for linear or radial gradient
  5050. if (color && color.linearGradient) {
  5051. fillType = 'gradient';
  5052. } else if (color && color.radialGradient) {
  5053. fillType = 'pattern';
  5054. }
  5055. if (fillType) {
  5056. var stopColor,
  5057. stopOpacity,
  5058. gradient = color.linearGradient || color.radialGradient,
  5059. x1,
  5060. y1,
  5061. x2,
  5062. y2,
  5063. opacity1,
  5064. opacity2,
  5065. color1,
  5066. color2,
  5067. fillAttr = '',
  5068. stops = color.stops,
  5069. firstStop,
  5070. lastStop,
  5071. colors = [],
  5072. addFillNode = function () {
  5073. // Add the fill subnode. When colors attribute is used, the meanings of opacity and o:opacity2
  5074. // are reversed.
  5075. markup = ['<fill colors="' + colors.join(',') + '" opacity="', opacity2, '" o:opacity2="', opacity1,
  5076. '" type="', fillType, '" ', fillAttr, 'focus="100%" method="any" />'];
  5077. createElement(renderer.prepVML(markup), null, null, elem);
  5078. };
  5079. // Extend from 0 to 1
  5080. firstStop = stops[0];
  5081. lastStop = stops[stops.length - 1];
  5082. if (firstStop[0] > 0) {
  5083. stops.unshift([
  5084. 0,
  5085. firstStop[1]
  5086. ]);
  5087. }
  5088. if (lastStop[0] < 1) {
  5089. stops.push([
  5090. 1,
  5091. lastStop[1]
  5092. ]);
  5093. }
  5094. // Compute the stops
  5095. each(stops, function (stop, i) {
  5096. if (regexRgba.test(stop[1])) {
  5097. colorObject = Color(stop[1]);
  5098. stopColor = colorObject.get('rgb');
  5099. stopOpacity = colorObject.get('a');
  5100. } else {
  5101. stopColor = stop[1];
  5102. stopOpacity = 1;
  5103. }
  5104. // Build the color attribute
  5105. colors.push((stop[0] * 100) + '% ' + stopColor);
  5106. // Only start and end opacities are allowed, so we use the first and the last
  5107. if (!i) {
  5108. opacity1 = stopOpacity;
  5109. color2 = stopColor;
  5110. } else {
  5111. opacity2 = stopOpacity;
  5112. color1 = stopColor;
  5113. }
  5114. });
  5115. // Apply the gradient to fills only.
  5116. if (prop === 'fill') {
  5117. // Handle linear gradient angle
  5118. if (fillType === 'gradient') {
  5119. x1 = gradient.x1 || gradient[0] || 0;
  5120. y1 = gradient.y1 || gradient[1] || 0;
  5121. x2 = gradient.x2 || gradient[2] || 0;
  5122. y2 = gradient.y2 || gradient[3] || 0;
  5123. fillAttr = 'angle="' + (90 - math.atan(
  5124. (y2 - y1) / // y vector
  5125. (x2 - x1) // x vector
  5126. ) * 180 / mathPI) + '"';
  5127. addFillNode();
  5128. // Radial (circular) gradient
  5129. } else {
  5130. var r = gradient.r,
  5131. sizex = r * 2,
  5132. sizey = r * 2,
  5133. cx = gradient.cx,
  5134. cy = gradient.cy,
  5135. radialReference = elem.radialReference,
  5136. bBox,
  5137. applyRadialGradient = function () {
  5138. if (radialReference) {
  5139. bBox = wrapper.getBBox();
  5140. cx += (radialReference[0] - bBox.x) / bBox.width - 0.5;
  5141. cy += (radialReference[1] - bBox.y) / bBox.height - 0.5;
  5142. sizex *= radialReference[2] / bBox.width;
  5143. sizey *= radialReference[2] / bBox.height;
  5144. }
  5145. fillAttr = 'src="' + defaultOptions.global.VMLRadialGradientURL + '" ' +
  5146. 'size="' + sizex + ',' + sizey + '" ' +
  5147. 'origin="0.5,0.5" ' +
  5148. 'position="' + cx + ',' + cy + '" ' +
  5149. 'color2="' + color2 + '" ';
  5150. addFillNode();
  5151. };
  5152. // Apply radial gradient
  5153. if (wrapper.added) {
  5154. applyRadialGradient();
  5155. } else {
  5156. // We need to know the bounding box to get the size and position right
  5157. wrapper.onAdd = applyRadialGradient;
  5158. }
  5159. // The fill element's color attribute is broken in IE8 standards mode, so we
  5160. // need to set the parent shape's fillcolor attribute instead.
  5161. ret = color1;
  5162. }
  5163. // Gradients are not supported for VML stroke, return the first color. #722.
  5164. } else {
  5165. ret = stopColor;
  5166. }
  5167. // If the color is an rgba color, split it and add a fill node
  5168. // to hold the opacity component
  5169. } else if (regexRgba.test(color) && elem.tagName !== 'IMG') {
  5170. colorObject = Color(color);
  5171. wrapper[prop + '-opacitySetter'](colorObject.get('a'), prop, elem);
  5172. ret = colorObject.get('rgb');
  5173. } else {
  5174. var propNodes = elem.getElementsByTagName(prop); // 'stroke' or 'fill' node
  5175. if (propNodes.length) {
  5176. propNodes[0].opacity = 1;
  5177. propNodes[0].type = 'solid';
  5178. }
  5179. ret = color;
  5180. }
  5181. return ret;
  5182. },
  5183. /**
  5184. * Take a VML string and prepare it for either IE8 or IE6/IE7.
  5185. * @param {Array} markup A string array of the VML markup to prepare
  5186. */
  5187. prepVML: function (markup) {
  5188. var vmlStyle = 'display:inline-block;behavior:url(#default#VML);',
  5189. isIE8 = this.isIE8;
  5190. markup = markup.join('');
  5191. if (isIE8) { // add xmlns and style inline
  5192. markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />');
  5193. if (markup.indexOf('style="') === -1) {
  5194. markup = markup.replace('/>', ' style="' + vmlStyle + '" />');
  5195. } else {
  5196. markup = markup.replace('style="', 'style="' + vmlStyle);
  5197. }
  5198. } else { // add namespace
  5199. markup = markup.replace('<', '<hcv:');
  5200. }
  5201. return markup;
  5202. },
  5203. /**
  5204. * Create rotated and aligned text
  5205. * @param {String} str
  5206. * @param {Number} x
  5207. * @param {Number} y
  5208. */
  5209. text: SVGRenderer.prototype.html,
  5210. /**
  5211. * Create and return a path element
  5212. * @param {Array} path
  5213. */
  5214. path: function (path) {
  5215. var attr = {
  5216. // subpixel precision down to 0.1 (width and height = 1px)
  5217. coordsize: '10 10'
  5218. };
  5219. if (isArray(path)) {
  5220. attr.d = path;
  5221. } else if (isObject(path)) { // attributes
  5222. extend(attr, path);
  5223. }
  5224. // create the shape
  5225. return this.createElement('shape').attr(attr);
  5226. },
  5227. /**
  5228. * Create and return a circle element. In VML circles are implemented as
  5229. * shapes, which is faster than v:oval
  5230. * @param {Number} x
  5231. * @param {Number} y
  5232. * @param {Number} r
  5233. */
  5234. circle: function (x, y, r) {
  5235. var circle = this.symbol('circle');
  5236. if (isObject(x)) {
  5237. r = x.r;
  5238. y = x.y;
  5239. x = x.x;
  5240. }
  5241. circle.isCircle = true; // Causes x and y to mean center (#1682)
  5242. circle.r = r;
  5243. return circle.attr({ x: x, y: y });
  5244. },
  5245. /**
  5246. * Create a group using an outer div and an inner v:group to allow rotating
  5247. * and flipping. A simple v:group would have problems with positioning
  5248. * child HTML elements and CSS clip.
  5249. *
  5250. * @param {String} name The name of the group
  5251. */
  5252. g: function (name) {
  5253. var wrapper,
  5254. attribs;
  5255. // set the class name
  5256. if (name) {
  5257. attribs = { 'className': PREFIX + name, 'class': PREFIX + name };
  5258. }
  5259. // the div to hold HTML and clipping
  5260. wrapper = this.createElement(DIV).attr(attribs);
  5261. return wrapper;
  5262. },
  5263. /**
  5264. * VML override to create a regular HTML image
  5265. * @param {String} src
  5266. * @param {Number} x
  5267. * @param {Number} y
  5268. * @param {Number} width
  5269. * @param {Number} height
  5270. */
  5271. image: function (src, x, y, width, height) {
  5272. var obj = this.createElement('img')
  5273. .attr({ src: src });
  5274. if (arguments.length > 1) {
  5275. obj.attr({
  5276. x: x,
  5277. y: y,
  5278. width: width,
  5279. height: height
  5280. });
  5281. }
  5282. return obj;
  5283. },
  5284. /**
  5285. * For rectangles, VML uses a shape for rect to overcome bugs and rotation problems
  5286. */
  5287. createElement: function (nodeName) {
  5288. return nodeName === 'rect' ? this.symbol(nodeName) : SVGRenderer.prototype.createElement.call(this, nodeName);
  5289. },
  5290. /**
  5291. * In the VML renderer, each child of an inverted div (group) is inverted
  5292. * @param {Object} element
  5293. * @param {Object} parentNode
  5294. */
  5295. invertChild: function (element, parentNode) {
  5296. var ren = this,
  5297. parentStyle = parentNode.style,
  5298. imgStyle = element.tagName === 'IMG' && element.style; // #1111
  5299. css(element, {
  5300. flip: 'x',
  5301. left: pInt(parentStyle.width) - (imgStyle ? pInt(imgStyle.top) : 1),
  5302. top: pInt(parentStyle.height) - (imgStyle ? pInt(imgStyle.left) : 1),
  5303. rotation: -90
  5304. });
  5305. // Recursively invert child elements, needed for nested composite shapes like box plots and error bars. #1680, #1806.
  5306. each(element.childNodes, function (child) {
  5307. ren.invertChild(child, element);
  5308. });
  5309. },
  5310. /**
  5311. * Symbol definitions that override the parent SVG renderer's symbols
  5312. *
  5313. */
  5314. symbols: {
  5315. // VML specific arc function
  5316. arc: function (x, y, w, h, options) {
  5317. var start = options.start,
  5318. end = options.end,
  5319. radius = options.r || w || h,
  5320. innerRadius = options.innerR,
  5321. cosStart = mathCos(start),
  5322. sinStart = mathSin(start),
  5323. cosEnd = mathCos(end),
  5324. sinEnd = mathSin(end),
  5325. ret;
  5326. if (end - start === 0) { // no angle, don't show it.
  5327. return ['x'];
  5328. }
  5329. ret = [
  5330. 'wa', // clockwise arc to
  5331. x - radius, // left
  5332. y - radius, // top
  5333. x + radius, // right
  5334. y + radius, // bottom
  5335. x + radius * cosStart, // start x
  5336. y + radius * sinStart, // start y
  5337. x + radius * cosEnd, // end x
  5338. y + radius * sinEnd // end y
  5339. ];
  5340. if (options.open && !innerRadius) {
  5341. ret.push(
  5342. 'e',
  5343. M,
  5344. x, // - innerRadius,
  5345. y// - innerRadius
  5346. );
  5347. }
  5348. ret.push(
  5349. 'at', // anti clockwise arc to
  5350. x - innerRadius, // left
  5351. y - innerRadius, // top
  5352. x + innerRadius, // right
  5353. y + innerRadius, // bottom
  5354. x + innerRadius * cosEnd, // start x
  5355. y + innerRadius * sinEnd, // start y
  5356. x + innerRadius * cosStart, // end x
  5357. y + innerRadius * sinStart, // end y
  5358. 'x', // finish path
  5359. 'e' // close
  5360. );
  5361. ret.isArc = true;
  5362. return ret;
  5363. },
  5364. // Add circle symbol path. This performs significantly faster than v:oval.
  5365. circle: function (x, y, w, h, wrapper) {
  5366. if (wrapper) {
  5367. w = h = 2 * wrapper.r;
  5368. }
  5369. // Center correction, #1682
  5370. if (wrapper && wrapper.isCircle) {
  5371. x -= w / 2;
  5372. y -= h / 2;
  5373. }
  5374. // Return the path
  5375. return [
  5376. 'wa', // clockwisearcto
  5377. x, // left
  5378. y, // top
  5379. x + w, // right
  5380. y + h, // bottom
  5381. x + w, // start x
  5382. y + h / 2, // start y
  5383. x + w, // end x
  5384. y + h / 2, // end y
  5385. //'x', // finish path
  5386. 'e' // close
  5387. ];
  5388. },
  5389. /**
  5390. * Add rectangle symbol path which eases rotation and omits arcsize problems
  5391. * compared to the built-in VML roundrect shape. When borders are not rounded,
  5392. * use the simpler square path, else use the callout path without the arrow.
  5393. */
  5394. rect: function (x, y, w, h, options) {
  5395. return SVGRenderer.prototype.symbols[
  5396. !defined(options) || !options.r ? 'square' : 'callout'
  5397. ].call(0, x, y, w, h, options);
  5398. }
  5399. }
  5400. };
  5401. Highcharts.VMLRenderer = VMLRenderer = function () {
  5402. this.init.apply(this, arguments);
  5403. };
  5404. VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension);
  5405. // general renderer
  5406. Renderer = VMLRenderer;
  5407. }
  5408. // This method is used with exporting in old IE, when emulating SVG (see #2314)
  5409. SVGRenderer.prototype.measureSpanWidth = function (text, styles) {
  5410. var measuringSpan = doc.createElement('span'),
  5411. offsetWidth,
  5412. textNode = doc.createTextNode(text);
  5413. measuringSpan.appendChild(textNode);
  5414. css(measuringSpan, styles);
  5415. this.box.appendChild(measuringSpan);
  5416. offsetWidth = measuringSpan.offsetWidth;
  5417. discardElement(measuringSpan); // #2463
  5418. return offsetWidth;
  5419. };
  5420. /* ****************************************************************************
  5421. * *
  5422. * END OF INTERNET EXPLORER <= 8 SPECIFIC CODE *
  5423. * *
  5424. *****************************************************************************/
  5425. /* ****************************************************************************
  5426. * *
  5427. * START OF ANDROID < 3 SPECIFIC CODE. THIS CAN BE REMOVED IF YOU'RE NOT *
  5428. * TARGETING THAT SYSTEM. *
  5429. * *
  5430. *****************************************************************************/
  5431. var CanVGRenderer,
  5432. CanVGController;
  5433. /**
  5434. * Downloads a script and executes a callback when done.
  5435. * @param {String} scriptLocation
  5436. * @param {Function} callback
  5437. */
  5438. function getScript(scriptLocation, callback) {
  5439. var head = doc.getElementsByTagName('head')[0],
  5440. script = doc.createElement('script');
  5441. script.type = 'text/javascript';
  5442. script.src = scriptLocation;
  5443. script.onload = callback;
  5444. head.appendChild(script);
  5445. }
  5446. if (useCanVG) {
  5447. /**
  5448. * The CanVGRenderer is empty from start to keep the source footprint small.
  5449. * When requested, the CanVGController downloads the rest of the source packaged
  5450. * together with the canvg library.
  5451. */
  5452. Highcharts.CanVGRenderer = CanVGRenderer = function () {
  5453. // Override the global SVG namespace to fake SVG/HTML that accepts CSS
  5454. SVG_NS = 'http://www.w3.org/1999/xhtml';
  5455. };
  5456. /**
  5457. * Start with an empty symbols object. This is needed when exporting is used (exporting.src.js will add a few symbols), but
  5458. * the implementation from SvgRenderer will not be merged in until first render.
  5459. */
  5460. CanVGRenderer.prototype.symbols = {};
  5461. /**
  5462. * Handles on demand download of canvg rendering support.
  5463. */
  5464. CanVGController = (function () {
  5465. // List of renderering calls
  5466. var deferredRenderCalls = [];
  5467. /**
  5468. * When downloaded, we are ready to draw deferred charts.
  5469. */
  5470. function drawDeferred() {
  5471. var callLength = deferredRenderCalls.length,
  5472. callIndex;
  5473. // Draw all pending render calls
  5474. for (callIndex = 0; callIndex < callLength; callIndex++) {
  5475. deferredRenderCalls[callIndex]();
  5476. }
  5477. // Clear the list
  5478. deferredRenderCalls = [];
  5479. }
  5480. return {
  5481. push: function (func, scriptLocation) {
  5482. // Only get the script once
  5483. if (deferredRenderCalls.length === 0) {
  5484. getScript(scriptLocation, drawDeferred);
  5485. }
  5486. // Register render call
  5487. deferredRenderCalls.push(func);
  5488. }
  5489. };
  5490. }());
  5491. Renderer = CanVGRenderer;
  5492. } // end CanVGRenderer
  5493. /* ****************************************************************************
  5494. * *
  5495. * END OF ANDROID < 3 SPECIFIC CODE *
  5496. * *
  5497. *****************************************************************************/
  5498. /**
  5499. * The Tick class
  5500. */
  5501. function Tick(axis, pos, type, noLabel) {
  5502. this.axis = axis;
  5503. this.pos = pos;
  5504. this.type = type || '';
  5505. this.isNew = true;
  5506. if (!type && !noLabel) {
  5507. this.addLabel();
  5508. }
  5509. }
  5510. Tick.prototype = {
  5511. /**
  5512. * Write the tick label
  5513. */
  5514. addLabel: function () {
  5515. var tick = this,
  5516. axis = tick.axis,
  5517. options = axis.options,
  5518. chart = axis.chart,
  5519. categories = axis.categories,
  5520. names = axis.names,
  5521. pos = tick.pos,
  5522. labelOptions = options.labels,
  5523. str,
  5524. tickPositions = axis.tickPositions,
  5525. isFirst = pos === tickPositions[0],
  5526. isLast = pos === tickPositions[tickPositions.length - 1],
  5527. value = categories ?
  5528. pick(categories[pos], names[pos], pos) :
  5529. pos,
  5530. label = tick.label,
  5531. tickPositionInfo = tickPositions.info,
  5532. dateTimeLabelFormat;
  5533. // Set the datetime label format. If a higher rank is set for this position, use that. If not,
  5534. // use the general format.
  5535. if (axis.isDatetimeAxis && tickPositionInfo) {
  5536. dateTimeLabelFormat = options.dateTimeLabelFormats[tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName];
  5537. }
  5538. // set properties for access in render method
  5539. tick.isFirst = isFirst;
  5540. tick.isLast = isLast;
  5541. // get the string
  5542. str = axis.labelFormatter.call({
  5543. axis: axis,
  5544. chart: chart,
  5545. isFirst: isFirst,
  5546. isLast: isLast,
  5547. dateTimeLabelFormat: dateTimeLabelFormat,
  5548. value: axis.isLog ? correctFloat(axis.lin2log(value)) : value
  5549. });
  5550. // prepare CSS
  5551. //css = width && { width: mathMax(1, mathRound(width - 2 * (labelOptions.padding || 10))) + PX };
  5552. // first call
  5553. if (!defined(label)) {
  5554. tick.label = label =
  5555. defined(str) && labelOptions.enabled ?
  5556. chart.renderer.text(
  5557. str,
  5558. 0,
  5559. 0,
  5560. labelOptions.useHTML
  5561. )
  5562. //.attr(attr)
  5563. // without position absolute, IE export sometimes is wrong
  5564. .css(merge(labelOptions.style))
  5565. .add(axis.labelGroup) :
  5566. null;
  5567. tick.labelLength = label && label.getBBox().width; // Un-rotated length
  5568. tick.rotation = 0; // Base value to detect change for new calls to getBBox
  5569. // update
  5570. } else if (label) {
  5571. label.attr({ text: str });
  5572. }
  5573. },
  5574. /**
  5575. * Get the offset height or width of the label
  5576. */
  5577. getLabelSize: function () {
  5578. return this.label ?
  5579. this.label.getBBox()[this.axis.horiz ? 'height' : 'width'] :
  5580. 0;
  5581. },
  5582. /**
  5583. * Handle the label overflow by adjusting the labels to the left and right edge, or
  5584. * hide them if they collide into the neighbour label.
  5585. */
  5586. handleOverflow: function (xy) {
  5587. var axis = this.axis,
  5588. pxPos = xy.x,
  5589. chartWidth = axis.chart.chartWidth,
  5590. spacing = axis.chart.spacing,
  5591. leftBound = pick(axis.labelLeft, mathMin(axis.pos, spacing[3])),
  5592. rightBound = pick(axis.labelRight, mathMax(axis.pos + axis.len, chartWidth - spacing[1])),
  5593. label = this.label,
  5594. rotation = this.rotation,
  5595. factor = { left: 0, center: 0.5, right: 1 }[axis.labelAlign],
  5596. labelWidth = label.getBBox().width,
  5597. slotWidth = axis.getSlotWidth(),
  5598. modifiedSlotWidth = slotWidth,
  5599. xCorrection = factor,
  5600. goRight = 1,
  5601. leftPos,
  5602. rightPos,
  5603. textWidth,
  5604. css = {};
  5605. // Check if the label overshoots the chart spacing box. If it does, move it.
  5606. // If it now overshoots the slotWidth, add ellipsis.
  5607. if (!rotation) {
  5608. leftPos = pxPos - factor * labelWidth;
  5609. rightPos = pxPos + (1 - factor) * labelWidth;
  5610. if (leftPos < leftBound) {
  5611. modifiedSlotWidth = xy.x + modifiedSlotWidth * (1 - factor) - leftBound;
  5612. } else if (rightPos > rightBound) {
  5613. modifiedSlotWidth = rightBound - xy.x + modifiedSlotWidth * factor;
  5614. goRight = -1;
  5615. }
  5616. modifiedSlotWidth = mathMin(slotWidth, modifiedSlotWidth); // #4177
  5617. if (modifiedSlotWidth < slotWidth && axis.labelAlign === 'center') {
  5618. xy.x += goRight * (slotWidth - modifiedSlotWidth - xCorrection * (slotWidth - mathMin(labelWidth, modifiedSlotWidth)));
  5619. }
  5620. // If the label width exceeds the available space, set a text width to be
  5621. // picked up below. Also, if a width has been set before, we need to set a new
  5622. // one because the reported labelWidth will be limited by the box (#3938).
  5623. if (labelWidth > modifiedSlotWidth || (axis.autoRotation && label.styles.width)) {
  5624. textWidth = modifiedSlotWidth;
  5625. }
  5626. // Add ellipsis to prevent rotated labels to be clipped against the edge of the chart
  5627. } else if (rotation < 0 && pxPos - factor * labelWidth < leftBound) {
  5628. textWidth = mathRound(pxPos / mathCos(rotation * deg2rad) - leftBound);
  5629. } else if (rotation > 0 && pxPos + factor * labelWidth > rightBound) {
  5630. textWidth = mathRound((chartWidth - pxPos) / mathCos(rotation * deg2rad));
  5631. }
  5632. if (textWidth) {
  5633. css.width = textWidth;
  5634. if (!axis.options.labels.style.textOverflow) {
  5635. css.textOverflow = 'ellipsis';
  5636. }
  5637. label.css(css);
  5638. }
  5639. },
  5640. /**
  5641. * Get the x and y position for ticks and labels
  5642. */
  5643. getPosition: function (horiz, pos, tickmarkOffset, old) {
  5644. var axis = this.axis,
  5645. chart = axis.chart,
  5646. cHeight = (old && chart.oldChartHeight) || chart.chartHeight;
  5647. return {
  5648. x: horiz ?
  5649. axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB :
  5650. axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0),
  5651. y: horiz ?
  5652. cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) :
  5653. cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB
  5654. };
  5655. },
  5656. /**
  5657. * Get the x, y position of the tick label
  5658. */
  5659. getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) {
  5660. var axis = this.axis,
  5661. transA = axis.transA,
  5662. reversed = axis.reversed,
  5663. staggerLines = axis.staggerLines,
  5664. rotCorr = axis.tickRotCorr || { x: 0, y: 0 },
  5665. yOffset = labelOptions.y,
  5666. line;
  5667. if (!defined(yOffset)) {
  5668. if (axis.side === 0) {
  5669. yOffset = label.rotation ? -8 : -label.getBBox().height;
  5670. } else if (axis.side === 2) {
  5671. yOffset = rotCorr.y + 8;
  5672. } else {
  5673. // #3140, #3140
  5674. yOffset = mathCos(label.rotation * deg2rad) * (rotCorr.y - label.getBBox(false, 0).height / 2);
  5675. }
  5676. }
  5677. x = x + labelOptions.x + rotCorr.x - (tickmarkOffset && horiz ?
  5678. tickmarkOffset * transA * (reversed ? -1 : 1) : 0);
  5679. y = y + yOffset - (tickmarkOffset && !horiz ?
  5680. tickmarkOffset * transA * (reversed ? 1 : -1) : 0);
  5681. // Correct for staggered labels
  5682. if (staggerLines) {
  5683. line = (index / (step || 1) % staggerLines);
  5684. if (axis.opposite) {
  5685. line = staggerLines - line - 1;
  5686. }
  5687. y += line * (axis.labelOffset / staggerLines);
  5688. }
  5689. return {
  5690. x: x,
  5691. y: mathRound(y)
  5692. };
  5693. },
  5694. /**
  5695. * Extendible method to return the path of the marker
  5696. */
  5697. getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) {
  5698. return renderer.crispLine([
  5699. M,
  5700. x,
  5701. y,
  5702. L,
  5703. x + (horiz ? 0 : -tickLength),
  5704. y + (horiz ? tickLength : 0)
  5705. ], tickWidth);
  5706. },
  5707. /**
  5708. * Put everything in place
  5709. *
  5710. * @param index {Number}
  5711. * @param old {Boolean} Use old coordinates to prepare an animation into new position
  5712. */
  5713. render: function (index, old, opacity) {
  5714. var tick = this,
  5715. axis = tick.axis,
  5716. options = axis.options,
  5717. chart = axis.chart,
  5718. renderer = chart.renderer,
  5719. horiz = axis.horiz,
  5720. type = tick.type,
  5721. label = tick.label,
  5722. pos = tick.pos,
  5723. labelOptions = options.labels,
  5724. gridLine = tick.gridLine,
  5725. gridPrefix = type ? type + 'Grid' : 'grid',
  5726. tickPrefix = type ? type + 'Tick' : 'tick',
  5727. gridLineWidth = options[gridPrefix + 'LineWidth'],
  5728. gridLineColor = options[gridPrefix + 'LineColor'],
  5729. dashStyle = options[gridPrefix + 'LineDashStyle'],
  5730. tickSize = axis.tickSize(tickPrefix),
  5731. tickColor = options[tickPrefix + 'Color'],
  5732. gridLinePath,
  5733. mark = tick.mark,
  5734. markPath,
  5735. step = /*axis.labelStep || */labelOptions.step,
  5736. attribs,
  5737. show = true,
  5738. tickmarkOffset = axis.tickmarkOffset,
  5739. xy = tick.getPosition(horiz, pos, tickmarkOffset, old),
  5740. x = xy.x,
  5741. y = xy.y,
  5742. reverseCrisp = ((horiz && x === axis.pos + axis.len) || (!horiz && y === axis.pos)) ? -1 : 1; // #1480, #1687
  5743. opacity = pick(opacity, 1);
  5744. this.isActive = true;
  5745. // create the grid line
  5746. if (gridLineWidth) {
  5747. gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLineWidth * reverseCrisp, old, true);
  5748. if (gridLine === UNDEFINED) {
  5749. attribs = {
  5750. stroke: gridLineColor,
  5751. 'stroke-width': gridLineWidth
  5752. };
  5753. if (dashStyle) {
  5754. attribs.dashstyle = dashStyle;
  5755. }
  5756. if (!type) {
  5757. attribs.zIndex = 1;
  5758. }
  5759. if (old) {
  5760. attribs.opacity = 0;
  5761. }
  5762. tick.gridLine = gridLine =
  5763. gridLineWidth ?
  5764. renderer.path(gridLinePath)
  5765. .attr(attribs).add(axis.gridGroup) :
  5766. null;
  5767. }
  5768. // If the parameter 'old' is set, the current call will be followed
  5769. // by another call, therefore do not do any animations this time
  5770. if (!old && gridLine && gridLinePath) {
  5771. gridLine[tick.isNew ? 'attr' : 'animate']({
  5772. d: gridLinePath,
  5773. opacity: opacity
  5774. });
  5775. }
  5776. }
  5777. // create the tick mark
  5778. if (tickSize) {
  5779. if (axis.opposite) {
  5780. tickSize[0] = -tickSize[0];
  5781. }
  5782. markPath = tick.getMarkPath(x, y, tickSize[0], tickSize[1] * reverseCrisp, horiz, renderer);
  5783. if (mark) { // updating
  5784. mark.animate({
  5785. d: markPath,
  5786. opacity: opacity
  5787. });
  5788. } else { // first time
  5789. tick.mark = renderer.path(
  5790. markPath
  5791. ).attr({
  5792. stroke: tickColor,
  5793. 'stroke-width': tickSize[1],
  5794. opacity: opacity
  5795. }).add(axis.axisGroup);
  5796. }
  5797. }
  5798. // the label is created on init - now move it into place
  5799. if (label && isNumber(x)) {
  5800. label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step);
  5801. // Apply show first and show last. If the tick is both first and last, it is
  5802. // a single centered tick, in which case we show the label anyway (#2100).
  5803. if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) ||
  5804. (tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) {
  5805. show = false;
  5806. // Handle label overflow and show or hide accordingly
  5807. } else if (horiz && !axis.isRadial && !labelOptions.step && !labelOptions.rotation && !old && opacity !== 0) {
  5808. tick.handleOverflow(xy);
  5809. }
  5810. // apply step
  5811. if (step && index % step) {
  5812. // show those indices dividable by step
  5813. show = false;
  5814. }
  5815. // Set the new position, and show or hide
  5816. if (show && isNumber(xy.y)) {
  5817. xy.opacity = opacity;
  5818. label[tick.isNew ? 'attr' : 'animate'](xy);
  5819. } else {
  5820. stop(label); // #5332
  5821. label.attr('y', -9999); // #1338
  5822. }
  5823. tick.isNew = false;
  5824. }
  5825. },
  5826. /**
  5827. * Destructor for the tick prototype
  5828. */
  5829. destroy: function () {
  5830. destroyObjectProperties(this, this.axis);
  5831. }
  5832. };
  5833. /**
  5834. * The object wrapper for plot lines and plot bands
  5835. * @param {Object} options
  5836. */
  5837. Highcharts.PlotLineOrBand = function (axis, options) {
  5838. this.axis = axis;
  5839. if (options) {
  5840. this.options = options;
  5841. this.id = options.id;
  5842. }
  5843. };
  5844. Highcharts.PlotLineOrBand.prototype = {
  5845. /**
  5846. * Render the plot line or plot band. If it is already existing,
  5847. * move it.
  5848. */
  5849. render: function () {
  5850. var plotLine = this,
  5851. axis = plotLine.axis,
  5852. horiz = axis.horiz,
  5853. options = plotLine.options,
  5854. optionsLabel = options.label,
  5855. label = plotLine.label,
  5856. width = options.width,
  5857. to = options.to,
  5858. from = options.from,
  5859. isBand = defined(from) && defined(to),
  5860. value = options.value,
  5861. dashStyle = options.dashStyle,
  5862. svgElem = plotLine.svgElem,
  5863. path = [],
  5864. addEvent,
  5865. eventType,
  5866. color = options.color,
  5867. zIndex = pick(options.zIndex, 0),
  5868. events = options.events,
  5869. attribs = {},
  5870. renderer = axis.chart.renderer,
  5871. log2lin = axis.log2lin;
  5872. // logarithmic conversion
  5873. if (axis.isLog) {
  5874. from = log2lin(from);
  5875. to = log2lin(to);
  5876. value = log2lin(value);
  5877. }
  5878. // plot line
  5879. if (width) {
  5880. path = axis.getPlotLinePath(value, width);
  5881. attribs = {
  5882. stroke: color,
  5883. 'stroke-width': width
  5884. };
  5885. if (dashStyle) {
  5886. attribs.dashstyle = dashStyle;
  5887. }
  5888. } else if (isBand) { // plot band
  5889. path = axis.getPlotBandPath(from, to, options);
  5890. if (color) {
  5891. attribs.fill = color;
  5892. }
  5893. if (options.borderWidth) {
  5894. attribs.stroke = options.borderColor;
  5895. attribs['stroke-width'] = options.borderWidth;
  5896. }
  5897. } else {
  5898. return;
  5899. }
  5900. // zIndex
  5901. attribs.zIndex = zIndex;
  5902. // common for lines and bands
  5903. if (svgElem) {
  5904. if (path) {
  5905. svgElem.show();
  5906. svgElem.animate({ d: path });
  5907. } else {
  5908. svgElem.hide();
  5909. if (label) {
  5910. plotLine.label = label = label.destroy();
  5911. }
  5912. }
  5913. } else if (path && path.length) {
  5914. plotLine.svgElem = svgElem = renderer.path(path)
  5915. .attr(attribs).add();
  5916. // events
  5917. if (events) {
  5918. addEvent = function (eventType) {
  5919. svgElem.on(eventType, function (e) {
  5920. events[eventType].apply(plotLine, [e]);
  5921. });
  5922. };
  5923. for (eventType in events) {
  5924. addEvent(eventType);
  5925. }
  5926. }
  5927. }
  5928. // the plot band/line label
  5929. if (optionsLabel && defined(optionsLabel.text) && path && path.length &&
  5930. axis.width > 0 && axis.height > 0 && !path.flat) {
  5931. // apply defaults
  5932. optionsLabel = merge({
  5933. align: horiz && isBand && 'center',
  5934. x: horiz ? !isBand && 4 : 10,
  5935. verticalAlign: !horiz && isBand && 'middle',
  5936. y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4,
  5937. rotation: horiz && !isBand && 90
  5938. }, optionsLabel);
  5939. this.renderLabel(optionsLabel, path, isBand, zIndex);
  5940. } else if (label) { // move out of sight
  5941. label.hide();
  5942. }
  5943. // chainable
  5944. return plotLine;
  5945. },
  5946. /**
  5947. * Render and align label for plot line or band.
  5948. */
  5949. renderLabel: function (optionsLabel, path, isBand, zIndex) {
  5950. var plotLine = this,
  5951. label = plotLine.label,
  5952. renderer = plotLine.axis.chart.renderer,
  5953. attribs,
  5954. xs,
  5955. ys,
  5956. x,
  5957. y;
  5958. // add the SVG element
  5959. if (!label) {
  5960. attribs = {
  5961. align: optionsLabel.textAlign || optionsLabel.align,
  5962. rotation: optionsLabel.rotation
  5963. };
  5964. attribs.zIndex = zIndex;
  5965. plotLine.label = label = renderer.text(
  5966. optionsLabel.text,
  5967. 0,
  5968. 0,
  5969. optionsLabel.useHTML
  5970. )
  5971. .attr(attribs)
  5972. .css(optionsLabel.style)
  5973. .add();
  5974. }
  5975. // get the bounding box and align the label
  5976. // #3000 changed to better handle choice between plotband or plotline
  5977. xs = [path[1], path[4], (isBand ? path[6] : path[1])];
  5978. ys = [path[2], path[5], (isBand ? path[7] : path[2])];
  5979. x = arrayMin(xs);
  5980. y = arrayMin(ys);
  5981. label.align(optionsLabel, false, {
  5982. x: x,
  5983. y: y,
  5984. width: arrayMax(xs) - x,
  5985. height: arrayMax(ys) - y
  5986. });
  5987. label.show();
  5988. },
  5989. /**
  5990. * Remove the plot line or band
  5991. */
  5992. destroy: function () {
  5993. // remove it from the lookup
  5994. erase(this.axis.plotLinesAndBands, this);
  5995. delete this.axis;
  5996. destroyObjectProperties(this);
  5997. }
  5998. };
  5999. /**
  6000. * Object with members for extending the Axis prototype
  6001. */
  6002. AxisPlotLineOrBandExtension = {
  6003. /**
  6004. * Create the path for a plot band
  6005. */
  6006. getPlotBandPath: function (from, to) {
  6007. var toPath = this.getPlotLinePath(to, null, null, true),
  6008. path = this.getPlotLinePath(from, null, null, true);
  6009. if (path && toPath) {
  6010. // Flat paths don't need labels (#3836)
  6011. path.flat = path.toString() === toPath.toString();
  6012. path.push(
  6013. toPath[4],
  6014. toPath[5],
  6015. toPath[1],
  6016. toPath[2]
  6017. );
  6018. } else { // outside the axis area
  6019. path = null;
  6020. }
  6021. return path;
  6022. },
  6023. addPlotBand: function (options) {
  6024. return this.addPlotBandOrLine(options, 'plotBands');
  6025. },
  6026. addPlotLine: function (options) {
  6027. return this.addPlotBandOrLine(options, 'plotLines');
  6028. },
  6029. /**
  6030. * Add a plot band or plot line after render time
  6031. *
  6032. * @param options {Object} The plotBand or plotLine configuration object
  6033. */
  6034. addPlotBandOrLine: function (options, coll) {
  6035. var obj = new Highcharts.PlotLineOrBand(this, options).render(),
  6036. userOptions = this.userOptions;
  6037. if (obj) { // #2189
  6038. // Add it to the user options for exporting and Axis.update
  6039. if (coll) {
  6040. userOptions[coll] = userOptions[coll] || [];
  6041. userOptions[coll].push(options);
  6042. }
  6043. this.plotLinesAndBands.push(obj);
  6044. }
  6045. return obj;
  6046. },
  6047. /**
  6048. * Remove a plot band or plot line from the chart by id
  6049. * @param {Object} id
  6050. */
  6051. removePlotBandOrLine: function (id) {
  6052. var plotLinesAndBands = this.plotLinesAndBands,
  6053. options = this.options,
  6054. userOptions = this.userOptions,
  6055. i = plotLinesAndBands.length;
  6056. while (i--) {
  6057. if (plotLinesAndBands[i].id === id) {
  6058. plotLinesAndBands[i].destroy();
  6059. }
  6060. }
  6061. each([options.plotLines || [], userOptions.plotLines || [], options.plotBands || [], userOptions.plotBands || []], function (arr) {
  6062. i = arr.length;
  6063. while (i--) {
  6064. if (arr[i].id === id) {
  6065. erase(arr, arr[i]);
  6066. }
  6067. }
  6068. });
  6069. }
  6070. };
  6071. /**
  6072. * Create a new axis object
  6073. * @param {Object} chart
  6074. * @param {Object} options
  6075. */
  6076. var Axis = Highcharts.Axis = function () {
  6077. this.init.apply(this, arguments);
  6078. };
  6079. Axis.prototype = {
  6080. /**
  6081. * Default options for the X axis - the Y axis has extended defaults
  6082. */
  6083. defaultOptions: {
  6084. // allowDecimals: null,
  6085. // alternateGridColor: null,
  6086. // categories: [],
  6087. dateTimeLabelFormats: {
  6088. millisecond: '%H:%M:%S.%L',
  6089. second: '%H:%M:%S',
  6090. minute: '%H:%M',
  6091. hour: '%H:%M',
  6092. day: '%e. %b',
  6093. week: '%e. %b',
  6094. month: '%b \'%y',
  6095. year: '%Y'
  6096. },
  6097. endOnTick: false,
  6098. gridLineColor: '#D8D8D8',
  6099. // gridLineDashStyle: 'solid',
  6100. // gridLineWidth: 0,
  6101. // reversed: false,
  6102. labels: {
  6103. enabled: true,
  6104. // rotation: 0,
  6105. // align: 'center',
  6106. // step: null,
  6107. style: {
  6108. color: '#606060',
  6109. cursor: 'default',
  6110. fontSize: '11px'
  6111. },
  6112. x: 0
  6113. //y: undefined
  6114. /*formatter: function () {
  6115. return this.value;
  6116. },*/
  6117. },
  6118. lineColor: '#C0D0E0',
  6119. lineWidth: 1,
  6120. //linkedTo: null,
  6121. //max: undefined,
  6122. //min: undefined,
  6123. minPadding: 0.01,
  6124. maxPadding: 0.01,
  6125. //minRange: null,
  6126. minorGridLineColor: '#E0E0E0',
  6127. // minorGridLineDashStyle: null,
  6128. minorGridLineWidth: 1,
  6129. minorTickColor: '#A0A0A0',
  6130. //minorTickInterval: null,
  6131. minorTickLength: 2,
  6132. minorTickPosition: 'outside', // inside or outside
  6133. //minorTickWidth: 0,
  6134. //opposite: false,
  6135. //offset: 0,
  6136. //plotBands: [{
  6137. // events: {},
  6138. // zIndex: 1,
  6139. // labels: { align, x, verticalAlign, y, style, rotation, textAlign }
  6140. //}],
  6141. //plotLines: [{
  6142. // events: {}
  6143. // dashStyle: {}
  6144. // zIndex:
  6145. // labels: { align, x, verticalAlign, y, style, rotation, textAlign }
  6146. //}],
  6147. //reversed: false,
  6148. // showFirstLabel: true,
  6149. // showLastLabel: true,
  6150. startOfWeek: 1,
  6151. startOnTick: false,
  6152. tickColor: '#C0D0E0',
  6153. //tickInterval: null,
  6154. tickLength: 10,
  6155. tickmarkPlacement: 'between', // on or between
  6156. tickPixelInterval: 100,
  6157. tickPosition: 'outside',
  6158. //tickWidth: 1,
  6159. title: {
  6160. //text: null,
  6161. align: 'middle', // low, middle or high
  6162. //margin: 0 for horizontal, 10 for vertical axes,
  6163. //rotation: 0,
  6164. //side: 'outside',
  6165. style: {
  6166. color: '#707070'
  6167. }
  6168. //x: 0,
  6169. //y: 0
  6170. },
  6171. type: 'linear' // linear, logarithmic or datetime
  6172. //visible: true
  6173. },
  6174. /**
  6175. * This options set extends the defaultOptions for Y axes
  6176. */
  6177. defaultYAxisOptions: {
  6178. endOnTick: true,
  6179. gridLineWidth: 1,
  6180. tickPixelInterval: 72,
  6181. showLastLabel: true,
  6182. labels: {
  6183. x: -8
  6184. },
  6185. lineWidth: 0,
  6186. maxPadding: 0.05,
  6187. minPadding: 0.05,
  6188. startOnTick: true,
  6189. //tickWidth: 0,
  6190. title: {
  6191. rotation: 270,
  6192. text: 'Values'
  6193. },
  6194. stackLabels: {
  6195. enabled: false,
  6196. //align: dynamic,
  6197. //y: dynamic,
  6198. //x: dynamic,
  6199. //verticalAlign: dynamic,
  6200. //textAlign: dynamic,
  6201. //rotation: 0,
  6202. formatter: function () {
  6203. return Highcharts.numberFormat(this.total, -1);
  6204. },
  6205. style: merge(defaultPlotOptions.line.dataLabels.style, { color: '#000000' })
  6206. }
  6207. },
  6208. /**
  6209. * These options extend the defaultOptions for left axes
  6210. */
  6211. defaultLeftAxisOptions: {
  6212. labels: {
  6213. x: -15
  6214. },
  6215. title: {
  6216. rotation: 270
  6217. }
  6218. },
  6219. /**
  6220. * These options extend the defaultOptions for right axes
  6221. */
  6222. defaultRightAxisOptions: {
  6223. labels: {
  6224. x: 15
  6225. },
  6226. title: {
  6227. rotation: 90
  6228. }
  6229. },
  6230. /**
  6231. * These options extend the defaultOptions for bottom axes
  6232. */
  6233. defaultBottomAxisOptions: {
  6234. labels: {
  6235. autoRotation: [-45],
  6236. x: 0
  6237. // overflow: undefined,
  6238. // staggerLines: null
  6239. },
  6240. title: {
  6241. rotation: 0
  6242. }
  6243. },
  6244. /**
  6245. * These options extend the defaultOptions for top axes
  6246. */
  6247. defaultTopAxisOptions: {
  6248. labels: {
  6249. autoRotation: [-45],
  6250. x: 0
  6251. // overflow: undefined
  6252. // staggerLines: null
  6253. },
  6254. title: {
  6255. rotation: 0
  6256. }
  6257. },
  6258. /**
  6259. * Initialize the axis
  6260. */
  6261. init: function (chart, userOptions) {
  6262. var isXAxis = userOptions.isX,
  6263. axis = this;
  6264. axis.chart = chart;
  6265. // Flag, is the axis horizontal
  6266. axis.horiz = chart.inverted ? !isXAxis : isXAxis;
  6267. // Flag, isXAxis
  6268. axis.isXAxis = isXAxis;
  6269. axis.coll = axis.coll || (isXAxis ? 'xAxis' : 'yAxis');
  6270. axis.opposite = userOptions.opposite; // needed in setOptions
  6271. axis.side = userOptions.side || (axis.horiz ?
  6272. (axis.opposite ? 0 : 2) : // top : bottom
  6273. (axis.opposite ? 1 : 3)); // right : left
  6274. axis.setOptions(userOptions);
  6275. var options = this.options,
  6276. type = options.type,
  6277. isDatetimeAxis = type === 'datetime';
  6278. axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format
  6279. // Flag, stagger lines or not
  6280. axis.userOptions = userOptions;
  6281. //axis.axisTitleMargin = UNDEFINED,// = options.title.margin,
  6282. axis.minPixelPadding = 0;
  6283. axis.reversed = options.reversed;
  6284. axis.visible = options.visible !== false;
  6285. axis.zoomEnabled = options.zoomEnabled !== false;
  6286. // Initial categories
  6287. axis.hasNames = type === 'category' || options.categories === true;
  6288. axis.categories = options.categories || axis.hasNames;
  6289. axis.names = axis.names || []; // Preserve on update (#3830)
  6290. // Elements
  6291. //axis.axisGroup = UNDEFINED;
  6292. //axis.gridGroup = UNDEFINED;
  6293. //axis.axisTitle = UNDEFINED;
  6294. //axis.axisLine = UNDEFINED;
  6295. // Shorthand types
  6296. axis.isLog = type === 'logarithmic';
  6297. axis.isDatetimeAxis = isDatetimeAxis;
  6298. // Flag, if axis is linked to another axis
  6299. axis.isLinked = defined(options.linkedTo);
  6300. // Linked axis.
  6301. //axis.linkedParent = UNDEFINED;
  6302. // Tick positions
  6303. //axis.tickPositions = UNDEFINED; // array containing predefined positions
  6304. // Tick intervals
  6305. //axis.tickInterval = UNDEFINED;
  6306. //axis.minorTickInterval = UNDEFINED;
  6307. // Major ticks
  6308. axis.ticks = {};
  6309. axis.labelEdge = [];
  6310. // Minor ticks
  6311. axis.minorTicks = {};
  6312. // List of plotLines/Bands
  6313. axis.plotLinesAndBands = [];
  6314. // Alternate bands
  6315. axis.alternateBands = {};
  6316. // Axis metrics
  6317. //axis.left = UNDEFINED;
  6318. //axis.top = UNDEFINED;
  6319. //axis.width = UNDEFINED;
  6320. //axis.height = UNDEFINED;
  6321. //axis.bottom = UNDEFINED;
  6322. //axis.right = UNDEFINED;
  6323. //axis.transA = UNDEFINED;
  6324. //axis.transB = UNDEFINED;
  6325. //axis.oldTransA = UNDEFINED;
  6326. axis.len = 0;
  6327. //axis.oldMin = UNDEFINED;
  6328. //axis.oldMax = UNDEFINED;
  6329. //axis.oldUserMin = UNDEFINED;
  6330. //axis.oldUserMax = UNDEFINED;
  6331. //axis.oldAxisLength = UNDEFINED;
  6332. axis.minRange = axis.userMinRange = options.minRange || options.maxZoom;
  6333. axis.range = options.range;
  6334. axis.offset = options.offset || 0;
  6335. // Dictionary for stacks
  6336. axis.stacks = {};
  6337. axis.oldStacks = {};
  6338. axis.stacksTouched = 0;
  6339. // Min and max in the data
  6340. //axis.dataMin = UNDEFINED,
  6341. //axis.dataMax = UNDEFINED,
  6342. // The axis range
  6343. axis.max = null;
  6344. axis.min = null;
  6345. // User set min and max
  6346. //axis.userMin = UNDEFINED,
  6347. //axis.userMax = UNDEFINED,
  6348. // Crosshair options
  6349. axis.crosshair = pick(options.crosshair, splat(chart.options.tooltip.crosshairs)[isXAxis ? 0 : 1], false);
  6350. // Run Axis
  6351. var eventType,
  6352. events = axis.options.events;
  6353. // Register
  6354. if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update()
  6355. if (isXAxis) { // #2713
  6356. chart.axes.splice(chart.xAxis.length, 0, axis);
  6357. } else {
  6358. chart.axes.push(axis);
  6359. }
  6360. chart[axis.coll].push(axis);
  6361. }
  6362. axis.series = axis.series || []; // populated by Series
  6363. // inverted charts have reversed xAxes as default
  6364. if (chart.inverted && isXAxis && axis.reversed === UNDEFINED) {
  6365. axis.reversed = true;
  6366. }
  6367. axis.removePlotBand = axis.removePlotBandOrLine;
  6368. axis.removePlotLine = axis.removePlotBandOrLine;
  6369. // register event listeners
  6370. for (eventType in events) {
  6371. addEvent(axis, eventType, events[eventType]);
  6372. }
  6373. // extend logarithmic axis
  6374. if (axis.isLog) {
  6375. axis.val2lin = axis.log2lin;
  6376. axis.lin2val = axis.lin2log;
  6377. }
  6378. },
  6379. /**
  6380. * Merge and set options
  6381. */
  6382. setOptions: function (userOptions) {
  6383. this.options = merge(
  6384. this.defaultOptions,
  6385. this.coll === 'yAxis' && this.defaultYAxisOptions,
  6386. [this.defaultTopAxisOptions, this.defaultRightAxisOptions,
  6387. this.defaultBottomAxisOptions, this.defaultLeftAxisOptions][this.side],
  6388. merge(
  6389. defaultOptions[this.coll], // if set in setOptions (#1053)
  6390. userOptions
  6391. )
  6392. );
  6393. },
  6394. /**
  6395. * The default label formatter. The context is a special config object for the label.
  6396. */
  6397. defaultLabelFormatter: function () {
  6398. var axis = this.axis,
  6399. value = this.value,
  6400. categories = axis.categories,
  6401. dateTimeLabelFormat = this.dateTimeLabelFormat,
  6402. numericSymbols = defaultOptions.lang.numericSymbols,
  6403. i = numericSymbols && numericSymbols.length,
  6404. multi,
  6405. ret,
  6406. formatOption = axis.options.labels.format,
  6407. // make sure the same symbol is added for all labels on a linear axis
  6408. numericSymbolDetector = axis.isLog ? value : axis.tickInterval;
  6409. if (formatOption) {
  6410. ret = format(formatOption, this);
  6411. } else if (categories) {
  6412. ret = value;
  6413. } else if (dateTimeLabelFormat) { // datetime axis
  6414. ret = dateFormat(dateTimeLabelFormat, value);
  6415. } else if (i && numericSymbolDetector >= 1000) {
  6416. // Decide whether we should add a numeric symbol like k (thousands) or M (millions).
  6417. // If we are to enable this in tooltip or other places as well, we can move this
  6418. // logic to the numberFormatter and enable it by a parameter.
  6419. while (i-- && ret === UNDEFINED) {
  6420. multi = Math.pow(1000, i + 1);
  6421. if (numericSymbolDetector >= multi && (value * 10) % multi === 0 && numericSymbols[i] !== null && value !== 0) { // #5480
  6422. ret = Highcharts.numberFormat(value / multi, -1) + numericSymbols[i];
  6423. }
  6424. }
  6425. }
  6426. if (ret === UNDEFINED) {
  6427. if (mathAbs(value) >= 10000) { // add thousands separators
  6428. ret = Highcharts.numberFormat(value, -1);
  6429. } else { // small numbers
  6430. ret = Highcharts.numberFormat(value, -1, UNDEFINED, ''); // #2466
  6431. }
  6432. }
  6433. return ret;
  6434. },
  6435. /**
  6436. * Get the minimum and maximum for the series of each axis
  6437. */
  6438. getSeriesExtremes: function () {
  6439. var axis = this,
  6440. chart = axis.chart;
  6441. axis.hasVisibleSeries = false;
  6442. // Reset properties in case we're redrawing (#3353)
  6443. axis.dataMin = axis.dataMax = axis.threshold = null;
  6444. axis.softThreshold = !axis.isXAxis;
  6445. if (axis.buildStacks) {
  6446. axis.buildStacks();
  6447. }
  6448. // loop through this axis' series
  6449. each(axis.series, function (series) {
  6450. if (series.visible || !chart.options.chart.ignoreHiddenSeries) {
  6451. var seriesOptions = series.options,
  6452. xData,
  6453. threshold = seriesOptions.threshold,
  6454. seriesDataMin,
  6455. seriesDataMax;
  6456. axis.hasVisibleSeries = true;
  6457. // Validate threshold in logarithmic axes
  6458. if (axis.isLog && threshold <= 0) {
  6459. threshold = null;
  6460. }
  6461. // Get dataMin and dataMax for X axes
  6462. if (axis.isXAxis) {
  6463. xData = series.xData;
  6464. if (xData.length) {
  6465. // If xData contains values which is not numbers, then filter them out.
  6466. // To prevent performance hit, we only do this after we have already
  6467. // found seriesDataMin because in most cases all data is valid. #5234.
  6468. seriesDataMin = arrayMin(xData);
  6469. if (!isNumber(seriesDataMin) && !(seriesDataMin instanceof Date)) { // Date for #5010
  6470. xData = grep(xData, function (x) {
  6471. return isNumber(x);
  6472. });
  6473. seriesDataMin = arrayMin(xData); // Do it again with valid data
  6474. }
  6475. axis.dataMin = mathMin(pick(axis.dataMin, xData[0]), seriesDataMin);
  6476. axis.dataMax = mathMax(pick(axis.dataMax, xData[0]), arrayMax(xData));
  6477. }
  6478. // Get dataMin and dataMax for Y axes, as well as handle stacking and processed data
  6479. } else {
  6480. // Get this particular series extremes
  6481. series.getExtremes();
  6482. seriesDataMax = series.dataMax;
  6483. seriesDataMin = series.dataMin;
  6484. // Get the dataMin and dataMax so far. If percentage is used, the min and max are
  6485. // always 0 and 100. If seriesDataMin and seriesDataMax is null, then series
  6486. // doesn't have active y data, we continue with nulls
  6487. if (defined(seriesDataMin) && defined(seriesDataMax)) {
  6488. axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin);
  6489. axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax);
  6490. }
  6491. // Adjust to threshold
  6492. if (defined(threshold)) {
  6493. axis.threshold = threshold;
  6494. }
  6495. // If any series has a hard threshold, it takes precedence
  6496. if (!seriesOptions.softThreshold || axis.isLog) {
  6497. axis.softThreshold = false;
  6498. }
  6499. }
  6500. }
  6501. });
  6502. },
  6503. /**
  6504. * Translate from axis value to pixel position on the chart, or back
  6505. *
  6506. */
  6507. translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacement) {
  6508. var axis = this.linkedParent || this, // #1417
  6509. sign = 1,
  6510. cvsOffset = 0,
  6511. localA = old ? axis.oldTransA : axis.transA,
  6512. localMin = old ? axis.oldMin : axis.min,
  6513. returnValue,
  6514. minPixelPadding = axis.minPixelPadding,
  6515. doPostTranslate = (axis.isOrdinal || axis.isBroken || (axis.isLog && handleLog)) && axis.lin2val;
  6516. if (!localA) {
  6517. localA = axis.transA;
  6518. }
  6519. // In vertical axes, the canvas coordinates start from 0 at the top like in
  6520. // SVG.
  6521. if (cvsCoord) {
  6522. sign *= -1; // canvas coordinates inverts the value
  6523. cvsOffset = axis.len;
  6524. }
  6525. // Handle reversed axis
  6526. if (axis.reversed) {
  6527. sign *= -1;
  6528. cvsOffset -= sign * (axis.sector || axis.len);
  6529. }
  6530. // From pixels to value
  6531. if (backwards) { // reverse translation
  6532. val = val * sign + cvsOffset;
  6533. val -= minPixelPadding;
  6534. returnValue = val / localA + localMin; // from chart pixel to value
  6535. if (doPostTranslate) { // log and ordinal axes
  6536. returnValue = axis.lin2val(returnValue);
  6537. }
  6538. // From value to pixels
  6539. } else {
  6540. if (doPostTranslate) { // log and ordinal axes
  6541. val = axis.val2lin(val);
  6542. }
  6543. if (pointPlacement === 'between') {
  6544. pointPlacement = 0.5;
  6545. }
  6546. returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) +
  6547. (isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0);
  6548. }
  6549. return returnValue;
  6550. },
  6551. /**
  6552. * Utility method to translate an axis value to pixel position.
  6553. * @param {Number} value A value in terms of axis units
  6554. * @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart
  6555. * or just the axis/pane itself.
  6556. */
  6557. toPixels: function (value, paneCoordinates) {
  6558. return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos);
  6559. },
  6560. /*
  6561. * Utility method to translate a pixel position in to an axis value
  6562. * @param {Number} pixel The pixel value coordinate
  6563. * @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the
  6564. * axis/pane itself.
  6565. */
  6566. toValue: function (pixel, paneCoordinates) {
  6567. return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true);
  6568. },
  6569. /**
  6570. * Create the path for a plot line that goes from the given value on
  6571. * this axis, across the plot to the opposite side
  6572. * @param {Number} value
  6573. * @param {Number} lineWidth Used for calculation crisp line
  6574. * @param {Number] old Use old coordinates (for resizing and rescaling)
  6575. */
  6576. getPlotLinePath: function (value, lineWidth, old, force, translatedValue) {
  6577. var axis = this,
  6578. chart = axis.chart,
  6579. axisLeft = axis.left,
  6580. axisTop = axis.top,
  6581. x1,
  6582. y1,
  6583. x2,
  6584. y2,
  6585. cHeight = (old && chart.oldChartHeight) || chart.chartHeight,
  6586. cWidth = (old && chart.oldChartWidth) || chart.chartWidth,
  6587. skip,
  6588. transB = axis.transB,
  6589. /**
  6590. * Check if x is between a and b. If not, either move to a/b or skip,
  6591. * depending on the force parameter.
  6592. */
  6593. between = function (x, a, b) {
  6594. if (x < a || x > b) {
  6595. if (force) {
  6596. x = mathMin(mathMax(a, x), b);
  6597. } else {
  6598. skip = true;
  6599. }
  6600. }
  6601. return x;
  6602. };
  6603. translatedValue = pick(translatedValue, axis.translate(value, null, null, old));
  6604. x1 = x2 = mathRound(translatedValue + transB);
  6605. y1 = y2 = mathRound(cHeight - translatedValue - transB);
  6606. if (!isNumber(translatedValue)) { // no min or max
  6607. skip = true;
  6608. } else if (axis.horiz) {
  6609. y1 = axisTop;
  6610. y2 = cHeight - axis.bottom;
  6611. x1 = x2 = between(x1, axisLeft, axisLeft + axis.width);
  6612. } else {
  6613. x1 = axisLeft;
  6614. x2 = cWidth - axis.right;
  6615. y1 = y2 = between(y1, axisTop, axisTop + axis.height);
  6616. }
  6617. return skip && !force ?
  6618. null :
  6619. chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 1);
  6620. },
  6621. /**
  6622. * Set the tick positions of a linear axis to round values like whole tens or every five.
  6623. */
  6624. getLinearTickPositions: function (tickInterval, min, max) {
  6625. var pos,
  6626. lastPos,
  6627. roundedMin = correctFloat(mathFloor(min / tickInterval) * tickInterval),
  6628. roundedMax = correctFloat(mathCeil(max / tickInterval) * tickInterval),
  6629. tickPositions = [];
  6630. // For single points, add a tick regardless of the relative position (#2662)
  6631. if (min === max && isNumber(min)) {
  6632. return [min];
  6633. }
  6634. // Populate the intermediate values
  6635. pos = roundedMin;
  6636. while (pos <= roundedMax) {
  6637. // Place the tick on the rounded value
  6638. tickPositions.push(pos);
  6639. // Always add the raw tickInterval, not the corrected one.
  6640. pos = correctFloat(pos + tickInterval);
  6641. // If the interval is not big enough in the current min - max range to actually increase
  6642. // the loop variable, we need to break out to prevent endless loop. Issue #619
  6643. if (pos === lastPos) {
  6644. break;
  6645. }
  6646. // Record the last value
  6647. lastPos = pos;
  6648. }
  6649. return tickPositions;
  6650. },
  6651. /**
  6652. * Return the minor tick positions. For logarithmic axes, reuse the same logic
  6653. * as for major ticks.
  6654. */
  6655. getMinorTickPositions: function () {
  6656. var axis = this,
  6657. options = axis.options,
  6658. tickPositions = axis.tickPositions,
  6659. minorTickInterval = axis.minorTickInterval,
  6660. minorTickPositions = [],
  6661. pos,
  6662. i,
  6663. pointRangePadding = axis.pointRangePadding || 0,
  6664. min = axis.min - pointRangePadding, // #1498
  6665. max = axis.max + pointRangePadding, // #1498
  6666. range = max - min,
  6667. len;
  6668. // If minor ticks get too dense, they are hard to read, and may cause long running script. So we don't draw them.
  6669. if (range && range / minorTickInterval < axis.len / 3) { // #3875
  6670. if (axis.isLog) {
  6671. len = tickPositions.length;
  6672. for (i = 1; i < len; i++) {
  6673. minorTickPositions = minorTickPositions.concat(
  6674. axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true)
  6675. );
  6676. }
  6677. } else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314
  6678. minorTickPositions = minorTickPositions.concat(
  6679. axis.getTimeTicks(
  6680. axis.normalizeTimeTickInterval(minorTickInterval),
  6681. min,
  6682. max,
  6683. options.startOfWeek
  6684. )
  6685. );
  6686. } else {
  6687. for (pos = min + (tickPositions[0] - min) % minorTickInterval; pos <= max; pos += minorTickInterval) {
  6688. minorTickPositions.push(pos);
  6689. }
  6690. }
  6691. }
  6692. if (minorTickPositions.length !== 0) { // don't change the extremes, when there is no minor ticks
  6693. axis.trimTicks(minorTickPositions, options.startOnTick, options.endOnTick); // #3652 #3743 #1498
  6694. }
  6695. return minorTickPositions;
  6696. },
  6697. /**
  6698. * Adjust the min and max for the minimum range. Keep in mind that the series data is
  6699. * not yet processed, so we don't have information on data cropping and grouping, or
  6700. * updated axis.pointRange or series.pointRange. The data can't be processed until
  6701. * we have finally established min and max.
  6702. */
  6703. adjustForMinRange: function () {
  6704. var axis = this,
  6705. options = axis.options,
  6706. min = axis.min,
  6707. max = axis.max,
  6708. zoomOffset,
  6709. spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange,
  6710. closestDataRange,
  6711. i,
  6712. distance,
  6713. xData,
  6714. loopLength,
  6715. minArgs,
  6716. maxArgs,
  6717. minRange;
  6718. // Set the automatic minimum range based on the closest point distance
  6719. if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) {
  6720. if (defined(options.min) || defined(options.max)) {
  6721. axis.minRange = null; // don't do this again
  6722. } else {
  6723. // Find the closest distance between raw data points, as opposed to
  6724. // closestPointRange that applies to processed points (cropped and grouped)
  6725. each(axis.series, function (series) {
  6726. xData = series.xData;
  6727. loopLength = series.xIncrement ? 1 : xData.length - 1;
  6728. for (i = loopLength; i > 0; i--) {
  6729. distance = xData[i] - xData[i - 1];
  6730. if (closestDataRange === UNDEFINED || distance < closestDataRange) {
  6731. closestDataRange = distance;
  6732. }
  6733. }
  6734. });
  6735. axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin);
  6736. }
  6737. }
  6738. // if minRange is exceeded, adjust
  6739. if (max - min < axis.minRange) {
  6740. minRange = axis.minRange;
  6741. zoomOffset = (minRange - max + min) / 2;
  6742. // if min and max options have been set, don't go beyond it
  6743. minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)];
  6744. if (spaceAvailable) { // if space is available, stay within the data range
  6745. minArgs[2] = axis.isLog ? axis.log2lin(axis.dataMin) : axis.dataMin;
  6746. }
  6747. min = arrayMax(minArgs);
  6748. maxArgs = [min + minRange, pick(options.max, min + minRange)];
  6749. if (spaceAvailable) { // if space is availabe, stay within the data range
  6750. maxArgs[2] = axis.isLog ? axis.log2lin(axis.dataMax) : axis.dataMax;
  6751. }
  6752. max = arrayMin(maxArgs);
  6753. // now if the max is adjusted, adjust the min back
  6754. if (max - min < minRange) {
  6755. minArgs[0] = max - minRange;
  6756. minArgs[1] = pick(options.min, max - minRange);
  6757. min = arrayMax(minArgs);
  6758. }
  6759. }
  6760. // Record modified extremes
  6761. axis.min = min;
  6762. axis.max = max;
  6763. },
  6764. /**
  6765. * Find the closestPointRange across all series
  6766. */
  6767. getClosest: function () {
  6768. var ret;
  6769. if (this.categories) {
  6770. ret = 1;
  6771. } else {
  6772. each(this.series, function (series) {
  6773. var seriesClosest = series.closestPointRange;
  6774. if (!series.noSharedTooltip && defined(seriesClosest)) {
  6775. ret = defined(ret) ?
  6776. mathMin(ret, seriesClosest) :
  6777. seriesClosest;
  6778. }
  6779. });
  6780. }
  6781. return ret;
  6782. },
  6783. /**
  6784. * When a point name is given and no x, search for the name in the existing categories,
  6785. * or if categories aren't provided, search names or create a new category (#2522).
  6786. */
  6787. nameToX: function (point) {
  6788. var explicitCategories = isArray(this.categories),
  6789. names = explicitCategories ? this.categories : this.names,
  6790. nameX = point.options.x,
  6791. x;
  6792. point.series.requireSorting = false;
  6793. if (!defined(nameX)) {
  6794. nameX = this.options.nameToX === false ?
  6795. point.series.autoIncrement() :
  6796. inArray(point.name, names);
  6797. }
  6798. if (nameX === -1) { // The name is not found in currenct categories
  6799. if (!explicitCategories) {
  6800. x = names.length;
  6801. }
  6802. } else {
  6803. x = nameX;
  6804. }
  6805. // Write the last point's name to the names array
  6806. this.names[x] = point.name;
  6807. return x;
  6808. },
  6809. /**
  6810. * When changes have been done to series data, update the axis.names.
  6811. */
  6812. updateNames: function () {
  6813. var axis = this;
  6814. if (this.names.length > 0) {
  6815. this.names.length = 0;
  6816. this.minRange = undefined;
  6817. each(this.series || [], function (series) {
  6818. // When adding a series, points are not yet generated
  6819. if (!series.processedXData) {
  6820. series.processData();
  6821. series.generatePoints();
  6822. }
  6823. each(series.points, function (point, i) {
  6824. var x;
  6825. if (point.options && point.options.x === undefined) {
  6826. x = axis.nameToX(point);
  6827. if (x !== point.x) {
  6828. point.x = x;
  6829. series.xData[i] = x;
  6830. }
  6831. }
  6832. });
  6833. });
  6834. }
  6835. },
  6836. /**
  6837. * Update translation information
  6838. */
  6839. setAxisTranslation: function (saveOld) {
  6840. var axis = this,
  6841. range = axis.max - axis.min,
  6842. pointRange = axis.axisPointRange || 0,
  6843. closestPointRange,
  6844. minPointOffset = 0,
  6845. pointRangePadding = 0,
  6846. linkedParent = axis.linkedParent,
  6847. ordinalCorrection,
  6848. hasCategories = !!axis.categories,
  6849. transA = axis.transA,
  6850. isXAxis = axis.isXAxis;
  6851. // Adjust translation for padding. Y axis with categories need to go through the same (#1784).
  6852. if (isXAxis || hasCategories || pointRange) {
  6853. if (linkedParent) {
  6854. minPointOffset = linkedParent.minPointOffset;
  6855. pointRangePadding = linkedParent.pointRangePadding;
  6856. } else {
  6857. // Get the closest points
  6858. closestPointRange = axis.getClosest();
  6859. each(axis.series, function (series) {
  6860. var seriesPointRange = hasCategories ?
  6861. 1 :
  6862. (isXAxis ?
  6863. pick(series.options.pointRange, closestPointRange, 0) :
  6864. (axis.axisPointRange || 0)), // #2806
  6865. pointPlacement = series.options.pointPlacement;
  6866. pointRange = mathMax(pointRange, seriesPointRange);
  6867. if (!axis.single) {
  6868. // minPointOffset is the value padding to the left of the axis in order to make
  6869. // room for points with a pointRange, typically columns. When the pointPlacement option
  6870. // is 'between' or 'on', this padding does not apply.
  6871. minPointOffset = mathMax(
  6872. minPointOffset,
  6873. isString(pointPlacement) ? 0 : seriesPointRange / 2
  6874. );
  6875. // Determine the total padding needed to the length of the axis to make room for the
  6876. // pointRange. If the series' pointPlacement is 'on', no padding is added.
  6877. pointRangePadding = mathMax(
  6878. pointRangePadding,
  6879. pointPlacement === 'on' ? 0 : seriesPointRange
  6880. );
  6881. }
  6882. });
  6883. }
  6884. // Record minPointOffset and pointRangePadding
  6885. ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853
  6886. axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection;
  6887. axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection;
  6888. // pointRange means the width reserved for each point, like in a column chart
  6889. axis.pointRange = mathMin(pointRange, range);
  6890. // closestPointRange means the closest distance between points. In columns
  6891. // it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange
  6892. // is some other value
  6893. if (isXAxis) {
  6894. axis.closestPointRange = closestPointRange;
  6895. }
  6896. }
  6897. // Secondary values
  6898. if (saveOld) {
  6899. axis.oldTransA = transA;
  6900. }
  6901. axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1);
  6902. axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend
  6903. axis.minPixelPadding = transA * minPointOffset;
  6904. },
  6905. minFromRange: function () {
  6906. return this.max - this.range;
  6907. },
  6908. /**
  6909. * Set the tick positions to round values and optionally extend the extremes
  6910. * to the nearest tick
  6911. */
  6912. setTickInterval: function (secondPass) {
  6913. var axis = this,
  6914. chart = axis.chart,
  6915. options = axis.options,
  6916. isLog = axis.isLog,
  6917. log2lin = axis.log2lin,
  6918. isDatetimeAxis = axis.isDatetimeAxis,
  6919. isXAxis = axis.isXAxis,
  6920. isLinked = axis.isLinked,
  6921. maxPadding = options.maxPadding,
  6922. minPadding = options.minPadding,
  6923. length,
  6924. linkedParentExtremes,
  6925. tickIntervalOption = options.tickInterval,
  6926. minTickInterval,
  6927. tickPixelIntervalOption = options.tickPixelInterval,
  6928. categories = axis.categories,
  6929. threshold = axis.threshold,
  6930. softThreshold = axis.softThreshold,
  6931. thresholdMin,
  6932. thresholdMax,
  6933. hardMin,
  6934. hardMax;
  6935. if (!isDatetimeAxis && !categories && !isLinked) {
  6936. this.getTickAmount();
  6937. }
  6938. // Min or max set either by zooming/setExtremes or initial options
  6939. hardMin = pick(axis.userMin, options.min);
  6940. hardMax = pick(axis.userMax, options.max);
  6941. // Linked axis gets the extremes from the parent axis
  6942. if (isLinked) {
  6943. axis.linkedParent = chart[axis.coll][options.linkedTo];
  6944. linkedParentExtremes = axis.linkedParent.getExtremes();
  6945. axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin);
  6946. axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax);
  6947. if (options.type !== axis.linkedParent.options.type) {
  6948. error(11, 1); // Can't link axes of different type
  6949. }
  6950. // Initial min and max from the extreme data values
  6951. } else {
  6952. // Adjust to hard threshold
  6953. if (!softThreshold && defined(threshold)) {
  6954. if (axis.dataMin >= threshold) {
  6955. thresholdMin = threshold;
  6956. minPadding = 0;
  6957. } else if (axis.dataMax <= threshold) {
  6958. thresholdMax = threshold;
  6959. maxPadding = 0;
  6960. }
  6961. }
  6962. axis.min = pick(hardMin, thresholdMin, axis.dataMin);
  6963. axis.max = pick(hardMax, thresholdMax, axis.dataMax);
  6964. }
  6965. if (isLog) {
  6966. if (!secondPass && mathMin(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978
  6967. error(10, 1); // Can't plot negative values on log axis
  6968. }
  6969. // The correctFloat cures #934, float errors on full tens. But it
  6970. // was too aggressive for #4360 because of conversion back to lin,
  6971. // therefore use precision 15.
  6972. axis.min = correctFloat(log2lin(axis.min), 15);
  6973. axis.max = correctFloat(log2lin(axis.max), 15);
  6974. }
  6975. // handle zoomed range
  6976. if (axis.range && defined(axis.max)) {
  6977. axis.userMin = axis.min = hardMin = mathMax(axis.min, axis.minFromRange()); // #618
  6978. axis.userMax = hardMax = axis.max;
  6979. axis.range = null; // don't use it when running setExtremes
  6980. }
  6981. // Hook for Highstock Scroller. Consider combining with beforePadding.
  6982. fireEvent(axis, 'foundExtremes');
  6983. // Hook for adjusting this.min and this.max. Used by bubble series.
  6984. if (axis.beforePadding) {
  6985. axis.beforePadding();
  6986. }
  6987. // adjust min and max for the minimum range
  6988. axis.adjustForMinRange();
  6989. // Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding
  6990. // into account, we do this after computing tick interval (#1337).
  6991. if (!categories && !axis.axisPointRange && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) {
  6992. length = axis.max - axis.min;
  6993. if (length) {
  6994. if (!defined(hardMin) && minPadding) {
  6995. axis.min -= length * minPadding;
  6996. }
  6997. if (!defined(hardMax) && maxPadding) {
  6998. axis.max += length * maxPadding;
  6999. }
  7000. }
  7001. }
  7002. // Stay within floor and ceiling
  7003. if (isNumber(options.floor)) {
  7004. axis.min = mathMax(axis.min, options.floor);
  7005. }
  7006. if (isNumber(options.ceiling)) {
  7007. axis.max = mathMin(axis.max, options.ceiling);
  7008. }
  7009. // When the threshold is soft, adjust the extreme value only if
  7010. // the data extreme and the padded extreme land on either side of the threshold. For example,
  7011. // a series of [0, 1, 2, 3] would make the yAxis add a tick for -1 because of the
  7012. // default minPadding and startOnTick options. This is prevented by the softThreshold
  7013. // option.
  7014. if (softThreshold && defined(axis.dataMin)) {
  7015. threshold = threshold || 0;
  7016. if (!defined(hardMin) && axis.min < threshold && axis.dataMin >= threshold) {
  7017. axis.min = threshold;
  7018. } else if (!defined(hardMax) && axis.max > threshold && axis.dataMax <= threshold) {
  7019. axis.max = threshold;
  7020. }
  7021. }
  7022. // get tickInterval
  7023. if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) {
  7024. axis.tickInterval = 1;
  7025. } else if (isLinked && !tickIntervalOption &&
  7026. tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) {
  7027. axis.tickInterval = tickIntervalOption = axis.linkedParent.tickInterval;
  7028. } else {
  7029. axis.tickInterval = pick(
  7030. tickIntervalOption,
  7031. this.tickAmount ? ((axis.max - axis.min) / mathMax(this.tickAmount - 1, 1)) : undefined,
  7032. categories ? // for categoried axis, 1 is default, for linear axis use tickPix
  7033. 1 :
  7034. // don't let it be more than the data range
  7035. (axis.max - axis.min) * tickPixelIntervalOption / mathMax(axis.len, tickPixelIntervalOption)
  7036. );
  7037. }
  7038. // Now we're finished detecting min and max, crop and group series data. This
  7039. // is in turn needed in order to find tick positions in ordinal axes.
  7040. if (isXAxis && !secondPass) {
  7041. each(axis.series, function (series) {
  7042. series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax);
  7043. });
  7044. }
  7045. // set the translation factor used in translate function
  7046. axis.setAxisTranslation(true);
  7047. // hook for ordinal axes and radial axes
  7048. if (axis.beforeSetTickPositions) {
  7049. axis.beforeSetTickPositions();
  7050. }
  7051. // hook for extensions, used in Highstock ordinal axes
  7052. if (axis.postProcessTickInterval) {
  7053. axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval);
  7054. }
  7055. // In column-like charts, don't cramp in more ticks than there are points (#1943, #4184)
  7056. if (axis.pointRange && !tickIntervalOption) {
  7057. axis.tickInterval = mathMax(axis.pointRange, axis.tickInterval);
  7058. }
  7059. // Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined.
  7060. minTickInterval = pick(options.minTickInterval, axis.isDatetimeAxis && axis.closestPointRange);
  7061. if (!tickIntervalOption && axis.tickInterval < minTickInterval) {
  7062. axis.tickInterval = minTickInterval;
  7063. }
  7064. // for linear axes, get magnitude and normalize the interval
  7065. if (!isDatetimeAxis && !isLog && !tickIntervalOption) {
  7066. axis.tickInterval = normalizeTickInterval(
  7067. axis.tickInterval,
  7068. null,
  7069. getMagnitude(axis.tickInterval),
  7070. // If the tick interval is between 0.5 and 5 and the axis max is in the order of
  7071. // thousands, chances are we are dealing with years. Don't allow decimals. #3363.
  7072. pick(options.allowDecimals, !(axis.tickInterval > 0.5 && axis.tickInterval < 5 && axis.max > 1000 && axis.max < 9999)),
  7073. !!this.tickAmount
  7074. );
  7075. }
  7076. // Prevent ticks from getting so close that we can't draw the labels
  7077. if (!this.tickAmount) {
  7078. axis.tickInterval = axis.unsquish();
  7079. }
  7080. this.setTickPositions();
  7081. },
  7082. /**
  7083. * Now we have computed the normalized tickInterval, get the tick positions
  7084. */
  7085. setTickPositions: function () {
  7086. var options = this.options,
  7087. tickPositions,
  7088. tickPositionsOption = options.tickPositions,
  7089. tickPositioner = options.tickPositioner,
  7090. startOnTick = options.startOnTick,
  7091. endOnTick = options.endOnTick,
  7092. single;
  7093. // Set the tickmarkOffset
  7094. this.tickmarkOffset = (this.categories && options.tickmarkPlacement === 'between' &&
  7095. this.tickInterval === 1) ? 0.5 : 0; // #3202
  7096. // get minorTickInterval
  7097. this.minorTickInterval = options.minorTickInterval === 'auto' && this.tickInterval ?
  7098. this.tickInterval / 5 : options.minorTickInterval;
  7099. // Find the tick positions
  7100. this.tickPositions = tickPositions = tickPositionsOption && tickPositionsOption.slice(); // Work on a copy (#1565)
  7101. if (!tickPositions) {
  7102. if (this.isDatetimeAxis) {
  7103. tickPositions = this.getTimeTicks(
  7104. this.normalizeTimeTickInterval(this.tickInterval, options.units),
  7105. this.min,
  7106. this.max,
  7107. options.startOfWeek,
  7108. this.ordinalPositions,
  7109. this.closestPointRange,
  7110. true
  7111. );
  7112. } else if (this.isLog) {
  7113. tickPositions = this.getLogTickPositions(this.tickInterval, this.min, this.max);
  7114. } else {
  7115. tickPositions = this.getLinearTickPositions(this.tickInterval, this.min, this.max);
  7116. }
  7117. // Too dense ticks, keep only the first and last (#4477)
  7118. if (tickPositions.length > this.len) {
  7119. tickPositions = [tickPositions[0], tickPositions.pop()];
  7120. }
  7121. this.tickPositions = tickPositions;
  7122. // Run the tick positioner callback, that allows modifying auto tick positions.
  7123. if (tickPositioner) {
  7124. tickPositioner = tickPositioner.apply(this, [this.min, this.max]);
  7125. if (tickPositioner) {
  7126. this.tickPositions = tickPositions = tickPositioner;
  7127. }
  7128. }
  7129. }
  7130. if (!this.isLinked) {
  7131. // reset min/max or remove extremes based on start/end on tick
  7132. this.trimTicks(tickPositions, startOnTick, endOnTick);
  7133. // When there is only one point, or all points have the same value on this axis, then min
  7134. // and max are equal and tickPositions.length is 0 or 1. In this case, add some padding
  7135. // in order to center the point, but leave it with one tick. #1337.
  7136. if (this.min === this.max && defined(this.min) && !this.tickAmount) {
  7137. // Substract half a unit (#2619, #2846, #2515, #3390)
  7138. single = true;
  7139. this.min -= 0.5;
  7140. this.max += 0.5;
  7141. }
  7142. this.single = single;
  7143. if (!tickPositionsOption && !tickPositioner) {
  7144. this.adjustTickAmount();
  7145. }
  7146. }
  7147. },
  7148. /**
  7149. * Handle startOnTick and endOnTick by either adapting to padding min/max or rounded min/max
  7150. */
  7151. trimTicks: function (tickPositions, startOnTick, endOnTick) {
  7152. var roundedMin = tickPositions[0],
  7153. roundedMax = tickPositions[tickPositions.length - 1],
  7154. minPointOffset = this.minPointOffset || 0;
  7155. if (startOnTick) {
  7156. this.min = roundedMin;
  7157. } else {
  7158. while (this.min - minPointOffset > tickPositions[0]) {
  7159. tickPositions.shift();
  7160. }
  7161. }
  7162. if (endOnTick) {
  7163. this.max = roundedMax;
  7164. } else {
  7165. while (this.max + minPointOffset < tickPositions[tickPositions.length - 1]) {
  7166. tickPositions.pop();
  7167. }
  7168. }
  7169. // If no tick are left, set one tick in the middle (#3195)
  7170. if (tickPositions.length === 0 && defined(roundedMin)) {
  7171. tickPositions.push((roundedMax + roundedMin) / 2);
  7172. }
  7173. },
  7174. /**
  7175. * Check if there are multiple axes in the same pane
  7176. * @returns {Boolean} There are other axes
  7177. */
  7178. alignToOthers: function () {
  7179. var others = {}, // Whether there is another axis to pair with this one
  7180. hasOther,
  7181. options = this.options;
  7182. if (this.chart.options.chart.alignTicks !== false && options.alignTicks !== false) {
  7183. each(this.chart[this.coll], function (axis) {
  7184. var otherOptions = axis.options,
  7185. horiz = axis.horiz,
  7186. key = [
  7187. horiz ? otherOptions.left : otherOptions.top,
  7188. otherOptions.width,
  7189. otherOptions.height,
  7190. otherOptions.pane
  7191. ].join(',');
  7192. if (axis.series.length) { // #4442
  7193. if (others[key]) {
  7194. hasOther = true; // #4201
  7195. } else {
  7196. others[key] = 1;
  7197. }
  7198. }
  7199. });
  7200. }
  7201. return hasOther;
  7202. },
  7203. /**
  7204. * Set the max ticks of either the x and y axis collection
  7205. */
  7206. getTickAmount: function () {
  7207. var options = this.options,
  7208. tickAmount = options.tickAmount,
  7209. tickPixelInterval = options.tickPixelInterval;
  7210. if (!defined(options.tickInterval) && this.len < tickPixelInterval && !this.isRadial &&
  7211. !this.isLog && options.startOnTick && options.endOnTick) {
  7212. tickAmount = 2;
  7213. }
  7214. if (!tickAmount && this.alignToOthers()) {
  7215. // Add 1 because 4 tick intervals require 5 ticks (including first and last)
  7216. tickAmount = mathCeil(this.len / tickPixelInterval) + 1;
  7217. }
  7218. // For tick amounts of 2 and 3, compute five ticks and remove the intermediate ones. This
  7219. // prevents the axis from adding ticks that are too far away from the data extremes.
  7220. if (tickAmount < 4) {
  7221. this.finalTickAmt = tickAmount;
  7222. tickAmount = 5;
  7223. }
  7224. this.tickAmount = tickAmount;
  7225. },
  7226. /**
  7227. * When using multiple axes, adjust the number of ticks to match the highest
  7228. * number of ticks in that group
  7229. */
  7230. adjustTickAmount: function () {
  7231. var tickInterval = this.tickInterval,
  7232. tickPositions = this.tickPositions,
  7233. tickAmount = this.tickAmount,
  7234. finalTickAmt = this.finalTickAmt,
  7235. currentTickAmount = tickPositions && tickPositions.length,
  7236. i,
  7237. len;
  7238. if (currentTickAmount < tickAmount) {
  7239. while (tickPositions.length < tickAmount) {
  7240. tickPositions.push(correctFloat(
  7241. tickPositions[tickPositions.length - 1] + tickInterval
  7242. ));
  7243. }
  7244. this.transA *= (currentTickAmount - 1) / (tickAmount - 1);
  7245. this.max = tickPositions[tickPositions.length - 1];
  7246. // We have too many ticks, run second pass to try to reduce ticks
  7247. } else if (currentTickAmount > tickAmount) {
  7248. this.tickInterval *= 2;
  7249. this.setTickPositions();
  7250. }
  7251. // The finalTickAmt property is set in getTickAmount
  7252. if (defined(finalTickAmt)) {
  7253. i = len = tickPositions.length;
  7254. while (i--) {
  7255. if (
  7256. (finalTickAmt === 3 && i % 2 === 1) || // Remove every other tick
  7257. (finalTickAmt <= 2 && i > 0 && i < len - 1) // Remove all but first and last
  7258. ) {
  7259. tickPositions.splice(i, 1);
  7260. }
  7261. }
  7262. this.finalTickAmt = UNDEFINED;
  7263. }
  7264. },
  7265. /**
  7266. * Set the scale based on data min and max, user set min and max or options
  7267. *
  7268. */
  7269. setScale: function () {
  7270. var axis = this,
  7271. isDirtyData,
  7272. isDirtyAxisLength;
  7273. axis.oldMin = axis.min;
  7274. axis.oldMax = axis.max;
  7275. axis.oldAxisLength = axis.len;
  7276. // set the new axisLength
  7277. axis.setAxisSize();
  7278. //axisLength = horiz ? axisWidth : axisHeight;
  7279. isDirtyAxisLength = axis.len !== axis.oldAxisLength;
  7280. // is there new data?
  7281. each(axis.series, function (series) {
  7282. if (series.isDirtyData || series.isDirty ||
  7283. series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well
  7284. isDirtyData = true;
  7285. }
  7286. });
  7287. // do we really need to go through all this?
  7288. if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw ||
  7289. axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax || axis.alignToOthers()) {
  7290. if (axis.resetStacks) {
  7291. axis.resetStacks();
  7292. }
  7293. axis.forceRedraw = false;
  7294. // get data extremes if needed
  7295. axis.getSeriesExtremes();
  7296. // get fixed positions based on tickInterval
  7297. axis.setTickInterval();
  7298. // record old values to decide whether a rescale is necessary later on (#540)
  7299. axis.oldUserMin = axis.userMin;
  7300. axis.oldUserMax = axis.userMax;
  7301. // Mark as dirty if it is not already set to dirty and extremes have changed. #595.
  7302. if (!axis.isDirty) {
  7303. axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax;
  7304. }
  7305. } else if (axis.cleanStacks) {
  7306. axis.cleanStacks();
  7307. }
  7308. },
  7309. /**
  7310. * Set the extremes and optionally redraw
  7311. * @param {Number} newMin
  7312. * @param {Number} newMax
  7313. * @param {Boolean} redraw
  7314. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  7315. * configuration
  7316. * @param {Object} eventArguments
  7317. *
  7318. */
  7319. setExtremes: function (newMin, newMax, redraw, animation, eventArguments) {
  7320. var axis = this,
  7321. chart = axis.chart;
  7322. redraw = pick(redraw, true); // defaults to true
  7323. each(axis.series, function (serie) {
  7324. delete serie.kdTree;
  7325. });
  7326. // Extend the arguments with min and max
  7327. eventArguments = extend(eventArguments, {
  7328. min: newMin,
  7329. max: newMax
  7330. });
  7331. // Fire the event
  7332. fireEvent(axis, 'setExtremes', eventArguments, function () { // the default event handler
  7333. axis.userMin = newMin;
  7334. axis.userMax = newMax;
  7335. axis.eventArgs = eventArguments;
  7336. if (redraw) {
  7337. chart.redraw(animation);
  7338. }
  7339. });
  7340. },
  7341. /**
  7342. * Overridable method for zooming chart. Pulled out in a separate method to allow overriding
  7343. * in stock charts.
  7344. */
  7345. zoom: function (newMin, newMax) {
  7346. var dataMin = this.dataMin,
  7347. dataMax = this.dataMax,
  7348. options = this.options,
  7349. min = mathMin(dataMin, pick(options.min, dataMin)),
  7350. max = mathMax(dataMax, pick(options.max, dataMax));
  7351. // Prevent pinch zooming out of range. Check for defined is for #1946. #1734.
  7352. if (!this.allowZoomOutside) {
  7353. if (defined(dataMin) && newMin <= min) {
  7354. newMin = min;
  7355. }
  7356. if (defined(dataMax) && newMax >= max) {
  7357. newMax = max;
  7358. }
  7359. }
  7360. // In full view, displaying the reset zoom button is not required
  7361. this.displayBtn = newMin !== UNDEFINED || newMax !== UNDEFINED;
  7362. // Do it
  7363. this.setExtremes(
  7364. newMin,
  7365. newMax,
  7366. false,
  7367. UNDEFINED,
  7368. { trigger: 'zoom' }
  7369. );
  7370. return true;
  7371. },
  7372. /**
  7373. * Update the axis metrics
  7374. */
  7375. setAxisSize: function () {
  7376. var chart = this.chart,
  7377. options = this.options,
  7378. offsetLeft = options.offsetLeft || 0,
  7379. offsetRight = options.offsetRight || 0,
  7380. horiz = this.horiz,
  7381. width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight),
  7382. height = pick(options.height, chart.plotHeight),
  7383. top = pick(options.top, chart.plotTop),
  7384. left = pick(options.left, chart.plotLeft + offsetLeft),
  7385. percentRegex = /%$/;
  7386. // Check for percentage based input values. Rounding fixes problems with
  7387. // column overflow and plot line filtering (#4898, #4899)
  7388. if (percentRegex.test(height)) {
  7389. height = Math.round(parseFloat(height) / 100 * chart.plotHeight);
  7390. }
  7391. if (percentRegex.test(top)) {
  7392. top = Math.round(parseFloat(top) / 100 * chart.plotHeight + chart.plotTop);
  7393. }
  7394. // Expose basic values to use in Series object and navigator
  7395. this.left = left;
  7396. this.top = top;
  7397. this.width = width;
  7398. this.height = height;
  7399. this.bottom = chart.chartHeight - height - top;
  7400. this.right = chart.chartWidth - width - left;
  7401. // Direction agnostic properties
  7402. this.len = mathMax(horiz ? width : height, 0); // mathMax fixes #905
  7403. this.pos = horiz ? left : top; // distance from SVG origin
  7404. },
  7405. /**
  7406. * Get the actual axis extremes
  7407. */
  7408. getExtremes: function () {
  7409. var axis = this,
  7410. isLog = axis.isLog,
  7411. lin2log = axis.lin2log;
  7412. return {
  7413. min: isLog ? correctFloat(lin2log(axis.min)) : axis.min,
  7414. max: isLog ? correctFloat(lin2log(axis.max)) : axis.max,
  7415. dataMin: axis.dataMin,
  7416. dataMax: axis.dataMax,
  7417. userMin: axis.userMin,
  7418. userMax: axis.userMax
  7419. };
  7420. },
  7421. /**
  7422. * Get the zero plane either based on zero or on the min or max value.
  7423. * Used in bar and area plots
  7424. */
  7425. getThreshold: function (threshold) {
  7426. var axis = this,
  7427. isLog = axis.isLog,
  7428. lin2log = axis.lin2log,
  7429. realMin = isLog ? lin2log(axis.min) : axis.min,
  7430. realMax = isLog ? lin2log(axis.max) : axis.max;
  7431. if (threshold === null) {
  7432. threshold = realMin;
  7433. } else if (realMin > threshold) {
  7434. threshold = realMin;
  7435. } else if (realMax < threshold) {
  7436. threshold = realMax;
  7437. }
  7438. return axis.translate(threshold, 0, 1, 0, 1);
  7439. },
  7440. /**
  7441. * Compute auto alignment for the axis label based on which side the axis is on
  7442. * and the given rotation for the label
  7443. */
  7444. autoLabelAlign: function (rotation) {
  7445. var ret,
  7446. angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360;
  7447. if (angle > 15 && angle < 165) {
  7448. ret = 'right';
  7449. } else if (angle > 195 && angle < 345) {
  7450. ret = 'left';
  7451. } else {
  7452. ret = 'center';
  7453. }
  7454. return ret;
  7455. },
  7456. /**
  7457. * Get the tick length and width for the axis.
  7458. * @param {String} prefix 'tick' or 'minorTick'
  7459. * @returns {Array} An array of tickLength and tickWidth
  7460. */
  7461. tickSize: function (prefix) {
  7462. var options = this.options,
  7463. tickLength = options[prefix + 'Length'],
  7464. tickWidth = pick(options[prefix + 'Width'], prefix === 'tick' && this.isXAxis ? 1 : 0); // X axis defaults to 1
  7465. if (tickWidth && tickLength) {
  7466. // Negate the length
  7467. if (options[prefix + 'Position'] === 'inside') {
  7468. tickLength = -tickLength;
  7469. }
  7470. return [tickLength, tickWidth];
  7471. }
  7472. },
  7473. /**
  7474. * Return the size of the labels
  7475. */
  7476. labelMetrics: function () {
  7477. return this.chart.renderer.fontMetrics(
  7478. this.options.labels.style.fontSize,
  7479. this.ticks[0] && this.ticks[0].label
  7480. );
  7481. },
  7482. /**
  7483. * Prevent the ticks from getting so close we can't draw the labels. On a horizontal
  7484. * axis, this is handled by rotating the labels, removing ticks and adding ellipsis.
  7485. * On a vertical axis remove ticks and add ellipsis.
  7486. */
  7487. unsquish: function () {
  7488. var labelOptions = this.options.labels,
  7489. horiz = this.horiz,
  7490. tickInterval = this.tickInterval,
  7491. newTickInterval = tickInterval,
  7492. slotSize = this.len / (((this.categories ? 1 : 0) + this.max - this.min) / tickInterval),
  7493. rotation,
  7494. rotationOption = labelOptions.rotation,
  7495. labelMetrics = this.labelMetrics(),
  7496. step,
  7497. bestScore = Number.MAX_VALUE,
  7498. autoRotation,
  7499. // Return the multiple of tickInterval that is needed to avoid collision
  7500. getStep = function (spaceNeeded) {
  7501. var step = spaceNeeded / (slotSize || 1);
  7502. step = step > 1 ? mathCeil(step) : 1;
  7503. return step * tickInterval;
  7504. };
  7505. if (horiz) {
  7506. autoRotation = !labelOptions.staggerLines && !labelOptions.step && ( // #3971
  7507. defined(rotationOption) ?
  7508. [rotationOption] :
  7509. slotSize < pick(labelOptions.autoRotationLimit, 80) && labelOptions.autoRotation
  7510. );
  7511. if (autoRotation) {
  7512. // Loop over the given autoRotation options, and determine which gives the best score. The
  7513. // best score is that with the lowest number of steps and a rotation closest to horizontal.
  7514. each(autoRotation, function (rot) {
  7515. var score;
  7516. if (rot === rotationOption || (rot && rot >= -90 && rot <= 90)) { // #3891
  7517. step = getStep(mathAbs(labelMetrics.h / mathSin(deg2rad * rot)));
  7518. score = step + mathAbs(rot / 360);
  7519. if (score < bestScore) {
  7520. bestScore = score;
  7521. rotation = rot;
  7522. newTickInterval = step;
  7523. }
  7524. }
  7525. });
  7526. }
  7527. } else if (!labelOptions.step) { // #4411
  7528. newTickInterval = getStep(labelMetrics.h);
  7529. }
  7530. this.autoRotation = autoRotation;
  7531. this.labelRotation = pick(rotation, rotationOption);
  7532. return newTickInterval;
  7533. },
  7534. /**
  7535. * Get the general slot width for this axis. This may change between the pre-render (from Axis.getOffset)
  7536. * and the final tick rendering and placement (#5086).
  7537. */
  7538. getSlotWidth: function () {
  7539. var chart = this.chart,
  7540. horiz = this.horiz,
  7541. labelOptions = this.options.labels,
  7542. slotCount = Math.max(this.tickPositions.length - (this.categories ? 0 : 1), 1),
  7543. marginLeft = chart.margin[3];
  7544. return (horiz && (labelOptions.step || 0) < 2 && !labelOptions.rotation && // #4415
  7545. ((this.staggerLines || 1) * chart.plotWidth) / slotCount) ||
  7546. (!horiz && ((marginLeft && (marginLeft - chart.spacing[3])) || chart.chartWidth * 0.33)); // #1580, #1931
  7547. },
  7548. /**
  7549. * Render the axis labels and determine whether ellipsis or rotation need to be applied
  7550. */
  7551. renderUnsquish: function () {
  7552. var chart = this.chart,
  7553. renderer = chart.renderer,
  7554. tickPositions = this.tickPositions,
  7555. ticks = this.ticks,
  7556. labelOptions = this.options.labels,
  7557. horiz = this.horiz,
  7558. slotWidth = this.getSlotWidth(),
  7559. innerWidth = mathMax(1, mathRound(slotWidth - 2 * (labelOptions.padding || 5))),
  7560. attr = {},
  7561. labelMetrics = this.labelMetrics(),
  7562. textOverflowOption = labelOptions.style.textOverflow,
  7563. css,
  7564. maxLabelLength = 0,
  7565. label,
  7566. i,
  7567. pos;
  7568. // Set rotation option unless it is "auto", like in gauges
  7569. if (!isString(labelOptions.rotation)) {
  7570. attr.rotation = labelOptions.rotation || 0; // #4443
  7571. }
  7572. // Get the longest label length
  7573. each(tickPositions, function (tick) {
  7574. tick = ticks[tick];
  7575. if (tick && tick.labelLength > maxLabelLength) {
  7576. maxLabelLength = tick.labelLength;
  7577. }
  7578. });
  7579. this.maxLabelLength = maxLabelLength;
  7580. // Handle auto rotation on horizontal axis
  7581. if (this.autoRotation) {
  7582. // Apply rotation only if the label is too wide for the slot, and
  7583. // the label is wider than its height.
  7584. if (maxLabelLength > innerWidth && maxLabelLength > labelMetrics.h) {
  7585. attr.rotation = this.labelRotation;
  7586. } else {
  7587. this.labelRotation = 0;
  7588. }
  7589. // Handle word-wrap or ellipsis on vertical axis
  7590. } else if (slotWidth) {
  7591. // For word-wrap or ellipsis
  7592. css = { width: innerWidth + PX };
  7593. if (!textOverflowOption) {
  7594. css.textOverflow = 'clip';
  7595. // On vertical axis, only allow word wrap if there is room for more lines.
  7596. i = tickPositions.length;
  7597. while (!horiz && i--) {
  7598. pos = tickPositions[i];
  7599. label = ticks[pos].label;
  7600. if (label) {
  7601. // Reset ellipsis in order to get the correct bounding box (#4070)
  7602. if (label.styles.textOverflow === 'ellipsis') {
  7603. label.css({ textOverflow: 'clip' });
  7604. // Set the correct width in order to read the bounding box height (#4678, #5034)
  7605. } else if (ticks[pos].labelLength > slotWidth) {
  7606. label.css({ width: slotWidth + 'px' });
  7607. }
  7608. if (label.getBBox().height > this.len / tickPositions.length - (labelMetrics.h - labelMetrics.f)) {
  7609. label.specCss = { textOverflow: 'ellipsis' };
  7610. }
  7611. }
  7612. }
  7613. }
  7614. }
  7615. // Add ellipsis if the label length is significantly longer than ideal
  7616. if (attr.rotation) {
  7617. css = {
  7618. width: (maxLabelLength > chart.chartHeight * 0.5 ? chart.chartHeight * 0.33 : chart.chartHeight) + PX
  7619. };
  7620. if (!textOverflowOption) {
  7621. css.textOverflow = 'ellipsis';
  7622. }
  7623. }
  7624. // Set the explicit or automatic label alignment
  7625. this.labelAlign = labelOptions.align || this.autoLabelAlign(this.labelRotation);
  7626. if (this.labelAlign) {
  7627. attr.align = this.labelAlign;
  7628. }
  7629. // Apply general and specific CSS
  7630. each(tickPositions, function (pos) {
  7631. var tick = ticks[pos],
  7632. label = tick && tick.label;
  7633. if (label) {
  7634. label.attr(attr); // This needs to go before the CSS in old IE (#4502)
  7635. if (css) {
  7636. label.css(merge(css, label.specCss));
  7637. }
  7638. delete label.specCss;
  7639. tick.rotation = attr.rotation;
  7640. }
  7641. });
  7642. // Note: Why is this not part of getLabelPosition?
  7643. this.tickRotCorr = renderer.rotCorr(labelMetrics.b, this.labelRotation || 0, this.side !== 0);
  7644. },
  7645. /**
  7646. * Return true if the axis has associated data
  7647. */
  7648. hasData: function () {
  7649. return this.hasVisibleSeries || (defined(this.min) && defined(this.max) && !!this.tickPositions);
  7650. },
  7651. /**
  7652. * Render the tick labels to a preliminary position to get their sizes
  7653. */
  7654. getOffset: function () {
  7655. var axis = this,
  7656. chart = axis.chart,
  7657. renderer = chart.renderer,
  7658. options = axis.options,
  7659. tickPositions = axis.tickPositions,
  7660. ticks = axis.ticks,
  7661. horiz = axis.horiz,
  7662. side = axis.side,
  7663. invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side,
  7664. hasData,
  7665. showAxis,
  7666. titleOffset = 0,
  7667. titleOffsetOption,
  7668. titleMargin = 0,
  7669. axisTitleOptions = options.title,
  7670. labelOptions = options.labels,
  7671. labelOffset = 0, // reset
  7672. labelOffsetPadded,
  7673. opposite = axis.opposite,
  7674. axisOffset = chart.axisOffset,
  7675. clipOffset = chart.clipOffset,
  7676. clip,
  7677. directionFactor = [-1, 1, 1, -1][side],
  7678. n,
  7679. textAlign,
  7680. axisParent = axis.axisParent, // Used in color axis
  7681. lineHeightCorrection,
  7682. tickSize = this.tickSize('tick');
  7683. // For reuse in Axis.render
  7684. hasData = axis.hasData();
  7685. axis.showAxis = showAxis = hasData || pick(options.showEmpty, true);
  7686. // Set/reset staggerLines
  7687. axis.staggerLines = axis.horiz && labelOptions.staggerLines;
  7688. // Create the axisGroup and gridGroup elements on first iteration
  7689. if (!axis.axisGroup) {
  7690. axis.gridGroup = renderer.g('grid')
  7691. .attr({ zIndex: options.gridZIndex || 1 })
  7692. .add(axisParent);
  7693. axis.axisGroup = renderer.g('axis')
  7694. .attr({ zIndex: options.zIndex || 2 })
  7695. .add(axisParent);
  7696. axis.labelGroup = renderer.g('axis-labels')
  7697. .attr({ zIndex: labelOptions.zIndex || 7 })
  7698. .addClass(PREFIX + axis.coll.toLowerCase() + '-labels')
  7699. .add(axisParent);
  7700. }
  7701. if (hasData || axis.isLinked) {
  7702. // Generate ticks
  7703. each(tickPositions, function (pos) {
  7704. if (!ticks[pos]) {
  7705. ticks[pos] = new Tick(axis, pos);
  7706. } else {
  7707. ticks[pos].addLabel(); // update labels depending on tick interval
  7708. }
  7709. });
  7710. axis.renderUnsquish();
  7711. // Left side must be align: right and right side must have align: left for labels
  7712. if (labelOptions.reserveSpace !== false && (side === 0 || side === 2 ||
  7713. { 1: 'left', 3: 'right' }[side] === axis.labelAlign || axis.labelAlign === 'center')) {
  7714. each(tickPositions, function (pos) {
  7715. // get the highest offset
  7716. labelOffset = mathMax(
  7717. ticks[pos].getLabelSize(),
  7718. labelOffset
  7719. );
  7720. });
  7721. }
  7722. if (axis.staggerLines) {
  7723. labelOffset *= axis.staggerLines;
  7724. axis.labelOffset = labelOffset * (axis.opposite ? -1 : 1);
  7725. }
  7726. } else { // doesn't have data
  7727. for (n in ticks) {
  7728. ticks[n].destroy();
  7729. delete ticks[n];
  7730. }
  7731. }
  7732. if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) {
  7733. if (!axis.axisTitle) {
  7734. textAlign = axisTitleOptions.textAlign;
  7735. if (!textAlign) {
  7736. textAlign = (horiz ? {
  7737. low: 'left',
  7738. middle: 'center',
  7739. high: 'right'
  7740. } : {
  7741. low: opposite ? 'right' : 'left',
  7742. middle: 'center',
  7743. high: opposite ? 'left' : 'right'
  7744. })[axisTitleOptions.align];
  7745. }
  7746. axis.axisTitle = renderer.text(
  7747. axisTitleOptions.text,
  7748. 0,
  7749. 0,
  7750. axisTitleOptions.useHTML
  7751. )
  7752. .attr({
  7753. zIndex: 7,
  7754. rotation: axisTitleOptions.rotation || 0,
  7755. align: textAlign
  7756. })
  7757. .addClass(PREFIX + this.coll.toLowerCase() + '-title')
  7758. .css(axisTitleOptions.style)
  7759. .add(axis.axisGroup);
  7760. axis.axisTitle.isNew = true;
  7761. }
  7762. if (showAxis) {
  7763. titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width'];
  7764. titleOffsetOption = axisTitleOptions.offset;
  7765. titleMargin = defined(titleOffsetOption) ? 0 : pick(axisTitleOptions.margin, horiz ? 5 : 10);
  7766. }
  7767. // hide or show the title depending on whether showEmpty is set
  7768. axis.axisTitle[showAxis ? 'show' : 'hide'](true);
  7769. }
  7770. // handle automatic or user set offset
  7771. axis.offset = directionFactor * pick(options.offset, axisOffset[side]);
  7772. axis.tickRotCorr = axis.tickRotCorr || { x: 0, y: 0 }; // polar
  7773. if (side === 0) {
  7774. lineHeightCorrection = -axis.labelMetrics().h;
  7775. } else if (side === 2) {
  7776. lineHeightCorrection = axis.tickRotCorr.y;
  7777. } else {
  7778. lineHeightCorrection = 0;
  7779. }
  7780. // Find the padded label offset
  7781. labelOffsetPadded = Math.abs(labelOffset) + titleMargin;
  7782. if (labelOffset) {
  7783. labelOffsetPadded -= lineHeightCorrection;
  7784. labelOffsetPadded += directionFactor * (horiz ? pick(labelOptions.y, axis.tickRotCorr.y + directionFactor * 8) : labelOptions.x);
  7785. }
  7786. axis.axisTitleMargin = pick(titleOffsetOption, labelOffsetPadded);
  7787. axisOffset[side] = mathMax(
  7788. axisOffset[side],
  7789. axis.axisTitleMargin + titleOffset + directionFactor * axis.offset,
  7790. labelOffsetPadded, // #3027
  7791. hasData && tickPositions.length && tickSize ? tickSize[0] : 0 // #4866
  7792. );
  7793. // Decide the clipping needed to keep the graph inside the plot area and axis lines
  7794. clip = options.offset ? 0 : mathFloor(options.lineWidth / 2) * 2; // #4308, #4371
  7795. clipOffset[invertedSide] = mathMax(clipOffset[invertedSide], clip);
  7796. },
  7797. /**
  7798. * Get the path for the axis line
  7799. */
  7800. getLinePath: function (lineWidth) {
  7801. var chart = this.chart,
  7802. opposite = this.opposite,
  7803. offset = this.offset,
  7804. horiz = this.horiz,
  7805. lineLeft = this.left + (opposite ? this.width : 0) + offset,
  7806. lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset;
  7807. if (opposite) {
  7808. lineWidth *= -1; // crispify the other way - #1480, #1687
  7809. }
  7810. return chart.renderer
  7811. .crispLine([
  7812. M,
  7813. horiz ?
  7814. this.left :
  7815. lineLeft,
  7816. horiz ?
  7817. lineTop :
  7818. this.top,
  7819. L,
  7820. horiz ?
  7821. chart.chartWidth - this.right :
  7822. lineLeft,
  7823. horiz ?
  7824. lineTop :
  7825. chart.chartHeight - this.bottom
  7826. ], lineWidth);
  7827. },
  7828. /**
  7829. * Position the title
  7830. */
  7831. getTitlePosition: function () {
  7832. // compute anchor points for each of the title align options
  7833. var horiz = this.horiz,
  7834. axisLeft = this.left,
  7835. axisTop = this.top,
  7836. axisLength = this.len,
  7837. axisTitleOptions = this.options.title,
  7838. margin = horiz ? axisLeft : axisTop,
  7839. opposite = this.opposite,
  7840. offset = this.offset,
  7841. xOption = axisTitleOptions.x || 0,
  7842. yOption = axisTitleOptions.y || 0,
  7843. fontSize = this.chart.renderer.fontMetrics(axisTitleOptions.style.fontSize).f,
  7844. // the position in the length direction of the axis
  7845. alongAxis = {
  7846. low: margin + (horiz ? 0 : axisLength),
  7847. middle: margin + axisLength / 2,
  7848. high: margin + (horiz ? axisLength : 0)
  7849. }[axisTitleOptions.align],
  7850. // the position in the perpendicular direction of the axis
  7851. offAxis = (horiz ? axisTop + this.height : axisLeft) +
  7852. (horiz ? 1 : -1) * // horizontal axis reverses the margin
  7853. (opposite ? -1 : 1) * // so does opposite axes
  7854. this.axisTitleMargin +
  7855. (this.side === 2 ? fontSize : 0);
  7856. return {
  7857. x: horiz ?
  7858. alongAxis + xOption :
  7859. offAxis + (opposite ? this.width : 0) + offset + xOption,
  7860. y: horiz ?
  7861. offAxis + yOption - (opposite ? this.height : 0) + offset :
  7862. alongAxis + yOption
  7863. };
  7864. },
  7865. /**
  7866. * Render the axis
  7867. */
  7868. render: function () {
  7869. var axis = this,
  7870. chart = axis.chart,
  7871. renderer = chart.renderer,
  7872. options = axis.options,
  7873. isLog = axis.isLog,
  7874. lin2log = axis.lin2log,
  7875. isLinked = axis.isLinked,
  7876. tickPositions = axis.tickPositions,
  7877. axisTitle = axis.axisTitle,
  7878. ticks = axis.ticks,
  7879. minorTicks = axis.minorTicks,
  7880. alternateBands = axis.alternateBands,
  7881. stackLabelOptions = options.stackLabels,
  7882. alternateGridColor = options.alternateGridColor,
  7883. tickmarkOffset = axis.tickmarkOffset,
  7884. lineWidth = options.lineWidth,
  7885. linePath,
  7886. hasRendered = chart.hasRendered,
  7887. slideInTicks = hasRendered && isNumber(axis.oldMin),
  7888. showAxis = axis.showAxis,
  7889. animation = animObject(renderer.globalAnimation),
  7890. from,
  7891. to;
  7892. // Reset
  7893. axis.labelEdge.length = 0;
  7894. //axis.justifyToPlot = overflow === 'justify';
  7895. axis.overlap = false;
  7896. // Mark all elements inActive before we go over and mark the active ones
  7897. each([ticks, minorTicks, alternateBands], function (coll) {
  7898. var pos;
  7899. for (pos in coll) {
  7900. coll[pos].isActive = false;
  7901. }
  7902. });
  7903. // If the series has data draw the ticks. Else only the line and title
  7904. if (axis.hasData() || isLinked) {
  7905. // minor ticks
  7906. if (axis.minorTickInterval && !axis.categories) {
  7907. each(axis.getMinorTickPositions(), function (pos) {
  7908. if (!minorTicks[pos]) {
  7909. minorTicks[pos] = new Tick(axis, pos, 'minor');
  7910. }
  7911. // render new ticks in old position
  7912. if (slideInTicks && minorTicks[pos].isNew) {
  7913. minorTicks[pos].render(null, true);
  7914. }
  7915. minorTicks[pos].render(null, false, 1);
  7916. });
  7917. }
  7918. // Major ticks. Pull out the first item and render it last so that
  7919. // we can get the position of the neighbour label. #808.
  7920. if (tickPositions.length) { // #1300
  7921. each(tickPositions, function (pos, i) {
  7922. // linked axes need an extra check to find out if
  7923. if (!isLinked || (pos >= axis.min && pos <= axis.max)) {
  7924. if (!ticks[pos]) {
  7925. ticks[pos] = new Tick(axis, pos);
  7926. }
  7927. // render new ticks in old position
  7928. if (slideInTicks && ticks[pos].isNew) {
  7929. ticks[pos].render(i, true, 0.1);
  7930. }
  7931. ticks[pos].render(i);
  7932. }
  7933. });
  7934. // In a categorized axis, the tick marks are displayed between labels. So
  7935. // we need to add a tick mark and grid line at the left edge of the X axis.
  7936. if (tickmarkOffset && (axis.min === 0 || axis.single)) {
  7937. if (!ticks[-1]) {
  7938. ticks[-1] = new Tick(axis, -1, null, true);
  7939. }
  7940. ticks[-1].render(-1);
  7941. }
  7942. }
  7943. // alternate grid color
  7944. if (alternateGridColor) {
  7945. each(tickPositions, function (pos, i) {
  7946. to = tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] + tickmarkOffset : axis.max - tickmarkOffset;
  7947. if (i % 2 === 0 && pos < axis.max && to <= axis.max + (chart.polar ? -tickmarkOffset : tickmarkOffset)) { // #2248, #4660
  7948. if (!alternateBands[pos]) {
  7949. alternateBands[pos] = new Highcharts.PlotLineOrBand(axis);
  7950. }
  7951. from = pos + tickmarkOffset; // #949
  7952. alternateBands[pos].options = {
  7953. from: isLog ? lin2log(from) : from,
  7954. to: isLog ? lin2log(to) : to,
  7955. color: alternateGridColor
  7956. };
  7957. alternateBands[pos].render();
  7958. alternateBands[pos].isActive = true;
  7959. }
  7960. });
  7961. }
  7962. // custom plot lines and bands
  7963. if (!axis._addedPlotLB) { // only first time
  7964. each((options.plotLines || []).concat(options.plotBands || []), function (plotLineOptions) {
  7965. axis.addPlotBandOrLine(plotLineOptions);
  7966. });
  7967. axis._addedPlotLB = true;
  7968. }
  7969. } // end if hasData
  7970. // Remove inactive ticks
  7971. each([ticks, minorTicks, alternateBands], function (coll) {
  7972. var pos,
  7973. i,
  7974. forDestruction = [],
  7975. delay = animation.duration,
  7976. destroyInactiveItems = function () {
  7977. i = forDestruction.length;
  7978. while (i--) {
  7979. // When resizing rapidly, the same items may be destroyed in different timeouts,
  7980. // or the may be reactivated
  7981. if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) {
  7982. coll[forDestruction[i]].destroy();
  7983. delete coll[forDestruction[i]];
  7984. }
  7985. }
  7986. };
  7987. for (pos in coll) {
  7988. if (!coll[pos].isActive) {
  7989. // Render to zero opacity
  7990. coll[pos].render(pos, false, 0);
  7991. coll[pos].isActive = false;
  7992. forDestruction.push(pos);
  7993. }
  7994. }
  7995. // When the objects are finished fading out, destroy them
  7996. syncTimeout(
  7997. destroyInactiveItems,
  7998. coll === alternateBands || !chart.hasRendered || !delay ? 0 : delay
  7999. );
  8000. });
  8001. // Static items. As the axis group is cleared on subsequent calls
  8002. // to render, these items are added outside the group.
  8003. // axis line
  8004. if (lineWidth) {
  8005. linePath = axis.getLinePath(lineWidth);
  8006. if (!axis.axisLine) {
  8007. axis.axisLine = renderer.path(linePath)
  8008. .attr({
  8009. stroke: options.lineColor,
  8010. 'stroke-width': lineWidth,
  8011. zIndex: 7
  8012. })
  8013. .add(axis.axisGroup);
  8014. } else {
  8015. axis.axisLine.animate({ d: linePath });
  8016. }
  8017. // show or hide the line depending on options.showEmpty
  8018. axis.axisLine[showAxis ? 'show' : 'hide'](true);
  8019. }
  8020. if (axisTitle && showAxis) {
  8021. axisTitle[axisTitle.isNew ? 'attr' : 'animate'](
  8022. axis.getTitlePosition()
  8023. );
  8024. axisTitle.isNew = false;
  8025. }
  8026. // Stacked totals:
  8027. if (stackLabelOptions && stackLabelOptions.enabled) {
  8028. axis.renderStackTotals();
  8029. }
  8030. // End stacked totals
  8031. axis.isDirty = false;
  8032. },
  8033. /**
  8034. * Redraw the axis to reflect changes in the data or axis extremes
  8035. */
  8036. redraw: function () {
  8037. if (this.visible) {
  8038. // render the axis
  8039. this.render();
  8040. // move plot lines and bands
  8041. each(this.plotLinesAndBands, function (plotLine) {
  8042. plotLine.render();
  8043. });
  8044. }
  8045. // mark associated series as dirty and ready for redraw
  8046. each(this.series, function (series) {
  8047. series.isDirty = true;
  8048. });
  8049. },
  8050. /**
  8051. * Destroys an Axis instance.
  8052. */
  8053. destroy: function (keepEvents) {
  8054. var axis = this,
  8055. stacks = axis.stacks,
  8056. stackKey,
  8057. plotLinesAndBands = axis.plotLinesAndBands,
  8058. i;
  8059. // Remove the events
  8060. if (!keepEvents) {
  8061. removeEvent(axis);
  8062. }
  8063. // Destroy each stack total
  8064. for (stackKey in stacks) {
  8065. destroyObjectProperties(stacks[stackKey]);
  8066. stacks[stackKey] = null;
  8067. }
  8068. // Destroy collections
  8069. each([axis.ticks, axis.minorTicks, axis.alternateBands], function (coll) {
  8070. destroyObjectProperties(coll);
  8071. });
  8072. i = plotLinesAndBands.length;
  8073. while (i--) { // #1975
  8074. plotLinesAndBands[i].destroy();
  8075. }
  8076. // Destroy properties
  8077. each(['stackTotalGroup', 'axisLine', 'axisTitle', 'axisGroup', 'gridGroup', 'labelGroup', 'cross'], function (prop) {
  8078. if (axis[prop]) {
  8079. axis[prop] = axis[prop].destroy();
  8080. }
  8081. });
  8082. this._addedPlotLB = this.chart._labelPanes = this.ordinalSlope = undefined; // #1611, #2887, #4314, #5316
  8083. },
  8084. /**
  8085. * Draw the crosshair
  8086. *
  8087. * @param {Object} e The event arguments from the modified pointer event
  8088. * @param {Object} point The Point object
  8089. */
  8090. drawCrosshair: function (e, point) {
  8091. var path,
  8092. options = this.crosshair,
  8093. pos,
  8094. attribs,
  8095. categorized,
  8096. strokeWidth;
  8097. // Use last available event when updating non-snapped crosshairs without
  8098. // mouse interaction (#5287)
  8099. if (!e) {
  8100. e = this.cross && this.cross.e;
  8101. }
  8102. if (
  8103. // Disabled in options
  8104. !this.crosshair ||
  8105. // Snap
  8106. ((defined(point) || !pick(options.snap, true)) === false)
  8107. ) {
  8108. this.hideCrosshair();
  8109. } else {
  8110. // Get the path
  8111. if (!pick(options.snap, true)) {
  8112. pos = (this.horiz ? e.chartX - this.pos : this.len - e.chartY + this.pos);
  8113. } else if (defined(point)) {
  8114. pos = this.isXAxis ? point.plotX : this.len - point.plotY; // #3834
  8115. }
  8116. if (this.isRadial) {
  8117. path = this.getPlotLinePath(this.isXAxis ? point.x : pick(point.stackY, point.y)) || null; // #3189
  8118. } else {
  8119. path = this.getPlotLinePath(null, null, null, null, pos) || null; // #3189
  8120. }
  8121. if (path === null) {
  8122. this.hideCrosshair();
  8123. return;
  8124. }
  8125. categorized = this.categories && !this.isRadial;
  8126. strokeWidth = pick(options.width, (categorized ? this.transA : 1));
  8127. // Draw the cross
  8128. if (this.cross) {
  8129. this.cross
  8130. .attr({
  8131. d: path,
  8132. visibility: 'visible',
  8133. 'stroke-width': strokeWidth // #4737
  8134. });
  8135. } else {
  8136. attribs = {
  8137. 'pointer-events': 'none', // #5259
  8138. 'stroke-width': strokeWidth,
  8139. stroke: options.color || (categorized ? 'rgba(155,200,255,0.2)' : '#C0C0C0'),
  8140. zIndex: pick(options.zIndex, 2)
  8141. };
  8142. if (options.dashStyle) {
  8143. attribs.dashstyle = options.dashStyle;
  8144. }
  8145. this.cross = this.chart.renderer.path(path).attr(attribs).add();
  8146. }
  8147. this.cross.e = e;
  8148. }
  8149. },
  8150. /**
  8151. * Hide the crosshair.
  8152. */
  8153. hideCrosshair: function () {
  8154. if (this.cross) {
  8155. this.cross.hide();
  8156. }
  8157. }
  8158. }; // end Axis
  8159. extend(Axis.prototype, AxisPlotLineOrBandExtension);
  8160. /**
  8161. * Set the tick positions to a time unit that makes sense, for example
  8162. * on the first of each month or on every Monday. Return an array
  8163. * with the time positions. Used in datetime axes as well as for grouping
  8164. * data on a datetime axis.
  8165. *
  8166. * @param {Object} normalizedInterval The interval in axis values (ms) and the count
  8167. * @param {Number} min The minimum in axis values
  8168. * @param {Number} max The maximum in axis values
  8169. * @param {Number} startOfWeek
  8170. */
  8171. Axis.prototype.getTimeTicks = function (normalizedInterval, min, max, startOfWeek) {
  8172. var tickPositions = [],
  8173. i,
  8174. higherRanks = {},
  8175. useUTC = defaultOptions.global.useUTC,
  8176. minYear, // used in months and years as a basis for Date.UTC()
  8177. minDate = new Date(min - getTZOffset(min)),
  8178. interval = normalizedInterval.unitRange,
  8179. count = normalizedInterval.count;
  8180. if (defined(min)) { // #1300
  8181. minDate[setMilliseconds](interval >= timeUnits.second ? 0 : // #3935
  8182. count * mathFloor(minDate.getMilliseconds() / count)); // #3652, #3654
  8183. if (interval >= timeUnits.second) { // second
  8184. minDate[setSeconds](interval >= timeUnits.minute ? 0 : // #3935
  8185. count * mathFloor(minDate.getSeconds() / count));
  8186. }
  8187. if (interval >= timeUnits.minute) { // minute
  8188. minDate[setMinutes](interval >= timeUnits.hour ? 0 :
  8189. count * mathFloor(minDate[getMinutes]() / count));
  8190. }
  8191. if (interval >= timeUnits.hour) { // hour
  8192. minDate[setHours](interval >= timeUnits.day ? 0 :
  8193. count * mathFloor(minDate[getHours]() / count));
  8194. }
  8195. if (interval >= timeUnits.day) { // day
  8196. minDate[setDate](interval >= timeUnits.month ? 1 :
  8197. count * mathFloor(minDate[getDate]() / count));
  8198. }
  8199. if (interval >= timeUnits.month) { // month
  8200. minDate[setMonth](interval >= timeUnits.year ? 0 :
  8201. count * mathFloor(minDate[getMonth]() / count));
  8202. minYear = minDate[getFullYear]();
  8203. }
  8204. if (interval >= timeUnits.year) { // year
  8205. minYear -= minYear % count;
  8206. minDate[setFullYear](minYear);
  8207. }
  8208. // week is a special case that runs outside the hierarchy
  8209. if (interval === timeUnits.week) {
  8210. // get start of current week, independent of count
  8211. minDate[setDate](minDate[getDate]() - minDate[getDay]() +
  8212. pick(startOfWeek, 1));
  8213. }
  8214. // get tick positions
  8215. i = 1;
  8216. if (timezoneOffset || getTimezoneOffset) {
  8217. minDate = minDate.getTime();
  8218. minDate = new Date(minDate + getTZOffset(minDate));
  8219. }
  8220. minYear = minDate[getFullYear]();
  8221. var time = minDate.getTime(),
  8222. minMonth = minDate[getMonth](),
  8223. minDateDate = minDate[getDate](),
  8224. variableDayLength = !useUTC || !!getTimezoneOffset, // #4951
  8225. localTimezoneOffset = (timeUnits.day +
  8226. (useUTC ? getTZOffset(minDate) : minDate.getTimezoneOffset() * 60 * 1000)
  8227. ) % timeUnits.day; // #950, #3359
  8228. // iterate and add tick positions at appropriate values
  8229. while (time < max) {
  8230. tickPositions.push(time);
  8231. // if the interval is years, use Date.UTC to increase years
  8232. if (interval === timeUnits.year) {
  8233. time = makeTime(minYear + i * count, 0);
  8234. // if the interval is months, use Date.UTC to increase months
  8235. } else if (interval === timeUnits.month) {
  8236. time = makeTime(minYear, minMonth + i * count);
  8237. // if we're using global time, the interval is not fixed as it jumps
  8238. // one hour at the DST crossover
  8239. } else if (variableDayLength && (interval === timeUnits.day || interval === timeUnits.week)) {
  8240. time = makeTime(minYear, minMonth, minDateDate +
  8241. i * count * (interval === timeUnits.day ? 1 : 7));
  8242. // else, the interval is fixed and we use simple addition
  8243. } else {
  8244. time += interval * count;
  8245. }
  8246. i++;
  8247. }
  8248. // push the last time
  8249. tickPositions.push(time);
  8250. // mark new days if the time is dividible by day (#1649, #1760)
  8251. each(grep(tickPositions, function (time) {
  8252. return interval <= timeUnits.hour && time % timeUnits.day === localTimezoneOffset;
  8253. }), function (time) {
  8254. higherRanks[time] = 'day';
  8255. });
  8256. }
  8257. // record information on the chosen unit - for dynamic label formatter
  8258. tickPositions.info = extend(normalizedInterval, {
  8259. higherRanks: higherRanks,
  8260. totalRange: interval * count
  8261. });
  8262. return tickPositions;
  8263. };
  8264. /**
  8265. * Get a normalized tick interval for dates. Returns a configuration object with
  8266. * unit range (interval), count and name. Used to prepare data for getTimeTicks.
  8267. * Previously this logic was part of getTimeTicks, but as getTimeTicks now runs
  8268. * of segments in stock charts, the normalizing logic was extracted in order to
  8269. * prevent it for running over again for each segment having the same interval.
  8270. * #662, #697.
  8271. */
  8272. Axis.prototype.normalizeTimeTickInterval = function (tickInterval, unitsOption) {
  8273. var units = unitsOption || [[
  8274. 'millisecond', // unit name
  8275. [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples
  8276. ], [
  8277. 'second',
  8278. [1, 2, 5, 10, 15, 30]
  8279. ], [
  8280. 'minute',
  8281. [1, 2, 5, 10, 15, 30]
  8282. ], [
  8283. 'hour',
  8284. [1, 2, 3, 4, 6, 8, 12]
  8285. ], [
  8286. 'day',
  8287. [1, 2]
  8288. ], [
  8289. 'week',
  8290. [1, 2]
  8291. ], [
  8292. 'month',
  8293. [1, 2, 3, 4, 6]
  8294. ], [
  8295. 'year',
  8296. null
  8297. ]],
  8298. unit = units[units.length - 1], // default unit is years
  8299. interval = timeUnits[unit[0]],
  8300. multiples = unit[1],
  8301. count,
  8302. i;
  8303. // loop through the units to find the one that best fits the tickInterval
  8304. for (i = 0; i < units.length; i++) {
  8305. unit = units[i];
  8306. interval = timeUnits[unit[0]];
  8307. multiples = unit[1];
  8308. if (units[i + 1]) {
  8309. // lessThan is in the middle between the highest multiple and the next unit.
  8310. var lessThan = (interval * multiples[multiples.length - 1] +
  8311. timeUnits[units[i + 1][0]]) / 2;
  8312. // break and keep the current unit
  8313. if (tickInterval <= lessThan) {
  8314. break;
  8315. }
  8316. }
  8317. }
  8318. // prevent 2.5 years intervals, though 25, 250 etc. are allowed
  8319. if (interval === timeUnits.year && tickInterval < 5 * interval) {
  8320. multiples = [1, 2, 5];
  8321. }
  8322. // get the count
  8323. count = normalizeTickInterval(
  8324. tickInterval / interval,
  8325. multiples,
  8326. unit[0] === 'year' ? mathMax(getMagnitude(tickInterval / interval), 1) : 1 // #1913, #2360
  8327. );
  8328. return {
  8329. unitRange: interval,
  8330. count: count,
  8331. unitName: unit[0]
  8332. };
  8333. };
  8334. /**
  8335. * Methods defined on the Axis prototype
  8336. */
  8337. /**
  8338. * Set the tick positions of a logarithmic axis
  8339. */
  8340. Axis.prototype.getLogTickPositions = function (interval, min, max, minor) {
  8341. var axis = this,
  8342. options = axis.options,
  8343. axisLength = axis.len,
  8344. lin2log = axis.lin2log,
  8345. log2lin = axis.log2lin,
  8346. // Since we use this method for both major and minor ticks,
  8347. // use a local variable and return the result
  8348. positions = [];
  8349. // Reset
  8350. if (!minor) {
  8351. axis._minorAutoInterval = null;
  8352. }
  8353. // First case: All ticks fall on whole logarithms: 1, 10, 100 etc.
  8354. if (interval >= 0.5) {
  8355. interval = mathRound(interval);
  8356. positions = axis.getLinearTickPositions(interval, min, max);
  8357. // Second case: We need intermediary ticks. For example
  8358. // 1, 2, 4, 6, 8, 10, 20, 40 etc.
  8359. } else if (interval >= 0.08) {
  8360. var roundedMin = mathFloor(min),
  8361. intermediate,
  8362. i,
  8363. j,
  8364. len,
  8365. pos,
  8366. lastPos,
  8367. break2;
  8368. if (interval > 0.3) {
  8369. intermediate = [1, 2, 4];
  8370. } else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc
  8371. intermediate = [1, 2, 4, 6, 8];
  8372. } else { // 0.1 equals ten minor ticks per 1, 10, 100 etc
  8373. intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  8374. }
  8375. for (i = roundedMin; i < max + 1 && !break2; i++) {
  8376. len = intermediate.length;
  8377. for (j = 0; j < len && !break2; j++) {
  8378. pos = log2lin(lin2log(i) * intermediate[j]);
  8379. if (pos > min && (!minor || lastPos <= max) && lastPos !== UNDEFINED) { // #1670, lastPos is #3113
  8380. positions.push(lastPos);
  8381. }
  8382. if (lastPos > max) {
  8383. break2 = true;
  8384. }
  8385. lastPos = pos;
  8386. }
  8387. }
  8388. // Third case: We are so deep in between whole logarithmic values that
  8389. // we might as well handle the tick positions like a linear axis. For
  8390. // example 1.01, 1.02, 1.03, 1.04.
  8391. } else {
  8392. var realMin = lin2log(min),
  8393. realMax = lin2log(max),
  8394. tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'],
  8395. filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption,
  8396. tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1),
  8397. totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength;
  8398. interval = pick(
  8399. filteredTickIntervalOption,
  8400. axis._minorAutoInterval,
  8401. (realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1)
  8402. );
  8403. interval = normalizeTickInterval(
  8404. interval,
  8405. null,
  8406. getMagnitude(interval)
  8407. );
  8408. positions = map(axis.getLinearTickPositions(
  8409. interval,
  8410. realMin,
  8411. realMax
  8412. ), log2lin);
  8413. if (!minor) {
  8414. axis._minorAutoInterval = interval / 5;
  8415. }
  8416. }
  8417. // Set the axis-level tickInterval variable
  8418. if (!minor) {
  8419. axis.tickInterval = interval;
  8420. }
  8421. return positions;
  8422. };
  8423. Axis.prototype.log2lin = function (num) {
  8424. return math.log(num) / math.LN10;
  8425. };
  8426. Axis.prototype.lin2log = function (num) {
  8427. return math.pow(10, num);
  8428. };
  8429. /**
  8430. * The tooltip object
  8431. * @param {Object} chart The chart instance
  8432. * @param {Object} options Tooltip options
  8433. */
  8434. var Tooltip = Highcharts.Tooltip = function () {
  8435. this.init.apply(this, arguments);
  8436. };
  8437. Tooltip.prototype = {
  8438. init: function (chart, options) {
  8439. var borderWidth = options.borderWidth,
  8440. style = options.style,
  8441. padding = pInt(style.padding);
  8442. // Save the chart and options
  8443. this.chart = chart;
  8444. this.options = options;
  8445. // Keep track of the current series
  8446. //this.currentSeries = UNDEFINED;
  8447. // List of crosshairs
  8448. this.crosshairs = [];
  8449. // Current values of x and y when animating
  8450. this.now = { x: 0, y: 0 };
  8451. // The tooltip is initially hidden
  8452. this.isHidden = true;
  8453. // create the label
  8454. this.label = chart.renderer.label('', 0, 0, options.shape || 'callout', null, null, options.useHTML, null, 'tooltip')
  8455. .attr({
  8456. padding: padding,
  8457. fill: options.backgroundColor,
  8458. 'stroke-width': borderWidth,
  8459. r: options.borderRadius,
  8460. zIndex: 8,
  8461. display: 'none' // #2301, #2657, #3532, #5570
  8462. })
  8463. .css(style)
  8464. .css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117)
  8465. .add();
  8466. // When using canVG the shadow shows up as a gray circle
  8467. // even if the tooltip is hidden.
  8468. if (!useCanVG) {
  8469. this.label.shadow(options.shadow);
  8470. }
  8471. // Public property for getting the shared state.
  8472. this.shared = options.shared;
  8473. },
  8474. /**
  8475. * Destroy the tooltip and its elements.
  8476. */
  8477. destroy: function () {
  8478. // Destroy and clear local variables
  8479. if (this.label) {
  8480. this.label = this.label.destroy();
  8481. }
  8482. clearTimeout(this.hideTimer);
  8483. clearTimeout(this.tooltipTimeout);
  8484. },
  8485. /**
  8486. * Provide a soft movement for the tooltip
  8487. *
  8488. * @param {Number} x
  8489. * @param {Number} y
  8490. * @private
  8491. */
  8492. move: function (x, y, anchorX, anchorY) {
  8493. var tooltip = this,
  8494. now = tooltip.now,
  8495. animate = tooltip.options.animation !== false && !tooltip.isHidden &&
  8496. // When we get close to the target position, abort animation and land on the right place (#3056)
  8497. (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1),
  8498. skipAnchor = tooltip.followPointer || tooltip.len > 1;
  8499. // Get intermediate values for animation
  8500. extend(now, {
  8501. x: animate ? (2 * now.x + x) / 3 : x,
  8502. y: animate ? (now.y + y) / 2 : y,
  8503. anchorX: skipAnchor ? UNDEFINED : animate ? (2 * now.anchorX + anchorX) / 3 : anchorX,
  8504. anchorY: skipAnchor ? UNDEFINED : animate ? (now.anchorY + anchorY) / 2 : anchorY
  8505. });
  8506. // Move to the intermediate value
  8507. tooltip.label.attr(now);
  8508. // Run on next tick of the mouse tracker
  8509. if (animate) {
  8510. // Never allow two timeouts
  8511. clearTimeout(this.tooltipTimeout);
  8512. // Set the fixed interval ticking for the smooth tooltip
  8513. this.tooltipTimeout = setTimeout(function () {
  8514. // The interval function may still be running during destroy, so check that the chart is really there before calling.
  8515. if (tooltip) {
  8516. tooltip.move(x, y, anchorX, anchorY);
  8517. }
  8518. }, 32);
  8519. }
  8520. },
  8521. /**
  8522. * Hide the tooltip
  8523. */
  8524. hide: function (delay) {
  8525. var tooltip = this;
  8526. clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766)
  8527. delay = pick(delay, this.options.hideDelay, 500);
  8528. if (!this.isHidden) {
  8529. this.hideTimer = syncTimeout(function () {
  8530. tooltip.label[delay ? 'fadeOut' : 'hide']();
  8531. tooltip.isHidden = true;
  8532. }, delay);
  8533. }
  8534. },
  8535. /**
  8536. * Extendable method to get the anchor position of the tooltip
  8537. * from a point or set of points
  8538. */
  8539. getAnchor: function (points, mouseEvent) {
  8540. var ret,
  8541. chart = this.chart,
  8542. inverted = chart.inverted,
  8543. plotTop = chart.plotTop,
  8544. plotLeft = chart.plotLeft,
  8545. plotX = 0,
  8546. plotY = 0,
  8547. yAxis,
  8548. xAxis;
  8549. points = splat(points);
  8550. // Pie uses a special tooltipPos
  8551. ret = points[0].tooltipPos;
  8552. // When tooltip follows mouse, relate the position to the mouse
  8553. if (this.followPointer && mouseEvent) {
  8554. if (mouseEvent.chartX === UNDEFINED) {
  8555. mouseEvent = chart.pointer.normalize(mouseEvent);
  8556. }
  8557. ret = [
  8558. mouseEvent.chartX - chart.plotLeft,
  8559. mouseEvent.chartY - plotTop
  8560. ];
  8561. }
  8562. // When shared, use the average position
  8563. if (!ret) {
  8564. each(points, function (point) {
  8565. yAxis = point.series.yAxis;
  8566. xAxis = point.series.xAxis;
  8567. plotX += point.plotX + (!inverted && xAxis ? xAxis.left - plotLeft : 0);
  8568. plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) +
  8569. (!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151
  8570. });
  8571. plotX /= points.length;
  8572. plotY /= points.length;
  8573. ret = [
  8574. inverted ? chart.plotWidth - plotY : plotX,
  8575. this.shared && !inverted && points.length > 1 && mouseEvent ?
  8576. mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424)
  8577. inverted ? chart.plotHeight - plotX : plotY
  8578. ];
  8579. }
  8580. return map(ret, mathRound);
  8581. },
  8582. /**
  8583. * Place the tooltip in a chart without spilling over
  8584. * and not covering the point it self.
  8585. */
  8586. getPosition: function (boxWidth, boxHeight, point) {
  8587. var chart = this.chart,
  8588. distance = this.distance,
  8589. ret = {},
  8590. h = point.h || 0, // #4117
  8591. swapped,
  8592. first = ['y', chart.chartHeight, boxHeight, point.plotY + chart.plotTop, chart.plotTop, chart.plotTop + chart.plotHeight],
  8593. second = ['x', chart.chartWidth, boxWidth, point.plotX + chart.plotLeft, chart.plotLeft, chart.plotLeft + chart.plotWidth],
  8594. // The far side is right or bottom
  8595. preferFarSide = !this.followPointer && pick(point.ttBelow, !chart.inverted === !!point.negative), // #4984
  8596. /**
  8597. * Handle the preferred dimension. When the preferred dimension is tooltip
  8598. * on top or bottom of the point, it will look for space there.
  8599. */
  8600. firstDimension = function (dim, outerSize, innerSize, point, min, max) {
  8601. var roomLeft = innerSize < point - distance,
  8602. roomRight = point + distance + innerSize < outerSize,
  8603. alignedLeft = point - distance - innerSize,
  8604. alignedRight = point + distance;
  8605. if (preferFarSide && roomRight) {
  8606. ret[dim] = alignedRight;
  8607. } else if (!preferFarSide && roomLeft) {
  8608. ret[dim] = alignedLeft;
  8609. } else if (roomLeft) {
  8610. ret[dim] = mathMin(max - innerSize, alignedLeft - h < 0 ? alignedLeft : alignedLeft - h);
  8611. } else if (roomRight) {
  8612. ret[dim] = mathMax(min, alignedRight + h + innerSize > outerSize ? alignedRight : alignedRight + h);
  8613. } else {
  8614. return false;
  8615. }
  8616. },
  8617. /**
  8618. * Handle the secondary dimension. If the preferred dimension is tooltip
  8619. * on top or bottom of the point, the second dimension is to align the tooltip
  8620. * above the point, trying to align center but allowing left or right
  8621. * align within the chart box.
  8622. */
  8623. secondDimension = function (dim, outerSize, innerSize, point) {
  8624. var retVal;
  8625. // Too close to the edge, return false and swap dimensions
  8626. if (point < distance || point > outerSize - distance) {
  8627. retVal = false;
  8628. // Align left/top
  8629. } else if (point < innerSize / 2) {
  8630. ret[dim] = 1;
  8631. // Align right/bottom
  8632. } else if (point > outerSize - innerSize / 2) {
  8633. ret[dim] = outerSize - innerSize - 2;
  8634. // Align center
  8635. } else {
  8636. ret[dim] = point - innerSize / 2;
  8637. }
  8638. return retVal;
  8639. },
  8640. /**
  8641. * Swap the dimensions
  8642. */
  8643. swap = function (count) {
  8644. var temp = first;
  8645. first = second;
  8646. second = temp;
  8647. swapped = count;
  8648. },
  8649. run = function () {
  8650. if (firstDimension.apply(0, first) !== false) {
  8651. if (secondDimension.apply(0, second) === false && !swapped) {
  8652. swap(true);
  8653. run();
  8654. }
  8655. } else if (!swapped) {
  8656. swap(true);
  8657. run();
  8658. } else {
  8659. ret.x = ret.y = 0;
  8660. }
  8661. };
  8662. // Under these conditions, prefer the tooltip on the side of the point
  8663. if (chart.inverted || this.len > 1) {
  8664. swap();
  8665. }
  8666. run();
  8667. return ret;
  8668. },
  8669. /**
  8670. * In case no user defined formatter is given, this will be used. Note that the context
  8671. * here is an object holding point, series, x, y etc.
  8672. */
  8673. defaultFormatter: function (tooltip) {
  8674. var items = this.points || splat(this),
  8675. s;
  8676. // build the header
  8677. s = [tooltip.tooltipFooterHeaderFormatter(items[0])]; //#3397: abstraction to enable formatting of footer and header
  8678. // build the values
  8679. s = s.concat(tooltip.bodyFormatter(items));
  8680. // footer
  8681. s.push(tooltip.tooltipFooterHeaderFormatter(items[0], true)); //#3397: abstraction to enable formatting of footer and header
  8682. return s.join('');
  8683. },
  8684. /**
  8685. * Refresh the tooltip's text and position.
  8686. * @param {Object} point
  8687. */
  8688. refresh: function (point, mouseEvent) {
  8689. var tooltip = this,
  8690. chart = tooltip.chart,
  8691. label = tooltip.label,
  8692. options = tooltip.options,
  8693. x,
  8694. y,
  8695. anchor,
  8696. textConfig = {},
  8697. text,
  8698. pointConfig = [],
  8699. formatter = options.formatter || tooltip.defaultFormatter,
  8700. hoverPoints = chart.hoverPoints,
  8701. borderColor,
  8702. shared = tooltip.shared,
  8703. currentSeries;
  8704. clearTimeout(this.hideTimer);
  8705. // get the reference point coordinates (pie charts use tooltipPos)
  8706. tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer;
  8707. anchor = tooltip.getAnchor(point, mouseEvent);
  8708. x = anchor[0];
  8709. y = anchor[1];
  8710. // shared tooltip, array is sent over
  8711. if (shared && !(point.series && point.series.noSharedTooltip)) {
  8712. // hide previous hoverPoints and set new
  8713. chart.hoverPoints = point;
  8714. if (hoverPoints) {
  8715. each(hoverPoints, function (point) {
  8716. point.setState();
  8717. });
  8718. }
  8719. each(point, function (item) {
  8720. item.setState(HOVER_STATE);
  8721. pointConfig.push(item.getLabelConfig());
  8722. });
  8723. textConfig = {
  8724. x: point[0].category,
  8725. y: point[0].y
  8726. };
  8727. textConfig.points = pointConfig;
  8728. this.len = pointConfig.length;
  8729. point = point[0];
  8730. // single point tooltip
  8731. } else {
  8732. textConfig = point.getLabelConfig();
  8733. }
  8734. text = formatter.call(textConfig, tooltip);
  8735. // register the current series
  8736. currentSeries = point.series;
  8737. this.distance = pick(currentSeries.tooltipOptions.distance, 16);
  8738. // update the inner HTML
  8739. if (text === false) {
  8740. this.hide();
  8741. } else {
  8742. // show it
  8743. if (tooltip.isHidden) {
  8744. stop(label);
  8745. label.attr({
  8746. opacity: 1,
  8747. display: 'block'
  8748. }).show();
  8749. }
  8750. // update text
  8751. label.attr({
  8752. text: text
  8753. });
  8754. // set the stroke color of the box
  8755. borderColor = options.borderColor || point.color || currentSeries.color || '#606060';
  8756. label.attr({
  8757. stroke: borderColor
  8758. });
  8759. tooltip.updatePosition({
  8760. plotX: x,
  8761. plotY: y,
  8762. negative: point.negative,
  8763. ttBelow: point.ttBelow,
  8764. h: anchor[2] || 0
  8765. });
  8766. this.isHidden = false;
  8767. }
  8768. fireEvent(chart, 'tooltipRefresh', {
  8769. text: text,
  8770. x: x + chart.plotLeft,
  8771. y: y + chart.plotTop,
  8772. borderColor: borderColor
  8773. });
  8774. },
  8775. /**
  8776. * Find the new position and perform the move
  8777. */
  8778. updatePosition: function (point) {
  8779. var chart = this.chart,
  8780. label = this.label,
  8781. pos = (this.options.positioner || this.getPosition).call(
  8782. this,
  8783. label.width,
  8784. label.height,
  8785. point
  8786. );
  8787. // do the move
  8788. this.move(
  8789. mathRound(pos.x),
  8790. mathRound(pos.y || 0), // can be undefined (#3977)
  8791. point.plotX + chart.plotLeft,
  8792. point.plotY + chart.plotTop
  8793. );
  8794. },
  8795. /**
  8796. * Get the best X date format based on the closest point range on the axis.
  8797. */
  8798. getXDateFormat: function (point, options, xAxis) {
  8799. var xDateFormat,
  8800. dateTimeLabelFormats = options.dateTimeLabelFormats,
  8801. closestPointRange = xAxis && xAxis.closestPointRange,
  8802. n,
  8803. blank = '01-01 00:00:00.000',
  8804. strpos = {
  8805. millisecond: 15,
  8806. second: 12,
  8807. minute: 9,
  8808. hour: 6,
  8809. day: 3
  8810. },
  8811. date,
  8812. lastN = 'millisecond'; // for sub-millisecond data, #4223
  8813. if (closestPointRange) {
  8814. date = dateFormat('%m-%d %H:%M:%S.%L', point.x);
  8815. for (n in timeUnits) {
  8816. // If the range is exactly one week and we're looking at a Sunday/Monday, go for the week format
  8817. if (closestPointRange === timeUnits.week && +dateFormat('%w', point.x) === xAxis.options.startOfWeek &&
  8818. date.substr(6) === blank.substr(6)) {
  8819. n = 'week';
  8820. break;
  8821. }
  8822. // The first format that is too great for the range
  8823. if (timeUnits[n] > closestPointRange) {
  8824. n = lastN;
  8825. break;
  8826. }
  8827. // If the point is placed every day at 23:59, we need to show
  8828. // the minutes as well. #2637.
  8829. if (strpos[n] && date.substr(strpos[n]) !== blank.substr(strpos[n])) {
  8830. break;
  8831. }
  8832. // Weeks are outside the hierarchy, only apply them on Mondays/Sundays like in the first condition
  8833. if (n !== 'week') {
  8834. lastN = n;
  8835. }
  8836. }
  8837. if (n) {
  8838. xDateFormat = dateTimeLabelFormats[n];
  8839. }
  8840. } else {
  8841. xDateFormat = dateTimeLabelFormats.day;
  8842. }
  8843. return xDateFormat || dateTimeLabelFormats.year; // #2546, 2581
  8844. },
  8845. /**
  8846. * Format the footer/header of the tooltip
  8847. * #3397: abstraction to enable formatting of footer and header
  8848. */
  8849. tooltipFooterHeaderFormatter: function (labelConfig, isFooter) {
  8850. var footOrHead = isFooter ? 'footer' : 'header',
  8851. series = labelConfig.series,
  8852. tooltipOptions = series.tooltipOptions,
  8853. xDateFormat = tooltipOptions.xDateFormat,
  8854. xAxis = series.xAxis,
  8855. isDateTime = xAxis && xAxis.options.type === 'datetime' && isNumber(labelConfig.key),
  8856. formatString = tooltipOptions[footOrHead + 'Format'];
  8857. // Guess the best date format based on the closest point distance (#568, #3418)
  8858. if (isDateTime && !xDateFormat) {
  8859. xDateFormat = this.getXDateFormat(labelConfig, tooltipOptions, xAxis);
  8860. }
  8861. // Insert the footer date format if any
  8862. if (isDateTime && xDateFormat) {
  8863. formatString = formatString.replace('{point.key}', '{point.key:' + xDateFormat + '}');
  8864. }
  8865. return format(formatString, {
  8866. point: labelConfig,
  8867. series: series
  8868. });
  8869. },
  8870. /**
  8871. * Build the body (lines) of the tooltip by iterating over the items and returning one entry for each item,
  8872. * abstracting this functionality allows to easily overwrite and extend it.
  8873. */
  8874. bodyFormatter: function (items) {
  8875. return map(items, function (item) {
  8876. var tooltipOptions = item.series.tooltipOptions;
  8877. return (tooltipOptions.pointFormatter || item.point.tooltipFormatter).call(item.point, tooltipOptions.pointFormat);
  8878. });
  8879. }
  8880. };
  8881. var hoverChartIndex;
  8882. // Global flag for touch support
  8883. hasTouch = doc && doc.documentElement.ontouchstart !== UNDEFINED;
  8884. /**
  8885. * The mouse tracker object. All methods starting with "on" are primary DOM event handlers.
  8886. * Subsequent methods should be named differently from what they are doing.
  8887. * @param {Object} chart The Chart instance
  8888. * @param {Object} options The root options object
  8889. */
  8890. var Pointer = Highcharts.Pointer = function (chart, options) {
  8891. this.init(chart, options);
  8892. };
  8893. Pointer.prototype = {
  8894. /**
  8895. * Initialize Pointer
  8896. */
  8897. init: function (chart, options) {
  8898. var chartOptions = options.chart,
  8899. chartEvents = chartOptions.events,
  8900. zoomType = useCanVG ? '' : chartOptions.zoomType,
  8901. inverted = chart.inverted,
  8902. zoomX,
  8903. zoomY;
  8904. // Store references
  8905. this.options = options;
  8906. this.chart = chart;
  8907. // Zoom status
  8908. this.zoomX = zoomX = /x/.test(zoomType);
  8909. this.zoomY = zoomY = /y/.test(zoomType);
  8910. this.zoomHor = (zoomX && !inverted) || (zoomY && inverted);
  8911. this.zoomVert = (zoomY && !inverted) || (zoomX && inverted);
  8912. this.hasZoom = zoomX || zoomY;
  8913. // Do we need to handle click on a touch device?
  8914. this.runChartClick = chartEvents && !!chartEvents.click;
  8915. this.pinchDown = [];
  8916. this.lastValidTouch = {};
  8917. if (Highcharts.Tooltip && options.tooltip.enabled) {
  8918. chart.tooltip = new Tooltip(chart, options.tooltip);
  8919. this.followTouchMove = pick(options.tooltip.followTouchMove, true);
  8920. }
  8921. this.setDOMEvents();
  8922. },
  8923. /**
  8924. * Add crossbrowser support for chartX and chartY
  8925. * @param {Object} e The event object in standard browsers
  8926. */
  8927. normalize: function (e, chartPosition) {
  8928. var chartX,
  8929. chartY,
  8930. ePos;
  8931. // IE normalizing
  8932. e = e || win.event;
  8933. if (!e.target) {
  8934. e.target = e.srcElement;
  8935. }
  8936. // iOS (#2757)
  8937. ePos = e.touches ? (e.touches.length ? e.touches.item(0) : e.changedTouches[0]) : e;
  8938. // Get mouse position
  8939. if (!chartPosition) {
  8940. this.chartPosition = chartPosition = offset(this.chart.container);
  8941. }
  8942. // chartX and chartY
  8943. if (ePos.pageX === UNDEFINED) { // IE < 9. #886.
  8944. chartX = mathMax(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is
  8945. // for IE10 quirks mode within framesets
  8946. chartY = e.y;
  8947. } else {
  8948. chartX = ePos.pageX - chartPosition.left;
  8949. chartY = ePos.pageY - chartPosition.top;
  8950. }
  8951. return extend(e, {
  8952. chartX: mathRound(chartX),
  8953. chartY: mathRound(chartY)
  8954. });
  8955. },
  8956. /**
  8957. * Get the click position in terms of axis values.
  8958. *
  8959. * @param {Object} e A pointer event
  8960. */
  8961. getCoordinates: function (e) {
  8962. var coordinates = {
  8963. xAxis: [],
  8964. yAxis: []
  8965. };
  8966. each(this.chart.axes, function (axis) {
  8967. coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({
  8968. axis: axis,
  8969. value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY'])
  8970. });
  8971. });
  8972. return coordinates;
  8973. },
  8974. /**
  8975. * With line type charts with a single tracker, get the point closest to the mouse.
  8976. * Run Point.onMouseOver and display tooltip for the point or points.
  8977. */
  8978. runPointActions: function (e) {
  8979. var pointer = this,
  8980. chart = pointer.chart,
  8981. series = chart.series,
  8982. tooltip = chart.tooltip,
  8983. shared = tooltip ? tooltip.shared : false,
  8984. followPointer,
  8985. updatePosition = true,
  8986. hoverPoint = chart.hoverPoint,
  8987. hoverSeries = chart.hoverSeries,
  8988. i,
  8989. anchor,
  8990. noSharedTooltip,
  8991. stickToHoverSeries,
  8992. directTouch,
  8993. kdpoints = [],
  8994. kdpointT;
  8995. // For hovering over the empty parts of the plot area (hoverSeries is undefined).
  8996. // If there is one series with point tracking (combo chart), don't go to nearest neighbour.
  8997. if (!shared && !hoverSeries) {
  8998. for (i = 0; i < series.length; i++) {
  8999. if (series[i].directTouch || !series[i].options.stickyTracking) {
  9000. series = [];
  9001. }
  9002. }
  9003. }
  9004. // If it has a hoverPoint and that series requires direct touch (like columns, #3899), or we're on
  9005. // a noSharedTooltip series among shared tooltip series (#4546), use the hoverPoint . Otherwise,
  9006. // search the k-d tree.
  9007. stickToHoverSeries = hoverSeries && (shared ? hoverSeries.noSharedTooltip : hoverSeries.directTouch);
  9008. if (stickToHoverSeries && hoverPoint) {
  9009. kdpoints = [hoverPoint];
  9010. // Handle shared tooltip or cases where a series is not yet hovered
  9011. } else {
  9012. // When we have non-shared tooltip and sticky tracking is disabled,
  9013. // search for the closest point only on hovered series: #5533, #5476
  9014. if (!shared && hoverSeries && !hoverSeries.options.stickyTracking) {
  9015. series = [hoverSeries];
  9016. }
  9017. // Find nearest points on all series
  9018. each(series, function (s) {
  9019. // Skip hidden series
  9020. noSharedTooltip = s.noSharedTooltip && shared;
  9021. directTouch = !shared && s.directTouch;
  9022. if (s.visible && !noSharedTooltip && !directTouch && pick(s.options.enableMouseTracking, true)) { // #3821
  9023. kdpointT = s.searchPoint(e, !noSharedTooltip && s.kdDimensions === 1); // #3828
  9024. if (kdpointT && kdpointT.series) { // Point.series becomes null when reset and before redraw (#5197)
  9025. kdpoints.push(kdpointT);
  9026. }
  9027. }
  9028. });
  9029. // Sort kdpoints by distance to mouse pointer
  9030. kdpoints.sort(function (p1, p2) {
  9031. var isCloserX = p1.distX - p2.distX,
  9032. isCloser = p1.dist - p2.dist,
  9033. isAbove = p1.series.group.zIndex > p2.series.group.zIndex ? -1 : 1;
  9034. // We have two points which are not in the same place on xAxis and shared tooltip:
  9035. if (isCloserX !== 0) {
  9036. return isCloserX;
  9037. }
  9038. // Points are not exactly in the same place on x/yAxis:
  9039. if (isCloser !== 0) {
  9040. return isCloser;
  9041. }
  9042. // The same xAxis and yAxis position, sort by z-index:
  9043. return isAbove;
  9044. });
  9045. }
  9046. // Remove points with different x-positions, required for shared tooltip and crosshairs (#4645):
  9047. if (shared) {
  9048. i = kdpoints.length;
  9049. while (i--) {
  9050. if (kdpoints[i].clientX !== kdpoints[0].clientX || kdpoints[i].series.noSharedTooltip) {
  9051. kdpoints.splice(i, 1);
  9052. }
  9053. }
  9054. }
  9055. // Refresh tooltip for kdpoint if new hover point or tooltip was hidden // #3926, #4200
  9056. if (kdpoints[0] && (kdpoints[0] !== pointer.hoverPoint || (tooltip && tooltip.isHidden))) {
  9057. // Draw tooltip if necessary
  9058. if (shared && !kdpoints[0].series.noSharedTooltip) {
  9059. // Do mouseover on all points (#3919, #3985, #4410)
  9060. for (i = 0; i >= 0; i--) {
  9061. kdpoints[i].onMouseOver(e, kdpoints[i] !== ((hoverSeries && hoverSeries.directTouch && hoverPoint) || kdpoints[0]));
  9062. }
  9063. // Make sure that the hoverPoint and hoverSeries are stored for events (e.g. click), #5622
  9064. if (hoverSeries && hoverSeries.directTouch && hoverPoint && hoverPoint !== kdpoints[0]) {
  9065. hoverPoint.onMouseOver(e, false);
  9066. }
  9067. if (kdpoints.length && tooltip) {
  9068. // Keep the order of series in tooltip:
  9069. tooltip.refresh(kdpoints.sort(function (p1, p2) {
  9070. return p1.series.index - p2.series.index;
  9071. }), e);
  9072. }
  9073. } else {
  9074. if (tooltip) {
  9075. tooltip.refresh(kdpoints[0], e);
  9076. }
  9077. if (!hoverSeries || !hoverSeries.directTouch) { // #4448
  9078. kdpoints[0].onMouseOver(e);
  9079. }
  9080. }
  9081. pointer.prevKDPoint = kdpoints[0];
  9082. updatePosition = false;
  9083. }
  9084. // Update positions (regardless of kdpoint or hoverPoint)
  9085. if (updatePosition) {
  9086. followPointer = hoverSeries && hoverSeries.tooltipOptions.followPointer;
  9087. if (tooltip && followPointer && !tooltip.isHidden) {
  9088. anchor = tooltip.getAnchor([{}], e);
  9089. tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] });
  9090. }
  9091. }
  9092. // Start the event listener to pick up the tooltip and crosshairs
  9093. if (!pointer._onDocumentMouseMove) {
  9094. pointer._onDocumentMouseMove = function (e) {
  9095. if (charts[hoverChartIndex]) {
  9096. charts[hoverChartIndex].pointer.onDocumentMouseMove(e);
  9097. }
  9098. };
  9099. addEvent(doc, 'mousemove', pointer._onDocumentMouseMove);
  9100. }
  9101. // Crosshair. For each hover point, loop over axes and draw cross if that point
  9102. // belongs to the axis (#4927).
  9103. each(shared ? kdpoints : [pick(hoverPoint, kdpoints[0])], function drawPointCrosshair(point) { // #5269
  9104. each(chart.axes, function drawAxisCrosshair(axis) {
  9105. // In case of snap = false, point is undefined, and we draw the crosshair anyway (#5066)
  9106. if (!point || point.series && point.series[axis.coll] === axis) { // #5658
  9107. axis.drawCrosshair(e, point);
  9108. }
  9109. });
  9110. });
  9111. },
  9112. /**
  9113. * Reset the tracking by hiding the tooltip, the hover series state and the hover point
  9114. *
  9115. * @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible
  9116. */
  9117. reset: function (allowMove, delay) {
  9118. var pointer = this,
  9119. chart = pointer.chart,
  9120. hoverSeries = chart.hoverSeries,
  9121. hoverPoint = chart.hoverPoint,
  9122. hoverPoints = chart.hoverPoints,
  9123. tooltip = chart.tooltip,
  9124. tooltipPoints = tooltip && tooltip.shared ? hoverPoints : hoverPoint;
  9125. // Check if the points have moved outside the plot area (#1003, #4736, #5101)
  9126. if (allowMove && tooltipPoints) {
  9127. each(splat(tooltipPoints), function (point) {
  9128. if (point.series.isCartesian && point.plotX === undefined) {
  9129. allowMove = false;
  9130. }
  9131. });
  9132. }
  9133. // Just move the tooltip, #349
  9134. if (allowMove) {
  9135. if (tooltip && tooltipPoints) {
  9136. tooltip.refresh(tooltipPoints);
  9137. if (hoverPoint) { // #2500
  9138. hoverPoint.setState(hoverPoint.state, true);
  9139. each(chart.axes, function (axis) {
  9140. if (axis.crosshair) {
  9141. axis.drawCrosshair(null, hoverPoint);
  9142. }
  9143. });
  9144. }
  9145. }
  9146. // Full reset
  9147. } else {
  9148. if (hoverPoint) {
  9149. hoverPoint.onMouseOut();
  9150. }
  9151. if (hoverPoints) {
  9152. each(hoverPoints, function (point) {
  9153. point.setState();
  9154. });
  9155. }
  9156. if (hoverSeries) {
  9157. hoverSeries.onMouseOut();
  9158. }
  9159. if (tooltip) {
  9160. tooltip.hide(delay);
  9161. }
  9162. if (pointer._onDocumentMouseMove) {
  9163. removeEvent(doc, 'mousemove', pointer._onDocumentMouseMove);
  9164. pointer._onDocumentMouseMove = null;
  9165. }
  9166. // Remove crosshairs
  9167. each(chart.axes, function (axis) {
  9168. axis.hideCrosshair();
  9169. });
  9170. pointer.hoverX = pointer.prevKDPoint = chart.hoverPoints = chart.hoverPoint = null;
  9171. }
  9172. },
  9173. /**
  9174. * Scale series groups to a certain scale and translation
  9175. */
  9176. scaleGroups: function (attribs, clip) {
  9177. var chart = this.chart,
  9178. seriesAttribs;
  9179. // Scale each series
  9180. each(chart.series, function (series) {
  9181. seriesAttribs = attribs || series.getPlotBox(); // #1701
  9182. if (series.xAxis && series.xAxis.zoomEnabled) {
  9183. series.group.attr(seriesAttribs);
  9184. if (series.markerGroup) {
  9185. series.markerGroup.attr(seriesAttribs);
  9186. series.markerGroup.clip(clip ? chart.clipRect : null);
  9187. }
  9188. if (series.dataLabelsGroup) {
  9189. series.dataLabelsGroup.attr(seriesAttribs);
  9190. }
  9191. }
  9192. });
  9193. // Clip
  9194. chart.clipRect.attr(clip || chart.clipBox);
  9195. },
  9196. /**
  9197. * Start a drag operation
  9198. */
  9199. dragStart: function (e) {
  9200. var chart = this.chart;
  9201. // Record the start position
  9202. chart.mouseIsDown = e.type;
  9203. chart.cancelClick = false;
  9204. chart.mouseDownX = this.mouseDownX = e.chartX;
  9205. chart.mouseDownY = this.mouseDownY = e.chartY;
  9206. },
  9207. /**
  9208. * Perform a drag operation in response to a mousemove event while the mouse is down
  9209. */
  9210. drag: function (e) {
  9211. var chart = this.chart,
  9212. chartOptions = chart.options.chart,
  9213. chartX = e.chartX,
  9214. chartY = e.chartY,
  9215. zoomHor = this.zoomHor,
  9216. zoomVert = this.zoomVert,
  9217. plotLeft = chart.plotLeft,
  9218. plotTop = chart.plotTop,
  9219. plotWidth = chart.plotWidth,
  9220. plotHeight = chart.plotHeight,
  9221. clickedInside,
  9222. size,
  9223. selectionMarker = this.selectionMarker,
  9224. mouseDownX = this.mouseDownX,
  9225. mouseDownY = this.mouseDownY,
  9226. panKey = chartOptions.panKey && e[chartOptions.panKey + 'Key'];
  9227. // If the device supports both touch and mouse (like IE11), and we are touch-dragging
  9228. // inside the plot area, don't handle the mouse event. #4339.
  9229. if (selectionMarker && selectionMarker.touch) {
  9230. return;
  9231. }
  9232. // If the mouse is outside the plot area, adjust to cooordinates
  9233. // inside to prevent the selection marker from going outside
  9234. if (chartX < plotLeft) {
  9235. chartX = plotLeft;
  9236. } else if (chartX > plotLeft + plotWidth) {
  9237. chartX = plotLeft + plotWidth;
  9238. }
  9239. if (chartY < plotTop) {
  9240. chartY = plotTop;
  9241. } else if (chartY > plotTop + plotHeight) {
  9242. chartY = plotTop + plotHeight;
  9243. }
  9244. // determine if the mouse has moved more than 10px
  9245. this.hasDragged = Math.sqrt(
  9246. Math.pow(mouseDownX - chartX, 2) +
  9247. Math.pow(mouseDownY - chartY, 2)
  9248. );
  9249. if (this.hasDragged > 10) {
  9250. clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop);
  9251. // make a selection
  9252. if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside && !panKey) {
  9253. if (!selectionMarker) {
  9254. this.selectionMarker = selectionMarker = chart.renderer.rect(
  9255. plotLeft,
  9256. plotTop,
  9257. zoomHor ? 1 : plotWidth,
  9258. zoomVert ? 1 : plotHeight,
  9259. 0
  9260. )
  9261. .attr({
  9262. fill: chartOptions.selectionMarkerFill || 'rgba(69,114,167,0.25)',
  9263. zIndex: 7
  9264. })
  9265. .add();
  9266. }
  9267. }
  9268. // adjust the width of the selection marker
  9269. if (selectionMarker && zoomHor) {
  9270. size = chartX - mouseDownX;
  9271. selectionMarker.attr({
  9272. width: mathAbs(size),
  9273. x: (size > 0 ? 0 : size) + mouseDownX
  9274. });
  9275. }
  9276. // adjust the height of the selection marker
  9277. if (selectionMarker && zoomVert) {
  9278. size = chartY - mouseDownY;
  9279. selectionMarker.attr({
  9280. height: mathAbs(size),
  9281. y: (size > 0 ? 0 : size) + mouseDownY
  9282. });
  9283. }
  9284. // panning
  9285. if (clickedInside && !selectionMarker && chartOptions.panning) {
  9286. chart.pan(e, chartOptions.panning);
  9287. }
  9288. }
  9289. },
  9290. /**
  9291. * On mouse up or touch end across the entire document, drop the selection.
  9292. */
  9293. drop: function (e) {
  9294. var pointer = this,
  9295. chart = this.chart,
  9296. hasPinched = this.hasPinched;
  9297. if (this.selectionMarker) {
  9298. var selectionData = {
  9299. originalEvent: e, // #4890
  9300. xAxis: [],
  9301. yAxis: []
  9302. },
  9303. selectionBox = this.selectionMarker,
  9304. selectionLeft = selectionBox.attr ? selectionBox.attr('x') : selectionBox.x,
  9305. selectionTop = selectionBox.attr ? selectionBox.attr('y') : selectionBox.y,
  9306. selectionWidth = selectionBox.attr ? selectionBox.attr('width') : selectionBox.width,
  9307. selectionHeight = selectionBox.attr ? selectionBox.attr('height') : selectionBox.height,
  9308. runZoom;
  9309. // a selection has been made
  9310. if (this.hasDragged || hasPinched) {
  9311. // record each axis' min and max
  9312. each(chart.axes, function (axis) {
  9313. if (axis.zoomEnabled && defined(axis.min) && (hasPinched || pointer[{ xAxis: 'zoomX', yAxis: 'zoomY' }[axis.coll]])) { // #859, #3569
  9314. var horiz = axis.horiz,
  9315. minPixelPadding = e.type === 'touchend' ? axis.minPixelPadding : 0, // #1207, #3075
  9316. selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop) + minPixelPadding),
  9317. selectionMax = axis.toValue((horiz ? selectionLeft + selectionWidth : selectionTop + selectionHeight) - minPixelPadding);
  9318. selectionData[axis.coll].push({
  9319. axis: axis,
  9320. min: mathMin(selectionMin, selectionMax), // for reversed axes
  9321. max: mathMax(selectionMin, selectionMax)
  9322. });
  9323. runZoom = true;
  9324. }
  9325. });
  9326. if (runZoom) {
  9327. fireEvent(chart, 'selection', selectionData, function (args) {
  9328. chart.zoom(extend(args, hasPinched ? { animation: false } : null));
  9329. });
  9330. }
  9331. }
  9332. this.selectionMarker = this.selectionMarker.destroy();
  9333. // Reset scaling preview
  9334. if (hasPinched) {
  9335. this.scaleGroups();
  9336. }
  9337. }
  9338. // Reset all
  9339. if (chart) { // it may be destroyed on mouse up - #877
  9340. css(chart.container, { cursor: chart._cursor });
  9341. chart.cancelClick = this.hasDragged > 10; // #370
  9342. chart.mouseIsDown = this.hasDragged = this.hasPinched = false;
  9343. this.pinchDown = [];
  9344. }
  9345. },
  9346. onContainerMouseDown: function (e) {
  9347. e = this.normalize(e);
  9348. // issue #295, dragging not always working in Firefox
  9349. if (e.preventDefault) {
  9350. e.preventDefault();
  9351. }
  9352. this.dragStart(e);
  9353. },
  9354. onDocumentMouseUp: function (e) {
  9355. if (charts[hoverChartIndex]) {
  9356. charts[hoverChartIndex].pointer.drop(e);
  9357. }
  9358. },
  9359. /**
  9360. * Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea.
  9361. * Issue #149 workaround. The mouseleave event does not always fire.
  9362. */
  9363. onDocumentMouseMove: function (e) {
  9364. var chart = this.chart,
  9365. chartPosition = this.chartPosition;
  9366. e = this.normalize(e, chartPosition);
  9367. // If we're outside, hide the tooltip
  9368. if (chartPosition && !this.inClass(e.target, 'highcharts-tracker') &&
  9369. !chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
  9370. this.reset();
  9371. }
  9372. },
  9373. /**
  9374. * When mouse leaves the container, hide the tooltip.
  9375. */
  9376. onContainerMouseLeave: function (e) {
  9377. var chart = charts[hoverChartIndex];
  9378. if (chart && (e.relatedTarget || e.toElement)) { // #4886, MS Touch end fires mouseleave but with no related target
  9379. chart.pointer.reset();
  9380. chart.pointer.chartPosition = null; // also reset the chart position, used in #149 fix
  9381. }
  9382. },
  9383. // The mousemove, touchmove and touchstart event handler
  9384. onContainerMouseMove: function (e) {
  9385. var chart = this.chart;
  9386. if (!defined(hoverChartIndex) || !charts[hoverChartIndex] || !charts[hoverChartIndex].mouseIsDown) {
  9387. hoverChartIndex = chart.index;
  9388. }
  9389. e = this.normalize(e);
  9390. e.returnValue = false; // #2251, #3224
  9391. if (chart.mouseIsDown === 'mousedown') {
  9392. this.drag(e);
  9393. }
  9394. // Show the tooltip and run mouse over events (#977)
  9395. if ((this.inClass(e.target, 'highcharts-tracker') ||
  9396. chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) {
  9397. this.runPointActions(e);
  9398. }
  9399. },
  9400. /**
  9401. * Utility to detect whether an element has, or has a parent with, a specific
  9402. * class name. Used on detection of tracker objects and on deciding whether
  9403. * hovering the tooltip should cause the active series to mouse out.
  9404. */
  9405. inClass: function (element, className) {
  9406. var elemClassName;
  9407. while (element) {
  9408. elemClassName = attr(element, 'class');
  9409. if (elemClassName) {
  9410. if (elemClassName.indexOf(className) !== -1) {
  9411. return true;
  9412. }
  9413. if (elemClassName.indexOf(PREFIX + 'container') !== -1) {
  9414. return false;
  9415. }
  9416. }
  9417. element = element.parentNode;
  9418. }
  9419. },
  9420. onTrackerMouseOut: function (e) {
  9421. var series = this.chart.hoverSeries,
  9422. relatedTarget = e.relatedTarget || e.toElement;
  9423. if (series && relatedTarget && !series.options.stickyTracking && // #4886
  9424. !this.inClass(relatedTarget, PREFIX + 'tooltip') &&
  9425. !this.inClass(relatedTarget, PREFIX + 'series-' + series.index)) { // #2499, #4465
  9426. series.onMouseOut();
  9427. }
  9428. },
  9429. onContainerClick: function (e) {
  9430. var chart = this.chart,
  9431. hoverPoint = chart.hoverPoint,
  9432. plotLeft = chart.plotLeft,
  9433. plotTop = chart.plotTop;
  9434. e = this.normalize(e);
  9435. if (!chart.cancelClick) {
  9436. // On tracker click, fire the series and point events. #783, #1583
  9437. if (hoverPoint && this.inClass(e.target, PREFIX + 'tracker')) {
  9438. // the series click event
  9439. fireEvent(hoverPoint.series, 'click', extend(e, {
  9440. point: hoverPoint
  9441. }));
  9442. // the point click event
  9443. if (chart.hoverPoint) { // it may be destroyed (#1844)
  9444. hoverPoint.firePointEvent('click', e);
  9445. }
  9446. // When clicking outside a tracker, fire a chart event
  9447. } else {
  9448. extend(e, this.getCoordinates(e));
  9449. // fire a click event in the chart
  9450. if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) {
  9451. fireEvent(chart, 'click', e);
  9452. }
  9453. }
  9454. }
  9455. },
  9456. /**
  9457. * Set the JS DOM events on the container and document. This method should contain
  9458. * a one-to-one assignment between methods and their handlers. Any advanced logic should
  9459. * be moved to the handler reflecting the event's name.
  9460. */
  9461. setDOMEvents: function () {
  9462. var pointer = this,
  9463. container = pointer.chart.container;
  9464. container.onmousedown = function (e) {
  9465. pointer.onContainerMouseDown(e);
  9466. };
  9467. container.onmousemove = function (e) {
  9468. pointer.onContainerMouseMove(e);
  9469. };
  9470. container.onclick = function (e) {
  9471. pointer.onContainerClick(e);
  9472. };
  9473. addEvent(container, 'mouseleave', pointer.onContainerMouseLeave);
  9474. if (chartCount === 1) {
  9475. addEvent(doc, 'mouseup', pointer.onDocumentMouseUp);
  9476. }
  9477. if (hasTouch) {
  9478. container.ontouchstart = function (e) {
  9479. pointer.onContainerTouchStart(e);
  9480. };
  9481. container.ontouchmove = function (e) {
  9482. pointer.onContainerTouchMove(e);
  9483. };
  9484. if (chartCount === 1) {
  9485. addEvent(doc, 'touchend', pointer.onDocumentTouchEnd);
  9486. }
  9487. }
  9488. },
  9489. /**
  9490. * Destroys the Pointer object and disconnects DOM events.
  9491. */
  9492. destroy: function () {
  9493. var prop;
  9494. removeEvent(this.chart.container, 'mouseleave', this.onContainerMouseLeave);
  9495. if (!chartCount) {
  9496. removeEvent(doc, 'mouseup', this.onDocumentMouseUp);
  9497. removeEvent(doc, 'touchend', this.onDocumentTouchEnd);
  9498. }
  9499. // memory and CPU leak
  9500. clearInterval(this.tooltipTimeout);
  9501. for (prop in this) {
  9502. this[prop] = null;
  9503. }
  9504. }
  9505. };
  9506. /* Support for touch devices */
  9507. extend(Highcharts.Pointer.prototype, {
  9508. /**
  9509. * Run translation operations
  9510. */
  9511. pinchTranslate: function (pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) {
  9512. if (this.zoomHor || this.pinchHor) {
  9513. this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
  9514. }
  9515. if (this.zoomVert || this.pinchVert) {
  9516. this.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
  9517. }
  9518. },
  9519. /**
  9520. * Run translation operations for each direction (horizontal and vertical) independently
  9521. */
  9522. pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch, forcedScale) {
  9523. var chart = this.chart,
  9524. xy = horiz ? 'x' : 'y',
  9525. XY = horiz ? 'X' : 'Y',
  9526. sChartXY = 'chart' + XY,
  9527. wh = horiz ? 'width' : 'height',
  9528. plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')],
  9529. selectionWH,
  9530. selectionXY,
  9531. clipXY,
  9532. scale = forcedScale || 1,
  9533. inverted = chart.inverted,
  9534. bounds = chart.bounds[horiz ? 'h' : 'v'],
  9535. singleTouch = pinchDown.length === 1,
  9536. touch0Start = pinchDown[0][sChartXY],
  9537. touch0Now = touches[0][sChartXY],
  9538. touch1Start = !singleTouch && pinchDown[1][sChartXY],
  9539. touch1Now = !singleTouch && touches[1][sChartXY],
  9540. outOfBounds,
  9541. transformScale,
  9542. scaleKey,
  9543. setScale = function () {
  9544. if (!singleTouch && mathAbs(touch0Start - touch1Start) > 20) { // Don't zoom if fingers are too close on this axis
  9545. scale = forcedScale || mathAbs(touch0Now - touch1Now) / mathAbs(touch0Start - touch1Start);
  9546. }
  9547. clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start;
  9548. selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale;
  9549. };
  9550. // Set the scale, first pass
  9551. setScale();
  9552. selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not
  9553. // Out of bounds
  9554. if (selectionXY < bounds.min) {
  9555. selectionXY = bounds.min;
  9556. outOfBounds = true;
  9557. } else if (selectionXY + selectionWH > bounds.max) {
  9558. selectionXY = bounds.max - selectionWH;
  9559. outOfBounds = true;
  9560. }
  9561. // Is the chart dragged off its bounds, determined by dataMin and dataMax?
  9562. if (outOfBounds) {
  9563. // Modify the touchNow position in order to create an elastic drag movement. This indicates
  9564. // to the user that the chart is responsive but can't be dragged further.
  9565. touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]);
  9566. if (!singleTouch) {
  9567. touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]);
  9568. }
  9569. // Set the scale, second pass to adapt to the modified touchNow positions
  9570. setScale();
  9571. } else {
  9572. lastValidTouch[xy] = [touch0Now, touch1Now];
  9573. }
  9574. // Set geometry for clipping, selection and transformation
  9575. if (!inverted) {
  9576. clip[xy] = clipXY - plotLeftTop;
  9577. clip[wh] = selectionWH;
  9578. }
  9579. scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY;
  9580. transformScale = inverted ? 1 / scale : scale;
  9581. selectionMarker[wh] = selectionWH;
  9582. selectionMarker[xy] = selectionXY;
  9583. transform[scaleKey] = scale;
  9584. transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start));
  9585. },
  9586. /**
  9587. * Handle touch events with two touches
  9588. */
  9589. pinch: function (e) {
  9590. var self = this,
  9591. chart = self.chart,
  9592. pinchDown = self.pinchDown,
  9593. touches = e.touches,
  9594. touchesLength = touches.length,
  9595. lastValidTouch = self.lastValidTouch,
  9596. hasZoom = self.hasZoom,
  9597. selectionMarker = self.selectionMarker,
  9598. transform = {},
  9599. fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, PREFIX + 'tracker') &&
  9600. chart.runTrackerClick) || self.runChartClick),
  9601. clip = {};
  9602. // Don't initiate panning until the user has pinched. This prevents us from
  9603. // blocking page scrolling as users scroll down a long page (#4210).
  9604. if (touchesLength > 1) {
  9605. self.initiated = true;
  9606. }
  9607. // On touch devices, only proceed to trigger click if a handler is defined
  9608. if (hasZoom && self.initiated && !fireClickEvent) {
  9609. e.preventDefault();
  9610. }
  9611. // Normalize each touch
  9612. map(touches, function (e) {
  9613. return self.normalize(e);
  9614. });
  9615. // Register the touch start position
  9616. if (e.type === 'touchstart') {
  9617. each(touches, function (e, i) {
  9618. pinchDown[i] = { chartX: e.chartX, chartY: e.chartY };
  9619. });
  9620. lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX];
  9621. lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY];
  9622. // Identify the data bounds in pixels
  9623. each(chart.axes, function (axis) {
  9624. if (axis.zoomEnabled) {
  9625. var bounds = chart.bounds[axis.horiz ? 'h' : 'v'],
  9626. minPixelPadding = axis.minPixelPadding,
  9627. min = axis.toPixels(pick(axis.options.min, axis.dataMin)),
  9628. max = axis.toPixels(pick(axis.options.max, axis.dataMax)),
  9629. absMin = mathMin(min, max),
  9630. absMax = mathMax(min, max);
  9631. // Store the bounds for use in the touchmove handler
  9632. bounds.min = mathMin(axis.pos, absMin - minPixelPadding);
  9633. bounds.max = mathMax(axis.pos + axis.len, absMax + minPixelPadding);
  9634. }
  9635. });
  9636. self.res = true; // reset on next move
  9637. // Event type is touchmove, handle panning and pinching
  9638. } else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first
  9639. // Set the marker
  9640. if (!selectionMarker) {
  9641. self.selectionMarker = selectionMarker = extend({
  9642. destroy: noop,
  9643. touch: true
  9644. }, chart.plotBox);
  9645. }
  9646. self.pinchTranslate(pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
  9647. self.hasPinched = hasZoom;
  9648. // Scale and translate the groups to provide visual feedback during pinching
  9649. self.scaleGroups(transform, clip);
  9650. // Optionally move the tooltip on touchmove
  9651. if (!hasZoom && self.followTouchMove && touchesLength === 1) {
  9652. this.runPointActions(self.normalize(e));
  9653. } else if (self.res) {
  9654. self.res = false;
  9655. this.reset(false, 0);
  9656. }
  9657. }
  9658. },
  9659. /**
  9660. * General touch handler shared by touchstart and touchmove.
  9661. */
  9662. touch: function (e, start) {
  9663. var chart = this.chart,
  9664. hasMoved,
  9665. pinchDown;
  9666. hoverChartIndex = chart.index;
  9667. if (e.touches.length === 1) {
  9668. e = this.normalize(e);
  9669. if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop) && !chart.openMenu) {
  9670. // Run mouse events and display tooltip etc
  9671. if (start) {
  9672. this.runPointActions(e);
  9673. }
  9674. // Android fires touchmove events after the touchstart even if the
  9675. // finger hasn't moved, or moved only a pixel or two. In iOS however,
  9676. // the touchmove doesn't fire unless the finger moves more than ~4px.
  9677. // So we emulate this behaviour in Android by checking how much it
  9678. // moved, and cancelling on small distances. #3450.
  9679. if (e.type === 'touchmove') {
  9680. pinchDown = this.pinchDown;
  9681. hasMoved = pinchDown[0] ? Math.sqrt( // #5266
  9682. Math.pow(pinchDown[0].chartX - e.chartX, 2) +
  9683. Math.pow(pinchDown[0].chartY - e.chartY, 2)
  9684. ) >= 4 : false;
  9685. }
  9686. if (pick(hasMoved, true)) {
  9687. this.pinch(e);
  9688. }
  9689. } else if (start) {
  9690. // Hide the tooltip on touching outside the plot area (#1203)
  9691. this.reset();
  9692. }
  9693. } else if (e.touches.length === 2) {
  9694. this.pinch(e);
  9695. }
  9696. },
  9697. onContainerTouchStart: function (e) {
  9698. this.touch(e, true);
  9699. },
  9700. onContainerTouchMove: function (e) {
  9701. this.touch(e);
  9702. },
  9703. onDocumentTouchEnd: function (e) {
  9704. if (charts[hoverChartIndex]) {
  9705. charts[hoverChartIndex].pointer.drop(e);
  9706. }
  9707. }
  9708. });
  9709. if (win.PointerEvent || win.MSPointerEvent) {
  9710. // The touches object keeps track of the points being touched at all times
  9711. var touches = {},
  9712. hasPointerEvent = !!win.PointerEvent,
  9713. getWebkitTouches = function () {
  9714. var key,
  9715. fake = [];
  9716. fake.item = function (i) {
  9717. return this[i];
  9718. };
  9719. for (key in touches) {
  9720. if (touches.hasOwnProperty(key)) {
  9721. fake.push({
  9722. pageX: touches[key].pageX,
  9723. pageY: touches[key].pageY,
  9724. target: touches[key].target
  9725. });
  9726. }
  9727. }
  9728. return fake;
  9729. },
  9730. translateMSPointer = function (e, method, wktype, func) {
  9731. var p;
  9732. if ((e.pointerType === 'touch' || e.pointerType === e.MSPOINTER_TYPE_TOUCH) && charts[hoverChartIndex]) {
  9733. func(e);
  9734. p = charts[hoverChartIndex].pointer;
  9735. p[method]({
  9736. type: wktype,
  9737. target: e.currentTarget,
  9738. preventDefault: noop,
  9739. touches: getWebkitTouches()
  9740. });
  9741. }
  9742. };
  9743. /**
  9744. * Extend the Pointer prototype with methods for each event handler and more
  9745. */
  9746. extend(Pointer.prototype, {
  9747. onContainerPointerDown: function (e) {
  9748. translateMSPointer(e, 'onContainerTouchStart', 'touchstart', function (e) {
  9749. touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY, target: e.currentTarget };
  9750. });
  9751. },
  9752. onContainerPointerMove: function (e) {
  9753. translateMSPointer(e, 'onContainerTouchMove', 'touchmove', function (e) {
  9754. touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY };
  9755. if (!touches[e.pointerId].target) {
  9756. touches[e.pointerId].target = e.currentTarget;
  9757. }
  9758. });
  9759. },
  9760. onDocumentPointerUp: function (e) {
  9761. translateMSPointer(e, 'onDocumentTouchEnd', 'touchend', function (e) {
  9762. delete touches[e.pointerId];
  9763. });
  9764. },
  9765. /**
  9766. * Add or remove the MS Pointer specific events
  9767. */
  9768. batchMSEvents: function (fn) {
  9769. fn(this.chart.container, hasPointerEvent ? 'pointerdown' : 'MSPointerDown', this.onContainerPointerDown);
  9770. fn(this.chart.container, hasPointerEvent ? 'pointermove' : 'MSPointerMove', this.onContainerPointerMove);
  9771. fn(doc, hasPointerEvent ? 'pointerup' : 'MSPointerUp', this.onDocumentPointerUp);
  9772. }
  9773. });
  9774. // Disable default IE actions for pinch and such on chart element
  9775. wrap(Pointer.prototype, 'init', function (proceed, chart, options) {
  9776. proceed.call(this, chart, options);
  9777. if (this.hasZoom) { // #4014
  9778. css(chart.container, {
  9779. '-ms-touch-action': NONE,
  9780. 'touch-action': NONE
  9781. });
  9782. }
  9783. });
  9784. // Add IE specific touch events to chart
  9785. wrap(Pointer.prototype, 'setDOMEvents', function (proceed) {
  9786. proceed.apply(this);
  9787. if (this.hasZoom || this.followTouchMove) {
  9788. this.batchMSEvents(addEvent);
  9789. }
  9790. });
  9791. // Destroy MS events also
  9792. wrap(Pointer.prototype, 'destroy', function (proceed) {
  9793. this.batchMSEvents(removeEvent);
  9794. proceed.call(this);
  9795. });
  9796. }
  9797. /**
  9798. * The overview of the chart's series
  9799. */
  9800. var Legend = Highcharts.Legend = function (chart, options) {
  9801. this.init(chart, options);
  9802. };
  9803. Legend.prototype = {
  9804. /**
  9805. * Initialize the legend
  9806. */
  9807. init: function (chart, options) {
  9808. var legend = this,
  9809. itemStyle = options.itemStyle,
  9810. padding,
  9811. itemMarginTop = options.itemMarginTop || 0;
  9812. this.options = options;
  9813. if (!options.enabled) {
  9814. return;
  9815. }
  9816. legend.itemStyle = itemStyle;
  9817. legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle);
  9818. legend.itemMarginTop = itemMarginTop;
  9819. legend.padding = padding = pick(options.padding, 8);
  9820. legend.initialItemX = padding;
  9821. legend.initialItemY = padding - 5; // 5 is the number of pixels above the text
  9822. legend.maxItemWidth = 0;
  9823. legend.chart = chart;
  9824. legend.itemHeight = 0;
  9825. legend.symbolWidth = pick(options.symbolWidth, 16);
  9826. legend.pages = [];
  9827. // Render it
  9828. legend.render();
  9829. // move checkboxes
  9830. addEvent(legend.chart, 'endResize', function () {
  9831. legend.positionCheckboxes();
  9832. });
  9833. },
  9834. /**
  9835. * Set the colors for the legend item
  9836. * @param {Object} item A Series or Point instance
  9837. * @param {Object} visible Dimmed or colored
  9838. */
  9839. colorizeItem: function (item, visible) {
  9840. var legend = this,
  9841. options = legend.options,
  9842. legendItem = item.legendItem,
  9843. legendLine = item.legendLine,
  9844. legendSymbol = item.legendSymbol,
  9845. hiddenColor = legend.itemHiddenStyle.color,
  9846. textColor = visible ? options.itemStyle.color : hiddenColor,
  9847. symbolColor = visible ? (item.legendColor || item.color || '#CCC') : hiddenColor,
  9848. markerOptions = item.options && item.options.marker,
  9849. symbolAttr = { fill: symbolColor },
  9850. key,
  9851. val;
  9852. if (legendItem) {
  9853. legendItem.css({ fill: textColor, color: textColor }); // color for #1553, oldIE
  9854. }
  9855. if (legendLine) {
  9856. legendLine.attr({ stroke: symbolColor });
  9857. }
  9858. if (legendSymbol) {
  9859. // Apply marker options
  9860. if (markerOptions && legendSymbol.isMarker) { // #585
  9861. symbolAttr.stroke = symbolColor;
  9862. markerOptions = item.convertAttribs(markerOptions);
  9863. for (key in markerOptions) {
  9864. val = markerOptions[key];
  9865. if (val !== UNDEFINED) {
  9866. symbolAttr[key] = val;
  9867. }
  9868. }
  9869. }
  9870. legendSymbol.attr(symbolAttr);
  9871. }
  9872. },
  9873. /**
  9874. * Position the legend item
  9875. * @param {Object} item A Series or Point instance
  9876. */
  9877. positionItem: function (item) {
  9878. var legend = this,
  9879. options = legend.options,
  9880. symbolPadding = options.symbolPadding,
  9881. ltr = !options.rtl,
  9882. legendItemPos = item._legendItemPos,
  9883. itemX = legendItemPos[0],
  9884. itemY = legendItemPos[1],
  9885. checkbox = item.checkbox,
  9886. legendGroup = item.legendGroup;
  9887. if (legendGroup && legendGroup.element) {
  9888. legendGroup.translate(
  9889. ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4,
  9890. itemY
  9891. );
  9892. }
  9893. if (checkbox) {
  9894. checkbox.x = itemX;
  9895. checkbox.y = itemY;
  9896. }
  9897. },
  9898. /**
  9899. * Destroy a single legend item
  9900. * @param {Object} item The series or point
  9901. */
  9902. destroyItem: function (item) {
  9903. var checkbox = item.checkbox;
  9904. // destroy SVG elements
  9905. each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) {
  9906. if (item[key]) {
  9907. item[key] = item[key].destroy();
  9908. }
  9909. });
  9910. if (checkbox) {
  9911. discardElement(item.checkbox);
  9912. }
  9913. },
  9914. /**
  9915. * Destroys the legend.
  9916. */
  9917. destroy: function () {
  9918. var legend = this,
  9919. legendGroup = legend.group,
  9920. box = legend.box;
  9921. if (box) {
  9922. legend.box = box.destroy();
  9923. }
  9924. if (legendGroup) {
  9925. legend.group = legendGroup.destroy();
  9926. }
  9927. },
  9928. /**
  9929. * Position the checkboxes after the width is determined
  9930. */
  9931. positionCheckboxes: function (scrollOffset) {
  9932. var alignAttr = this.group.alignAttr,
  9933. translateY,
  9934. clipHeight = this.clipHeight || this.legendHeight,
  9935. titleHeight = this.titleHeight;
  9936. if (alignAttr) {
  9937. translateY = alignAttr.translateY;
  9938. each(this.allItems, function (item) {
  9939. var checkbox = item.checkbox,
  9940. top;
  9941. if (checkbox) {
  9942. top = translateY + titleHeight + checkbox.y + (scrollOffset || 0) + 3;
  9943. css(checkbox, {
  9944. left: (alignAttr.translateX + item.checkboxOffset + checkbox.x - 20) + PX,
  9945. top: top + PX,
  9946. display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE
  9947. });
  9948. }
  9949. });
  9950. }
  9951. },
  9952. /**
  9953. * Render the legend title on top of the legend
  9954. */
  9955. renderTitle: function () {
  9956. var options = this.options,
  9957. padding = this.padding,
  9958. titleOptions = options.title,
  9959. titleHeight = 0,
  9960. bBox;
  9961. if (titleOptions.text) {
  9962. if (!this.title) {
  9963. this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title')
  9964. .attr({ zIndex: 1 })
  9965. .css(titleOptions.style)
  9966. .add(this.group);
  9967. }
  9968. bBox = this.title.getBBox();
  9969. titleHeight = bBox.height;
  9970. this.offsetWidth = bBox.width; // #1717
  9971. this.contentGroup.attr({ translateY: titleHeight });
  9972. }
  9973. this.titleHeight = titleHeight;
  9974. },
  9975. /**
  9976. * Set the legend item text
  9977. */
  9978. setText: function (item) {
  9979. var options = this.options;
  9980. item.legendItem.attr({
  9981. text: options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item)
  9982. });
  9983. },
  9984. /**
  9985. * Render a single specific legend item
  9986. * @param {Object} item A series or point
  9987. */
  9988. renderItem: function (item) {
  9989. var legend = this,
  9990. chart = legend.chart,
  9991. renderer = chart.renderer,
  9992. options = legend.options,
  9993. horizontal = options.layout === 'horizontal',
  9994. symbolWidth = legend.symbolWidth,
  9995. symbolPadding = options.symbolPadding,
  9996. itemStyle = legend.itemStyle,
  9997. itemHiddenStyle = legend.itemHiddenStyle,
  9998. padding = legend.padding,
  9999. itemDistance = horizontal ? pick(options.itemDistance, 20) : 0,
  10000. ltr = !options.rtl,
  10001. itemHeight,
  10002. widthOption = options.width,
  10003. itemMarginBottom = options.itemMarginBottom || 0,
  10004. itemMarginTop = legend.itemMarginTop,
  10005. initialItemX = legend.initialItemX,
  10006. bBox,
  10007. itemWidth,
  10008. li = item.legendItem,
  10009. series = item.series && item.series.drawLegendSymbol ? item.series : item,
  10010. seriesOptions = series.options,
  10011. showCheckbox = legend.createCheckboxForItem && seriesOptions && seriesOptions.showCheckbox,
  10012. useHTML = options.useHTML;
  10013. if (!li) { // generate it once, later move it
  10014. // Generate the group box
  10015. // A group to hold the symbol and text. Text is to be appended in Legend class.
  10016. item.legendGroup = renderer.g('legend-item')
  10017. .attr({ zIndex: 1 })
  10018. .add(legend.scrollGroup);
  10019. // Generate the list item text and add it to the group
  10020. item.legendItem = li = renderer.text(
  10021. '',
  10022. ltr ? symbolWidth + symbolPadding : -symbolPadding,
  10023. legend.baseline || 0,
  10024. useHTML
  10025. )
  10026. .css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021)
  10027. .attr({
  10028. align: ltr ? 'left' : 'right',
  10029. zIndex: 2
  10030. })
  10031. .add(item.legendGroup);
  10032. // Get the baseline for the first item - the font size is equal for all
  10033. if (!legend.baseline) {
  10034. legend.fontMetrics = renderer.fontMetrics(itemStyle.fontSize, li);
  10035. legend.baseline = legend.fontMetrics.f + 3 + itemMarginTop;
  10036. li.attr('y', legend.baseline);
  10037. }
  10038. // Draw the legend symbol inside the group box
  10039. series.drawLegendSymbol(legend, item);
  10040. if (legend.setItemEvents) {
  10041. legend.setItemEvents(item, li, useHTML, itemStyle, itemHiddenStyle);
  10042. }
  10043. // add the HTML checkbox on top
  10044. if (showCheckbox) {
  10045. legend.createCheckboxForItem(item);
  10046. }
  10047. }
  10048. // Colorize the items
  10049. legend.colorizeItem(item, item.visible);
  10050. // Always update the text
  10051. legend.setText(item);
  10052. // calculate the positions for the next line
  10053. bBox = li.getBBox();
  10054. itemWidth = item.checkboxOffset =
  10055. options.itemWidth ||
  10056. item.legendItemWidth ||
  10057. symbolWidth + symbolPadding + bBox.width + itemDistance + (showCheckbox ? 20 : 0);
  10058. legend.itemHeight = itemHeight = mathRound(item.legendItemHeight || bBox.height);
  10059. // if the item exceeds the width, start a new line
  10060. if (horizontal && legend.itemX - initialItemX + itemWidth >
  10061. (widthOption || (chart.chartWidth - 2 * padding - initialItemX - options.x))) {
  10062. legend.itemX = initialItemX;
  10063. legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom;
  10064. legend.lastLineHeight = 0; // reset for next line (#915, #3976)
  10065. }
  10066. // If the item exceeds the height, start a new column
  10067. /*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) {
  10068. legend.itemY = legend.initialItemY;
  10069. legend.itemX += legend.maxItemWidth;
  10070. legend.maxItemWidth = 0;
  10071. }*/
  10072. // Set the edge positions
  10073. legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth);
  10074. legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom;
  10075. legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915
  10076. // cache the position of the newly generated or reordered items
  10077. item._legendItemPos = [legend.itemX, legend.itemY];
  10078. // advance
  10079. if (horizontal) {
  10080. legend.itemX += itemWidth;
  10081. } else {
  10082. legend.itemY += itemMarginTop + itemHeight + itemMarginBottom;
  10083. legend.lastLineHeight = itemHeight;
  10084. }
  10085. // the width of the widest item
  10086. legend.offsetWidth = widthOption || mathMax(
  10087. (horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding,
  10088. legend.offsetWidth
  10089. );
  10090. },
  10091. /**
  10092. * Get all items, which is one item per series for normal series and one item per point
  10093. * for pie series.
  10094. */
  10095. getAllItems: function () {
  10096. var allItems = [];
  10097. each(this.chart.series, function (series) {
  10098. var seriesOptions = series.options;
  10099. // Handle showInLegend. If the series is linked to another series, defaults to false.
  10100. if (!pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? UNDEFINED : false, true)) {
  10101. return;
  10102. }
  10103. // use points or series for the legend item depending on legendType
  10104. allItems = allItems.concat(
  10105. series.legendItems ||
  10106. (seriesOptions.legendType === 'point' ?
  10107. series.data :
  10108. series)
  10109. );
  10110. });
  10111. return allItems;
  10112. },
  10113. /**
  10114. * Adjust the chart margins by reserving space for the legend on only one side
  10115. * of the chart. If the position is set to a corner, top or bottom is reserved
  10116. * for horizontal legends and left or right for vertical ones.
  10117. */
  10118. adjustMargins: function (margin, spacing) {
  10119. var chart = this.chart,
  10120. options = this.options,
  10121. // Use the first letter of each alignment option in order to detect the side
  10122. alignment = options.align.charAt(0) + options.verticalAlign.charAt(0) + options.layout.charAt(0); // #4189 - use charAt(x) notation instead of [x] for IE7
  10123. if (!options.floating) {
  10124. each([
  10125. /(lth|ct|rth)/,
  10126. /(rtv|rm|rbv)/,
  10127. /(rbh|cb|lbh)/,
  10128. /(lbv|lm|ltv)/
  10129. ], function (alignments, side) {
  10130. if (alignments.test(alignment) && !defined(margin[side])) {
  10131. // Now we have detected on which side of the chart we should reserve space for the legend
  10132. chart[marginNames[side]] = mathMax(
  10133. chart[marginNames[side]],
  10134. chart.legend[(side + 1) % 2 ? 'legendHeight' : 'legendWidth'] +
  10135. [1, -1, -1, 1][side] * options[(side % 2) ? 'x' : 'y'] +
  10136. pick(options.margin, 12) +
  10137. spacing[side]
  10138. );
  10139. }
  10140. });
  10141. }
  10142. },
  10143. /**
  10144. * Render the legend. This method can be called both before and after
  10145. * chart.render. If called after, it will only rearrange items instead
  10146. * of creating new ones.
  10147. */
  10148. render: function () {
  10149. var legend = this,
  10150. chart = legend.chart,
  10151. renderer = chart.renderer,
  10152. legendGroup = legend.group,
  10153. allItems,
  10154. display,
  10155. legendWidth,
  10156. legendHeight,
  10157. box = legend.box,
  10158. options = legend.options,
  10159. padding = legend.padding,
  10160. legendBorderWidth = options.borderWidth,
  10161. legendBackgroundColor = options.backgroundColor;
  10162. legend.itemX = legend.initialItemX;
  10163. legend.itemY = legend.initialItemY;
  10164. legend.offsetWidth = 0;
  10165. legend.lastItemY = 0;
  10166. if (!legendGroup) {
  10167. legend.group = legendGroup = renderer.g('legend')
  10168. .attr({ zIndex: 7 })
  10169. .add();
  10170. legend.contentGroup = renderer.g()
  10171. .attr({ zIndex: 1 }) // above background
  10172. .add(legendGroup);
  10173. legend.scrollGroup = renderer.g()
  10174. .add(legend.contentGroup);
  10175. }
  10176. legend.renderTitle();
  10177. // add each series or point
  10178. allItems = legend.getAllItems();
  10179. // sort by legendIndex
  10180. stableSort(allItems, function (a, b) {
  10181. return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0);
  10182. });
  10183. // reversed legend
  10184. if (options.reversed) {
  10185. allItems.reverse();
  10186. }
  10187. legend.allItems = allItems;
  10188. legend.display = display = !!allItems.length;
  10189. // render the items
  10190. legend.lastLineHeight = 0;
  10191. each(allItems, function (item) {
  10192. legend.renderItem(item);
  10193. });
  10194. // Get the box
  10195. legendWidth = (options.width || legend.offsetWidth) + padding;
  10196. legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight;
  10197. legendHeight = legend.handleOverflow(legendHeight);
  10198. legendHeight += padding;
  10199. // Draw the border and/or background
  10200. if (legendBorderWidth || legendBackgroundColor) {
  10201. if (!box) {
  10202. legend.box = box = renderer.rect(
  10203. 0,
  10204. 0,
  10205. legendWidth,
  10206. legendHeight,
  10207. options.borderRadius,
  10208. legendBorderWidth || 0
  10209. ).attr({
  10210. stroke: options.borderColor,
  10211. 'stroke-width': legendBorderWidth || 0,
  10212. fill: legendBackgroundColor || NONE
  10213. })
  10214. .add(legendGroup)
  10215. .shadow(options.shadow);
  10216. box.isNew = true;
  10217. } else if (legendWidth > 0 && legendHeight > 0) {
  10218. box[box.isNew ? 'attr' : 'animate'](
  10219. box.crisp({ width: legendWidth, height: legendHeight })
  10220. );
  10221. box.isNew = false;
  10222. }
  10223. // hide the border if no items
  10224. box[display ? 'show' : 'hide']();
  10225. }
  10226. legend.legendWidth = legendWidth;
  10227. legend.legendHeight = legendHeight;
  10228. // Now that the legend width and height are established, put the items in the
  10229. // final position
  10230. each(allItems, function (item) {
  10231. legend.positionItem(item);
  10232. });
  10233. // 1.x compatibility: positioning based on style
  10234. /*var props = ['left', 'right', 'top', 'bottom'],
  10235. prop,
  10236. i = 4;
  10237. while (i--) {
  10238. prop = props[i];
  10239. if (options.style[prop] && options.style[prop] !== 'auto') {
  10240. options[i < 2 ? 'align' : 'verticalAlign'] = prop;
  10241. options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1);
  10242. }
  10243. }*/
  10244. if (display) {
  10245. legendGroup.align(extend({
  10246. width: legendWidth,
  10247. height: legendHeight
  10248. }, options), true, 'spacingBox');
  10249. }
  10250. if (!chart.isResizing) {
  10251. this.positionCheckboxes();
  10252. }
  10253. },
  10254. /**
  10255. * Set up the overflow handling by adding navigation with up and down arrows below the
  10256. * legend.
  10257. */
  10258. handleOverflow: function (legendHeight) {
  10259. var legend = this,
  10260. chart = this.chart,
  10261. renderer = chart.renderer,
  10262. options = this.options,
  10263. optionsY = options.y,
  10264. alignTop = options.verticalAlign === 'top',
  10265. spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding,
  10266. maxHeight = options.maxHeight,
  10267. clipHeight,
  10268. clipRect = this.clipRect,
  10269. navOptions = options.navigation,
  10270. animation = pick(navOptions.animation, true),
  10271. arrowSize = navOptions.arrowSize || 12,
  10272. nav = this.nav,
  10273. pages = this.pages,
  10274. padding = this.padding,
  10275. lastY,
  10276. allItems = this.allItems,
  10277. clipToHeight = function (height) {
  10278. clipRect.attr({
  10279. height: height
  10280. });
  10281. // useHTML
  10282. if (legend.contentGroup.div) {
  10283. legend.contentGroup.div.style.clip = 'rect(' + padding + 'px,9999px,' + (padding + height) + 'px,0)';
  10284. }
  10285. };
  10286. // Adjust the height
  10287. if (options.layout === 'horizontal') {
  10288. spaceHeight /= 2;
  10289. }
  10290. if (maxHeight) {
  10291. spaceHeight = mathMin(spaceHeight, maxHeight);
  10292. }
  10293. // Reset the legend height and adjust the clipping rectangle
  10294. pages.length = 0;
  10295. if (legendHeight > spaceHeight && navOptions.enabled !== false) {
  10296. this.clipHeight = clipHeight = mathMax(spaceHeight - 20 - this.titleHeight - padding, 0);
  10297. this.currentPage = pick(this.currentPage, 1);
  10298. this.fullHeight = legendHeight;
  10299. // Fill pages with Y positions so that the top of each a legend item defines
  10300. // the scroll top for each page (#2098)
  10301. each(allItems, function (item, i) {
  10302. var y = item._legendItemPos[1],
  10303. h = mathRound(item.legendItem.getBBox().height),
  10304. len = pages.length;
  10305. if (!len || (y - pages[len - 1] > clipHeight && (lastY || y) !== pages[len - 1])) {
  10306. pages.push(lastY || y);
  10307. len++;
  10308. }
  10309. if (i === allItems.length - 1 && y + h - pages[len - 1] > clipHeight) {
  10310. pages.push(y);
  10311. }
  10312. if (y !== lastY) {
  10313. lastY = y;
  10314. }
  10315. });
  10316. // Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787)
  10317. if (!clipRect) {
  10318. clipRect = legend.clipRect = renderer.clipRect(0, padding, 9999, 0);
  10319. legend.contentGroup.clip(clipRect);
  10320. }
  10321. clipToHeight(clipHeight);
  10322. // Add navigation elements
  10323. if (!nav) {
  10324. this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group);
  10325. this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize)
  10326. .on('click', function () {
  10327. legend.scroll(-1, animation);
  10328. })
  10329. .add(nav);
  10330. this.pager = renderer.text('', 15, 10)
  10331. .css(navOptions.style)
  10332. .add(nav);
  10333. this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize)
  10334. .on('click', function () {
  10335. legend.scroll(1, animation);
  10336. })
  10337. .add(nav);
  10338. }
  10339. // Set initial position
  10340. legend.scroll(0);
  10341. legendHeight = spaceHeight;
  10342. } else if (nav) {
  10343. clipToHeight(chart.chartHeight);
  10344. nav.hide();
  10345. this.scrollGroup.attr({
  10346. translateY: 1
  10347. });
  10348. this.clipHeight = 0; // #1379
  10349. }
  10350. return legendHeight;
  10351. },
  10352. /**
  10353. * Scroll the legend by a number of pages
  10354. * @param {Object} scrollBy
  10355. * @param {Object} animation
  10356. */
  10357. scroll: function (scrollBy, animation) {
  10358. var pages = this.pages,
  10359. pageCount = pages.length,
  10360. currentPage = this.currentPage + scrollBy,
  10361. clipHeight = this.clipHeight,
  10362. navOptions = this.options.navigation,
  10363. activeColor = navOptions.activeColor,
  10364. inactiveColor = navOptions.inactiveColor,
  10365. pager = this.pager,
  10366. padding = this.padding,
  10367. scrollOffset;
  10368. // When resizing while looking at the last page
  10369. if (currentPage > pageCount) {
  10370. currentPage = pageCount;
  10371. }
  10372. if (currentPage > 0) {
  10373. if (animation !== UNDEFINED) {
  10374. setAnimation(animation, this.chart);
  10375. }
  10376. this.nav.attr({
  10377. translateX: padding,
  10378. translateY: clipHeight + this.padding + 7 + this.titleHeight,
  10379. visibility: VISIBLE
  10380. });
  10381. this.up.attr({
  10382. fill: currentPage === 1 ? inactiveColor : activeColor
  10383. })
  10384. .css({
  10385. cursor: currentPage === 1 ? 'default' : 'pointer'
  10386. });
  10387. pager.attr({
  10388. text: currentPage + '/' + pageCount
  10389. });
  10390. this.down.attr({
  10391. x: 18 + this.pager.getBBox().width, // adjust to text width
  10392. fill: currentPage === pageCount ? inactiveColor : activeColor
  10393. })
  10394. .css({
  10395. cursor: currentPage === pageCount ? 'default' : 'pointer'
  10396. });
  10397. scrollOffset = -pages[currentPage - 1] + this.initialItemY;
  10398. this.scrollGroup.animate({
  10399. translateY: scrollOffset
  10400. });
  10401. this.currentPage = currentPage;
  10402. this.positionCheckboxes(scrollOffset);
  10403. }
  10404. }
  10405. };
  10406. /*
  10407. * LegendSymbolMixin
  10408. */
  10409. var LegendSymbolMixin = Highcharts.LegendSymbolMixin = {
  10410. /**
  10411. * Get the series' symbol in the legend
  10412. *
  10413. * @param {Object} legend The legend object
  10414. * @param {Object} item The series (this) or point
  10415. */
  10416. drawRectangle: function (legend, item) {
  10417. var symbolHeight = legend.options.symbolHeight || legend.fontMetrics.f;
  10418. item.legendSymbol = this.chart.renderer.rect(
  10419. 0,
  10420. legend.baseline - symbolHeight + 1, // #3988
  10421. legend.symbolWidth,
  10422. symbolHeight,
  10423. legend.options.symbolRadius || 0
  10424. ).attr({
  10425. zIndex: 3
  10426. }).add(item.legendGroup);
  10427. },
  10428. /**
  10429. * Get the series' symbol in the legend. This method should be overridable to create custom
  10430. * symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols.
  10431. *
  10432. * @param {Object} legend The legend object
  10433. */
  10434. drawLineMarker: function (legend) {
  10435. var options = this.options,
  10436. markerOptions = options.marker,
  10437. radius,
  10438. legendSymbol,
  10439. symbolWidth = legend.symbolWidth,
  10440. renderer = this.chart.renderer,
  10441. legendItemGroup = this.legendGroup,
  10442. verticalCenter = legend.baseline - mathRound(legend.fontMetrics.b * 0.3),
  10443. attr;
  10444. // Draw the line
  10445. if (options.lineWidth) {
  10446. attr = {
  10447. 'stroke-width': options.lineWidth
  10448. };
  10449. if (options.dashStyle) {
  10450. attr.dashstyle = options.dashStyle;
  10451. }
  10452. this.legendLine = renderer.path([
  10453. M,
  10454. 0,
  10455. verticalCenter,
  10456. L,
  10457. symbolWidth,
  10458. verticalCenter
  10459. ])
  10460. .attr(attr)
  10461. .add(legendItemGroup);
  10462. }
  10463. // Draw the marker
  10464. if (markerOptions && markerOptions.enabled !== false) {
  10465. radius = markerOptions.radius;
  10466. this.legendSymbol = legendSymbol = renderer.symbol(
  10467. this.symbol,
  10468. (symbolWidth / 2) - radius,
  10469. verticalCenter - radius,
  10470. 2 * radius,
  10471. 2 * radius,
  10472. markerOptions
  10473. )
  10474. .add(legendItemGroup);
  10475. legendSymbol.isMarker = true;
  10476. }
  10477. }
  10478. };
  10479. // Workaround for #2030, horizontal legend items not displaying in IE11 Preview,
  10480. // and for #2580, a similar drawing flaw in Firefox 26.
  10481. // Explore if there's a general cause for this. The problem may be related
  10482. // to nested group elements, as the legend item texts are within 4 group elements.
  10483. if (/Trident\/7\.0/.test(userAgent) || isFirefox) {
  10484. wrap(Legend.prototype, 'positionItem', function (proceed, item) {
  10485. var legend = this,
  10486. runPositionItem = function () { // If chart destroyed in sync, this is undefined (#2030)
  10487. if (item._legendItemPos) {
  10488. proceed.call(legend, item);
  10489. }
  10490. };
  10491. // Do it now, for export and to get checkbox placement
  10492. runPositionItem();
  10493. // Do it after to work around the core issue
  10494. setTimeout(runPositionItem);
  10495. });
  10496. }
  10497. /**
  10498. * The Chart class
  10499. * @param {String|Object} renderTo The DOM element to render to, or its id
  10500. * @param {Object} options
  10501. * @param {Function} callback Function to run when the chart has loaded
  10502. */
  10503. var Chart = Highcharts.Chart = function () {
  10504. this.getArgs.apply(this, arguments);
  10505. };
  10506. Highcharts.chart = function (a, b, c) {
  10507. return new Chart(a, b, c);
  10508. };
  10509. Chart.prototype = {
  10510. /**
  10511. * Hook for modules
  10512. */
  10513. callbacks: [],
  10514. /**
  10515. * Handle the arguments passed to the constructor
  10516. * @returns {Array} Arguments without renderTo
  10517. */
  10518. getArgs: function () {
  10519. var args = [].slice.call(arguments);
  10520. // Remove the optional first argument, renderTo, and
  10521. // set it on this.
  10522. if (isString(args[0]) || args[0].nodeName) {
  10523. this.renderTo = args.shift();
  10524. }
  10525. this.init(args[0], args[1]);
  10526. },
  10527. /**
  10528. * Initialize the chart
  10529. */
  10530. init: function (userOptions, callback) {
  10531. // Handle regular options
  10532. var options,
  10533. seriesOptions = userOptions.series; // skip merging data points to increase performance
  10534. userOptions.series = null;
  10535. options = merge(defaultOptions, userOptions); // do the merge
  10536. options.series = userOptions.series = seriesOptions; // set back the series data
  10537. this.userOptions = userOptions;
  10538. var optionsChart = options.chart;
  10539. // Create margin & spacing array
  10540. this.margin = this.splashArray('margin', optionsChart);
  10541. this.spacing = this.splashArray('spacing', optionsChart);
  10542. var chartEvents = optionsChart.events;
  10543. //this.runChartClick = chartEvents && !!chartEvents.click;
  10544. this.bounds = { h: {}, v: {} }; // Pixel data bounds for touch zoom
  10545. this.callback = callback;
  10546. this.isResizing = 0;
  10547. this.options = options;
  10548. //chartTitleOptions = UNDEFINED;
  10549. //chartSubtitleOptions = UNDEFINED;
  10550. this.axes = [];
  10551. this.series = [];
  10552. this.hasCartesianSeries = optionsChart.showAxes;
  10553. //this.axisOffset = UNDEFINED;
  10554. //this.maxTicks = UNDEFINED; // handle the greatest amount of ticks on grouped axes
  10555. //this.inverted = UNDEFINED;
  10556. //this.loadingShown = UNDEFINED;
  10557. //this.container = UNDEFINED;
  10558. //this.chartWidth = UNDEFINED;
  10559. //this.chartHeight = UNDEFINED;
  10560. //this.marginRight = UNDEFINED;
  10561. //this.marginBottom = UNDEFINED;
  10562. //this.containerWidth = UNDEFINED;
  10563. //this.containerHeight = UNDEFINED;
  10564. //this.oldChartWidth = UNDEFINED;
  10565. //this.oldChartHeight = UNDEFINED;
  10566. //this.renderTo = UNDEFINED;
  10567. //this.renderToClone = UNDEFINED;
  10568. //this.spacingBox = UNDEFINED
  10569. //this.legend = UNDEFINED;
  10570. // Elements
  10571. //this.chartBackground = UNDEFINED;
  10572. //this.plotBackground = UNDEFINED;
  10573. //this.plotBGImage = UNDEFINED;
  10574. //this.plotBorder = UNDEFINED;
  10575. //this.loadingDiv = UNDEFINED;
  10576. //this.loadingSpan = UNDEFINED;
  10577. var chart = this,
  10578. eventType;
  10579. // Add the chart to the global lookup
  10580. chart.index = charts.length;
  10581. charts.push(chart);
  10582. chartCount++;
  10583. // Set up auto resize
  10584. if (optionsChart.reflow !== false) {
  10585. addEvent(chart, 'load', function () {
  10586. chart.initReflow();
  10587. });
  10588. }
  10589. // Chart event handlers
  10590. if (chartEvents) {
  10591. for (eventType in chartEvents) {
  10592. addEvent(chart, eventType, chartEvents[eventType]);
  10593. }
  10594. }
  10595. chart.xAxis = [];
  10596. chart.yAxis = [];
  10597. // Expose methods and variables
  10598. chart.animation = useCanVG ? false : pick(optionsChart.animation, true);
  10599. chart.pointCount = chart.colorCounter = chart.symbolCounter = 0;
  10600. chart.firstRender();
  10601. },
  10602. /**
  10603. * Initialize an individual series, called internally before render time
  10604. */
  10605. initSeries: function (options) {
  10606. var chart = this,
  10607. optionsChart = chart.options.chart,
  10608. type = options.type || optionsChart.type || optionsChart.defaultSeriesType,
  10609. series,
  10610. constr = seriesTypes[type];
  10611. // No such series type
  10612. if (!constr) {
  10613. error(17, true);
  10614. }
  10615. series = new constr();
  10616. series.init(this, options);
  10617. return series;
  10618. },
  10619. /**
  10620. * Check whether a given point is within the plot area
  10621. *
  10622. * @param {Number} plotX Pixel x relative to the plot area
  10623. * @param {Number} plotY Pixel y relative to the plot area
  10624. * @param {Boolean} inverted Whether the chart is inverted
  10625. */
  10626. isInsidePlot: function (plotX, plotY, inverted) {
  10627. var x = inverted ? plotY : plotX,
  10628. y = inverted ? plotX : plotY;
  10629. return x >= 0 &&
  10630. x <= this.plotWidth &&
  10631. y >= 0 &&
  10632. y <= this.plotHeight;
  10633. },
  10634. /**
  10635. * Redraw legend, axes or series based on updated data
  10636. *
  10637. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  10638. * configuration
  10639. */
  10640. redraw: function (animation) {
  10641. var chart = this,
  10642. axes = chart.axes,
  10643. series = chart.series,
  10644. pointer = chart.pointer,
  10645. legend = chart.legend,
  10646. redrawLegend = chart.isDirtyLegend,
  10647. hasStackedSeries,
  10648. hasDirtyStacks,
  10649. hasCartesianSeries = chart.hasCartesianSeries,
  10650. isDirtyBox = chart.isDirtyBox,
  10651. seriesLength = series.length,
  10652. i = seriesLength,
  10653. serie,
  10654. renderer = chart.renderer,
  10655. isHiddenChart = renderer.isHidden(),
  10656. afterRedraw = [];
  10657. setAnimation(animation, chart);
  10658. if (isHiddenChart) {
  10659. chart.cloneRenderTo();
  10660. }
  10661. // Adjust title layout (reflow multiline text)
  10662. chart.layOutTitles();
  10663. // link stacked series
  10664. while (i--) {
  10665. serie = series[i];
  10666. if (serie.options.stacking) {
  10667. hasStackedSeries = true;
  10668. if (serie.isDirty) {
  10669. hasDirtyStacks = true;
  10670. break;
  10671. }
  10672. }
  10673. }
  10674. if (hasDirtyStacks) { // mark others as dirty
  10675. i = seriesLength;
  10676. while (i--) {
  10677. serie = series[i];
  10678. if (serie.options.stacking) {
  10679. serie.isDirty = true;
  10680. }
  10681. }
  10682. }
  10683. // Handle updated data in the series
  10684. each(series, function (serie) {
  10685. if (serie.isDirty) {
  10686. if (serie.options.legendType === 'point') {
  10687. if (serie.updateTotals) {
  10688. serie.updateTotals();
  10689. }
  10690. redrawLegend = true;
  10691. }
  10692. }
  10693. if (serie.isDirtyData) {
  10694. fireEvent(serie, 'updatedData');
  10695. }
  10696. });
  10697. // handle added or removed series
  10698. if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed
  10699. // draw legend graphics
  10700. legend.render();
  10701. chart.isDirtyLegend = false;
  10702. }
  10703. // reset stacks
  10704. if (hasStackedSeries) {
  10705. chart.getStacks();
  10706. }
  10707. if (hasCartesianSeries) {
  10708. if (!chart.isResizing) {
  10709. // reset maxTicks
  10710. chart.maxTicks = null;
  10711. // set axes scales
  10712. each(axes, function (axis) {
  10713. axis.updateNames();
  10714. axis.setScale();
  10715. });
  10716. }
  10717. }
  10718. chart.getMargins(); // #3098
  10719. if (hasCartesianSeries) {
  10720. // If one axis is dirty, all axes must be redrawn (#792, #2169)
  10721. each(axes, function (axis) {
  10722. if (axis.isDirty) {
  10723. isDirtyBox = true;
  10724. }
  10725. });
  10726. // redraw axes
  10727. each(axes, function (axis) {
  10728. // Fire 'afterSetExtremes' only if extremes are set
  10729. var key = axis.min + ',' + axis.max;
  10730. if (axis.extKey !== key) { // #821, #4452
  10731. axis.extKey = key;
  10732. afterRedraw.push(function () { // prevent a recursive call to chart.redraw() (#1119)
  10733. fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751
  10734. delete axis.eventArgs;
  10735. });
  10736. }
  10737. if (isDirtyBox || hasStackedSeries) {
  10738. axis.redraw();
  10739. }
  10740. });
  10741. }
  10742. // the plot areas size has changed
  10743. if (isDirtyBox) {
  10744. chart.drawChartBox();
  10745. }
  10746. // redraw affected series
  10747. each(series, function (serie) {
  10748. if (serie.isDirty && serie.visible &&
  10749. (!serie.isCartesian || serie.xAxis)) { // issue #153
  10750. serie.redraw();
  10751. }
  10752. });
  10753. // move tooltip or reset
  10754. if (pointer) {
  10755. pointer.reset(true);
  10756. }
  10757. // redraw if canvas
  10758. renderer.draw();
  10759. // fire the event
  10760. fireEvent(chart, 'redraw');
  10761. if (isHiddenChart) {
  10762. chart.cloneRenderTo(true);
  10763. }
  10764. // Fire callbacks that are put on hold until after the redraw
  10765. each(afterRedraw, function (callback) {
  10766. callback.call();
  10767. });
  10768. },
  10769. /**
  10770. * Get an axis, series or point object by id.
  10771. * @param id {String} The id as given in the configuration options
  10772. */
  10773. get: function (id) {
  10774. var chart = this,
  10775. axes = chart.axes,
  10776. series = chart.series;
  10777. var i,
  10778. j,
  10779. points;
  10780. // search axes
  10781. for (i = 0; i < axes.length; i++) {
  10782. if (axes[i].options.id === id) {
  10783. return axes[i];
  10784. }
  10785. }
  10786. // search series
  10787. for (i = 0; i < series.length; i++) {
  10788. if (series[i].options.id === id) {
  10789. return series[i];
  10790. }
  10791. }
  10792. // search points
  10793. for (i = 0; i < series.length; i++) {
  10794. points = series[i].points || [];
  10795. for (j = 0; j < points.length; j++) {
  10796. if (points[j].id === id) {
  10797. return points[j];
  10798. }
  10799. }
  10800. }
  10801. return null;
  10802. },
  10803. /**
  10804. * Create the Axis instances based on the config options
  10805. */
  10806. getAxes: function () {
  10807. var chart = this,
  10808. options = this.options,
  10809. xAxisOptions = options.xAxis = splat(options.xAxis || {}),
  10810. yAxisOptions = options.yAxis = splat(options.yAxis || {}),
  10811. optionsArray;
  10812. // make sure the options are arrays and add some members
  10813. each(xAxisOptions, function (axis, i) {
  10814. axis.index = i;
  10815. axis.isX = true;
  10816. });
  10817. each(yAxisOptions, function (axis, i) {
  10818. axis.index = i;
  10819. });
  10820. // concatenate all axis options into one array
  10821. optionsArray = xAxisOptions.concat(yAxisOptions);
  10822. each(optionsArray, function (axisOptions) {
  10823. new Axis(chart, axisOptions); // eslint-disable-line no-new
  10824. });
  10825. },
  10826. /**
  10827. * Get the currently selected points from all series
  10828. */
  10829. getSelectedPoints: function () {
  10830. var points = [];
  10831. each(this.series, function (serie) {
  10832. points = points.concat(grep(serie.points || [], function (point) {
  10833. return point.selected;
  10834. }));
  10835. });
  10836. return points;
  10837. },
  10838. /**
  10839. * Get the currently selected series
  10840. */
  10841. getSelectedSeries: function () {
  10842. return grep(this.series, function (serie) {
  10843. return serie.selected;
  10844. });
  10845. },
  10846. /**
  10847. * Show the title and subtitle of the chart
  10848. *
  10849. * @param titleOptions {Object} New title options
  10850. * @param subtitleOptions {Object} New subtitle options
  10851. *
  10852. */
  10853. setTitle: function (titleOptions, subtitleOptions, redraw) {
  10854. var chart = this,
  10855. options = chart.options,
  10856. chartTitleOptions,
  10857. chartSubtitleOptions;
  10858. chartTitleOptions = options.title = merge(options.title, titleOptions);
  10859. chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions);
  10860. // add title and subtitle
  10861. each([
  10862. ['title', titleOptions, chartTitleOptions],
  10863. ['subtitle', subtitleOptions, chartSubtitleOptions]
  10864. ], function (arr) {
  10865. var name = arr[0],
  10866. title = chart[name],
  10867. titleOptions = arr[1],
  10868. chartTitleOptions = arr[2];
  10869. if (title && titleOptions) {
  10870. chart[name] = title = title.destroy(); // remove old
  10871. }
  10872. if (chartTitleOptions && chartTitleOptions.text && !title) {
  10873. chart[name] = chart.renderer.text(
  10874. chartTitleOptions.text,
  10875. 0,
  10876. 0,
  10877. chartTitleOptions.useHTML
  10878. )
  10879. .attr({
  10880. align: chartTitleOptions.align,
  10881. 'class': PREFIX + name,
  10882. zIndex: chartTitleOptions.zIndex || 4
  10883. })
  10884. .css(chartTitleOptions.style)
  10885. .add();
  10886. }
  10887. });
  10888. chart.layOutTitles(redraw);
  10889. },
  10890. /**
  10891. * Lay out the chart titles and cache the full offset height for use in getMargins
  10892. */
  10893. layOutTitles: function (redraw) {
  10894. var titleOffset = 0,
  10895. title = this.title,
  10896. subtitle = this.subtitle,
  10897. options = this.options,
  10898. titleOptions = options.title,
  10899. subtitleOptions = options.subtitle,
  10900. requiresDirtyBox,
  10901. renderer = this.renderer,
  10902. spacingBox = this.spacingBox;
  10903. if (title) {
  10904. title
  10905. .css({ width: (titleOptions.width || spacingBox.width + titleOptions.widthAdjust) + PX })
  10906. .align(extend({
  10907. y: renderer.fontMetrics(titleOptions.style.fontSize, title).b - 3
  10908. }, titleOptions), false, spacingBox);
  10909. if (!titleOptions.floating && !titleOptions.verticalAlign) {
  10910. titleOffset = title.getBBox().height;
  10911. }
  10912. }
  10913. if (subtitle) {
  10914. subtitle
  10915. .css({ width: (subtitleOptions.width || spacingBox.width + subtitleOptions.widthAdjust) + PX })
  10916. .align(extend({
  10917. y: titleOffset + (titleOptions.margin - 13) + renderer.fontMetrics(subtitleOptions.style.fontSize, title).b
  10918. }, subtitleOptions), false, spacingBox);
  10919. if (!subtitleOptions.floating && !subtitleOptions.verticalAlign) {
  10920. titleOffset = mathCeil(titleOffset + subtitle.getBBox().height);
  10921. }
  10922. }
  10923. requiresDirtyBox = this.titleOffset !== titleOffset;
  10924. this.titleOffset = titleOffset; // used in getMargins
  10925. if (!this.isDirtyBox && requiresDirtyBox) {
  10926. this.isDirtyBox = requiresDirtyBox;
  10927. // Redraw if necessary (#2719, #2744)
  10928. if (this.hasRendered && pick(redraw, true) && this.isDirtyBox) {
  10929. this.redraw();
  10930. }
  10931. }
  10932. },
  10933. /**
  10934. * Get chart width and height according to options and container size
  10935. */
  10936. getChartSize: function () {
  10937. var chart = this,
  10938. optionsChart = chart.options.chart,
  10939. widthOption = optionsChart.width,
  10940. heightOption = optionsChart.height,
  10941. renderTo = chart.renderToClone || chart.renderTo;
  10942. // Get inner width and height
  10943. if (!defined(widthOption)) {
  10944. chart.containerWidth = getStyle(renderTo, 'width');
  10945. }
  10946. if (!defined(heightOption)) {
  10947. chart.containerHeight = getStyle(renderTo, 'height');
  10948. }
  10949. chart.chartWidth = mathMax(0, widthOption || chart.containerWidth || 600); // #1393, 1460
  10950. chart.chartHeight = mathMax(0, pick(heightOption,
  10951. // the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7:
  10952. chart.containerHeight > 19 ? chart.containerHeight : 400));
  10953. },
  10954. /**
  10955. * Create a clone of the chart's renderTo div and place it outside the viewport to allow
  10956. * size computation on chart.render and chart.redraw
  10957. */
  10958. cloneRenderTo: function (revert) {
  10959. var clone = this.renderToClone,
  10960. container = this.container;
  10961. // Destroy the clone and bring the container back to the real renderTo div
  10962. if (revert) {
  10963. if (clone) {
  10964. while (clone.childNodes.length) { // #5231
  10965. this.renderTo.appendChild(clone.firstChild);
  10966. }
  10967. discardElement(clone);
  10968. delete this.renderToClone;
  10969. }
  10970. // Set up the clone
  10971. } else {
  10972. if (container && container.parentNode === this.renderTo) {
  10973. this.renderTo.removeChild(container); // do not clone this
  10974. }
  10975. this.renderToClone = clone = this.renderTo.cloneNode(0);
  10976. css(clone, {
  10977. position: ABSOLUTE,
  10978. top: '-9999px',
  10979. display: 'block' // #833
  10980. });
  10981. if (clone.style.setProperty) { // #2631
  10982. clone.style.setProperty('display', 'block', 'important');
  10983. }
  10984. doc.body.appendChild(clone);
  10985. if (container) {
  10986. clone.appendChild(container);
  10987. }
  10988. }
  10989. },
  10990. /**
  10991. * Get the containing element, determine the size and create the inner container
  10992. * div to hold the chart
  10993. */
  10994. getContainer: function () {
  10995. var chart = this,
  10996. container,
  10997. options = chart.options,
  10998. optionsChart = options.chart,
  10999. chartWidth,
  11000. chartHeight,
  11001. renderTo = chart.renderTo,
  11002. indexAttrName = 'data-highcharts-chart',
  11003. oldChartIndex,
  11004. Ren,
  11005. containerId = 'highcharts-' + idCounter++;
  11006. if (!renderTo) {
  11007. chart.renderTo = renderTo = optionsChart.renderTo;
  11008. }
  11009. if (isString(renderTo)) {
  11010. chart.renderTo = renderTo = doc.getElementById(renderTo);
  11011. }
  11012. // Display an error if the renderTo is wrong
  11013. if (!renderTo) {
  11014. error(13, true);
  11015. }
  11016. // If the container already holds a chart, destroy it. The check for hasRendered is there
  11017. // because web pages that are saved to disk from the browser, will preserve the data-highcharts-chart
  11018. // attribute and the SVG contents, but not an interactive chart. So in this case,
  11019. // charts[oldChartIndex] will point to the wrong chart if any (#2609).
  11020. oldChartIndex = pInt(attr(renderTo, indexAttrName));
  11021. if (isNumber(oldChartIndex) && charts[oldChartIndex] && charts[oldChartIndex].hasRendered) {
  11022. charts[oldChartIndex].destroy();
  11023. }
  11024. // Make a reference to the chart from the div
  11025. attr(renderTo, indexAttrName, chart.index);
  11026. // remove previous chart
  11027. renderTo.innerHTML = '';
  11028. // If the container doesn't have an offsetWidth, it has or is a child of a node
  11029. // that has display:none. We need to temporarily move it out to a visible
  11030. // state to determine the size, else the legend and tooltips won't render
  11031. // properly. The allowClone option is used in sparklines as a micro optimization,
  11032. // saving about 1-2 ms each chart.
  11033. if (!optionsChart.skipClone && !renderTo.offsetWidth) {
  11034. chart.cloneRenderTo();
  11035. }
  11036. // get the width and height
  11037. chart.getChartSize();
  11038. chartWidth = chart.chartWidth;
  11039. chartHeight = chart.chartHeight;
  11040. // create the inner container
  11041. chart.container = container = createElement(DIV, {
  11042. className: PREFIX + 'container' +
  11043. (optionsChart.className ? ' ' + optionsChart.className : ''),
  11044. id: containerId
  11045. }, extend({
  11046. position: RELATIVE,
  11047. overflow: HIDDEN, // needed for context menu (avoid scrollbars) and
  11048. // content overflow in IE
  11049. width: chartWidth + PX,
  11050. height: chartHeight + PX,
  11051. textAlign: 'left',
  11052. lineHeight: 'normal', // #427
  11053. zIndex: 0, // #1072
  11054. '-webkit-tap-highlight-color': 'rgba(0,0,0,0)'
  11055. }, optionsChart.style),
  11056. chart.renderToClone || renderTo
  11057. );
  11058. // cache the cursor (#1650)
  11059. chart._cursor = container.style.cursor;
  11060. // Initialize the renderer
  11061. Ren = Highcharts[optionsChart.renderer] || Renderer;
  11062. chart.renderer = new Ren(
  11063. container,
  11064. chartWidth,
  11065. chartHeight,
  11066. optionsChart.style,
  11067. optionsChart.forExport,
  11068. options.exporting && options.exporting.allowHTML
  11069. );
  11070. if (useCanVG) {
  11071. // If we need canvg library, extend and configure the renderer
  11072. // to get the tracker for translating mouse events
  11073. chart.renderer.create(chart, container, chartWidth, chartHeight);
  11074. }
  11075. // Add a reference to the charts index
  11076. chart.renderer.chartIndex = chart.index;
  11077. },
  11078. /**
  11079. * Calculate margins by rendering axis labels in a preliminary position. Title,
  11080. * subtitle and legend have already been rendered at this stage, but will be
  11081. * moved into their final positions
  11082. */
  11083. getMargins: function (skipAxes) {
  11084. var chart = this,
  11085. spacing = chart.spacing,
  11086. margin = chart.margin,
  11087. titleOffset = chart.titleOffset;
  11088. chart.resetMargins();
  11089. // Adjust for title and subtitle
  11090. if (titleOffset && !defined(margin[0])) {
  11091. chart.plotTop = mathMax(chart.plotTop, titleOffset + chart.options.title.margin + spacing[0]);
  11092. }
  11093. // Adjust for legend
  11094. if (chart.legend.display) {
  11095. chart.legend.adjustMargins(margin, spacing);
  11096. }
  11097. // adjust for scroller
  11098. if (chart.extraBottomMargin) {
  11099. chart.marginBottom += chart.extraBottomMargin;
  11100. }
  11101. if (chart.extraTopMargin) {
  11102. chart.plotTop += chart.extraTopMargin;
  11103. }
  11104. if (!skipAxes) {
  11105. this.getAxisMargins();
  11106. }
  11107. },
  11108. getAxisMargins: function () {
  11109. var chart = this,
  11110. axisOffset = chart.axisOffset = [0, 0, 0, 0], // top, right, bottom, left
  11111. margin = chart.margin;
  11112. // pre-render axes to get labels offset width
  11113. if (chart.hasCartesianSeries) {
  11114. each(chart.axes, function (axis) {
  11115. if (axis.visible) {
  11116. axis.getOffset();
  11117. }
  11118. });
  11119. }
  11120. // Add the axis offsets
  11121. each(marginNames, function (m, side) {
  11122. if (!defined(margin[side])) {
  11123. chart[m] += axisOffset[side];
  11124. }
  11125. });
  11126. chart.setChartSize();
  11127. },
  11128. /**
  11129. * Resize the chart to its container if size is not explicitly set
  11130. */
  11131. reflow: function (e) {
  11132. var chart = this,
  11133. optionsChart = chart.options.chart,
  11134. renderTo = chart.renderTo,
  11135. hasUserWidth = defined(optionsChart.width),
  11136. width = optionsChart.width || getStyle(renderTo, 'width'),
  11137. height = optionsChart.height || getStyle(renderTo, 'height'),
  11138. target = e ? e.target : win;
  11139. // Width and height checks for display:none. Target is doc in IE8 and Opera,
  11140. // win in Firefox, Chrome and IE9.
  11141. if (!hasUserWidth && !chart.isPrinting && width && height && (target === win || target === doc)) { // #1093
  11142. if (width !== chart.containerWidth || height !== chart.containerHeight) {
  11143. clearTimeout(chart.reflowTimeout);
  11144. // When called from window.resize, e is set, else it's called directly (#2224)
  11145. chart.reflowTimeout = syncTimeout(function () {
  11146. if (chart.container) { // It may have been destroyed in the meantime (#1257)
  11147. chart.setSize(undefined, undefined, false);
  11148. }
  11149. }, e ? 100 : 0);
  11150. }
  11151. chart.containerWidth = width;
  11152. chart.containerHeight = height;
  11153. }
  11154. },
  11155. /**
  11156. * Add the event handlers necessary for auto resizing
  11157. */
  11158. initReflow: function () {
  11159. var chart = this,
  11160. reflow = function (e) {
  11161. chart.reflow(e);
  11162. };
  11163. addEvent(win, 'resize', reflow);
  11164. addEvent(chart, 'destroy', function () {
  11165. removeEvent(win, 'resize', reflow);
  11166. });
  11167. },
  11168. /**
  11169. * Resize the chart to a given width and height
  11170. * @param {Number} width
  11171. * @param {Number} height
  11172. * @param {Object|Boolean} animation
  11173. */
  11174. setSize: function (width, height, animation) {
  11175. var chart = this,
  11176. renderer = chart.renderer,
  11177. globalAnimation;
  11178. // Handle the isResizing counter
  11179. chart.isResizing += 1;
  11180. // set the animation for the current process
  11181. setAnimation(animation, chart);
  11182. chart.oldChartHeight = chart.chartHeight;
  11183. chart.oldChartWidth = chart.chartWidth;
  11184. if (width !== undefined) {
  11185. chart.options.chart.width = width;
  11186. }
  11187. if (height !== undefined) {
  11188. chart.options.chart.height = height;
  11189. }
  11190. chart.getChartSize();
  11191. // Resize the container with the global animation applied if enabled (#2503)
  11192. globalAnimation = renderer.globalAnimation;
  11193. (globalAnimation ? animate : css)(chart.container, {
  11194. width: chart.chartWidth + PX,
  11195. height: chart.chartHeight + PX
  11196. }, globalAnimation);
  11197. chart.setChartSize(true);
  11198. renderer.setSize(chart.chartWidth, chart.chartHeight, animation);
  11199. // handle axes
  11200. chart.maxTicks = null;
  11201. each(chart.axes, function (axis) {
  11202. axis.isDirty = true;
  11203. axis.setScale();
  11204. });
  11205. // make sure non-cartesian series are also handled
  11206. each(chart.series, function (serie) {
  11207. serie.isDirty = true;
  11208. });
  11209. chart.isDirtyLegend = true; // force legend redraw
  11210. chart.isDirtyBox = true; // force redraw of plot and chart border
  11211. chart.layOutTitles(); // #2857
  11212. chart.getMargins();
  11213. chart.redraw(animation);
  11214. chart.oldChartHeight = null;
  11215. fireEvent(chart, 'resize');
  11216. // Fire endResize and set isResizing back. If animation is disabled, fire without delay
  11217. syncTimeout(function () {
  11218. if (chart) {
  11219. fireEvent(chart, 'endResize', null, function () {
  11220. chart.isResizing -= 1;
  11221. });
  11222. }
  11223. }, animObject(globalAnimation).duration);
  11224. },
  11225. /**
  11226. * Set the public chart properties. This is done before and after the pre-render
  11227. * to determine margin sizes
  11228. */
  11229. setChartSize: function (skipAxes) {
  11230. var chart = this,
  11231. inverted = chart.inverted,
  11232. renderer = chart.renderer,
  11233. chartWidth = chart.chartWidth,
  11234. chartHeight = chart.chartHeight,
  11235. optionsChart = chart.options.chart,
  11236. spacing = chart.spacing,
  11237. clipOffset = chart.clipOffset,
  11238. clipX,
  11239. clipY,
  11240. plotLeft,
  11241. plotTop,
  11242. plotWidth,
  11243. plotHeight,
  11244. plotBorderWidth;
  11245. chart.plotLeft = plotLeft = mathRound(chart.plotLeft);
  11246. chart.plotTop = plotTop = mathRound(chart.plotTop);
  11247. chart.plotWidth = plotWidth = mathMax(0, mathRound(chartWidth - plotLeft - chart.marginRight));
  11248. chart.plotHeight = plotHeight = mathMax(0, mathRound(chartHeight - plotTop - chart.marginBottom));
  11249. chart.plotSizeX = inverted ? plotHeight : plotWidth;
  11250. chart.plotSizeY = inverted ? plotWidth : plotHeight;
  11251. chart.plotBorderWidth = optionsChart.plotBorderWidth || 0;
  11252. // Set boxes used for alignment
  11253. chart.spacingBox = renderer.spacingBox = {
  11254. x: spacing[3],
  11255. y: spacing[0],
  11256. width: chartWidth - spacing[3] - spacing[1],
  11257. height: chartHeight - spacing[0] - spacing[2]
  11258. };
  11259. chart.plotBox = renderer.plotBox = {
  11260. x: plotLeft,
  11261. y: plotTop,
  11262. width: plotWidth,
  11263. height: plotHeight
  11264. };
  11265. plotBorderWidth = 2 * mathFloor(chart.plotBorderWidth / 2);
  11266. clipX = mathCeil(mathMax(plotBorderWidth, clipOffset[3]) / 2);
  11267. clipY = mathCeil(mathMax(plotBorderWidth, clipOffset[0]) / 2);
  11268. chart.clipBox = {
  11269. x: clipX,
  11270. y: clipY,
  11271. width: mathFloor(chart.plotSizeX - mathMax(plotBorderWidth, clipOffset[1]) / 2 - clipX),
  11272. height: mathMax(0, mathFloor(chart.plotSizeY - mathMax(plotBorderWidth, clipOffset[2]) / 2 - clipY))
  11273. };
  11274. if (!skipAxes) {
  11275. each(chart.axes, function (axis) {
  11276. axis.setAxisSize();
  11277. axis.setAxisTranslation();
  11278. });
  11279. }
  11280. },
  11281. /**
  11282. * Initial margins before auto size margins are applied
  11283. */
  11284. resetMargins: function () {
  11285. var chart = this;
  11286. each(marginNames, function (m, side) {
  11287. chart[m] = pick(chart.margin[side], chart.spacing[side]);
  11288. });
  11289. chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left
  11290. chart.clipOffset = [0, 0, 0, 0];
  11291. },
  11292. /**
  11293. * Draw the borders and backgrounds for chart and plot area
  11294. */
  11295. drawChartBox: function () {
  11296. var chart = this,
  11297. optionsChart = chart.options.chart,
  11298. renderer = chart.renderer,
  11299. chartWidth = chart.chartWidth,
  11300. chartHeight = chart.chartHeight,
  11301. chartBackground = chart.chartBackground,
  11302. plotBackground = chart.plotBackground,
  11303. plotBorder = chart.plotBorder,
  11304. plotBGImage = chart.plotBGImage,
  11305. chartBorderWidth = optionsChart.borderWidth || 0,
  11306. chartBackgroundColor = optionsChart.backgroundColor,
  11307. plotBackgroundColor = optionsChart.plotBackgroundColor,
  11308. plotBackgroundImage = optionsChart.plotBackgroundImage,
  11309. plotBorderWidth = optionsChart.plotBorderWidth || 0,
  11310. mgn,
  11311. bgAttr,
  11312. plotLeft = chart.plotLeft,
  11313. plotTop = chart.plotTop,
  11314. plotWidth = chart.plotWidth,
  11315. plotHeight = chart.plotHeight,
  11316. plotBox = chart.plotBox,
  11317. clipRect = chart.clipRect,
  11318. clipBox = chart.clipBox;
  11319. // Chart area
  11320. mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0);
  11321. if (chartBorderWidth || chartBackgroundColor) {
  11322. if (!chartBackground) {
  11323. bgAttr = {
  11324. fill: chartBackgroundColor || NONE
  11325. };
  11326. if (chartBorderWidth) { // #980
  11327. bgAttr.stroke = optionsChart.borderColor;
  11328. bgAttr['stroke-width'] = chartBorderWidth;
  11329. }
  11330. chart.chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn,
  11331. optionsChart.borderRadius, chartBorderWidth)
  11332. .attr(bgAttr)
  11333. .addClass(PREFIX + 'background')
  11334. .add()
  11335. .shadow(optionsChart.shadow);
  11336. } else { // resize
  11337. chartBackground.animate(
  11338. chartBackground.crisp({ width: chartWidth - mgn, height: chartHeight - mgn })
  11339. );
  11340. }
  11341. }
  11342. // Plot background
  11343. if (plotBackgroundColor) {
  11344. if (!plotBackground) {
  11345. chart.plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0)
  11346. .attr({
  11347. fill: plotBackgroundColor
  11348. })
  11349. .add()
  11350. .shadow(optionsChart.plotShadow);
  11351. } else {
  11352. plotBackground.animate(plotBox);
  11353. }
  11354. }
  11355. if (plotBackgroundImage) {
  11356. if (!plotBGImage) {
  11357. chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight)
  11358. .add();
  11359. } else {
  11360. plotBGImage.animate(plotBox);
  11361. }
  11362. }
  11363. // Plot clip
  11364. if (!clipRect) {
  11365. chart.clipRect = renderer.clipRect(clipBox);
  11366. } else {
  11367. clipRect.animate({
  11368. width: clipBox.width,
  11369. height: clipBox.height
  11370. });
  11371. }
  11372. // Plot area border
  11373. if (plotBorderWidth) {
  11374. if (!plotBorder) {
  11375. chart.plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, -plotBorderWidth)
  11376. .attr({
  11377. stroke: optionsChart.plotBorderColor,
  11378. 'stroke-width': plotBorderWidth,
  11379. fill: NONE,
  11380. zIndex: 1
  11381. })
  11382. .add();
  11383. } else {
  11384. plotBorder.strokeWidth = -plotBorderWidth;
  11385. plotBorder.animate(
  11386. plotBorder.crisp({ x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight }) //#3282 plotBorder should be negative
  11387. );
  11388. }
  11389. }
  11390. // reset
  11391. chart.isDirtyBox = false;
  11392. },
  11393. /**
  11394. * Detect whether a certain chart property is needed based on inspecting its options
  11395. * and series. This mainly applies to the chart.invert property, and in extensions to
  11396. * the chart.angular and chart.polar properties.
  11397. */
  11398. propFromSeries: function () {
  11399. var chart = this,
  11400. optionsChart = chart.options.chart,
  11401. klass,
  11402. seriesOptions = chart.options.series,
  11403. i,
  11404. value;
  11405. each(['inverted', 'angular', 'polar'], function (key) {
  11406. // The default series type's class
  11407. klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType];
  11408. // Get the value from available chart-wide properties
  11409. value = (
  11410. chart[key] || // 1. it is set before
  11411. optionsChart[key] || // 2. it is set in the options
  11412. (klass && klass.prototype[key]) // 3. it's default series class requires it
  11413. );
  11414. // 4. Check if any the chart's series require it
  11415. i = seriesOptions && seriesOptions.length;
  11416. while (!value && i--) {
  11417. klass = seriesTypes[seriesOptions[i].type];
  11418. if (klass && klass.prototype[key]) {
  11419. value = true;
  11420. }
  11421. }
  11422. // Set the chart property
  11423. chart[key] = value;
  11424. });
  11425. },
  11426. /**
  11427. * Link two or more series together. This is done initially from Chart.render,
  11428. * and after Chart.addSeries and Series.remove.
  11429. */
  11430. linkSeries: function () {
  11431. var chart = this,
  11432. chartSeries = chart.series;
  11433. // Reset links
  11434. each(chartSeries, function (series) {
  11435. series.linkedSeries.length = 0;
  11436. });
  11437. // Apply new links
  11438. each(chartSeries, function (series) {
  11439. var linkedTo = series.options.linkedTo;
  11440. if (isString(linkedTo)) {
  11441. if (linkedTo === ':previous') {
  11442. linkedTo = chart.series[series.index - 1];
  11443. } else {
  11444. linkedTo = chart.get(linkedTo);
  11445. }
  11446. if (linkedTo && linkedTo.linkedParent !== series) { // #3341 avoid mutual linking
  11447. linkedTo.linkedSeries.push(series);
  11448. series.linkedParent = linkedTo;
  11449. series.visible = pick(series.options.visible, linkedTo.options.visible, series.visible); // #3879
  11450. }
  11451. }
  11452. });
  11453. },
  11454. /**
  11455. * Render series for the chart
  11456. */
  11457. renderSeries: function () {
  11458. each(this.series, function (serie) {
  11459. serie.translate();
  11460. serie.render();
  11461. });
  11462. },
  11463. /**
  11464. * Render labels for the chart
  11465. */
  11466. renderLabels: function () {
  11467. var chart = this,
  11468. labels = chart.options.labels;
  11469. if (labels.items) {
  11470. each(labels.items, function (label) {
  11471. var style = extend(labels.style, label.style),
  11472. x = pInt(style.left) + chart.plotLeft,
  11473. y = pInt(style.top) + chart.plotTop + 12;
  11474. // delete to prevent rewriting in IE
  11475. delete style.left;
  11476. delete style.top;
  11477. chart.renderer.text(
  11478. label.html,
  11479. x,
  11480. y
  11481. )
  11482. .attr({ zIndex: 2 })
  11483. .css(style)
  11484. .add();
  11485. });
  11486. }
  11487. },
  11488. /**
  11489. * Render all graphics for the chart
  11490. */
  11491. render: function () {
  11492. var chart = this,
  11493. axes = chart.axes,
  11494. renderer = chart.renderer,
  11495. options = chart.options,
  11496. tempWidth,
  11497. tempHeight,
  11498. redoHorizontal,
  11499. redoVertical;
  11500. // Title
  11501. chart.setTitle();
  11502. // Legend
  11503. chart.legend = new Legend(chart, options.legend);
  11504. // Get stacks
  11505. if (chart.getStacks) {
  11506. chart.getStacks();
  11507. }
  11508. // Get chart margins
  11509. chart.getMargins(true);
  11510. chart.setChartSize();
  11511. // Record preliminary dimensions for later comparison
  11512. tempWidth = chart.plotWidth;
  11513. tempHeight = chart.plotHeight = chart.plotHeight - 21; // 21 is the most common correction for X axis labels
  11514. // Get margins by pre-rendering axes
  11515. each(axes, function (axis) {
  11516. axis.setScale();
  11517. });
  11518. chart.getAxisMargins();
  11519. // If the plot area size has changed significantly, calculate tick positions again
  11520. redoHorizontal = tempWidth / chart.plotWidth > 1.1;
  11521. redoVertical = tempHeight / chart.plotHeight > 1.05; // Height is more sensitive
  11522. if (redoHorizontal || redoVertical) {
  11523. chart.maxTicks = null; // reset for second pass
  11524. each(axes, function (axis) {
  11525. if ((axis.horiz && redoHorizontal) || (!axis.horiz && redoVertical)) {
  11526. axis.setTickInterval(true); // update to reflect the new margins
  11527. }
  11528. });
  11529. chart.getMargins(); // second pass to check for new labels
  11530. }
  11531. // Draw the borders and backgrounds
  11532. chart.drawChartBox();
  11533. // Axes
  11534. if (chart.hasCartesianSeries) {
  11535. each(axes, function (axis) {
  11536. if (axis.visible) {
  11537. axis.render();
  11538. }
  11539. });
  11540. }
  11541. // The series
  11542. if (!chart.seriesGroup) {
  11543. chart.seriesGroup = renderer.g('series-group')
  11544. .attr({ zIndex: 3 })
  11545. .add();
  11546. }
  11547. chart.renderSeries();
  11548. // Labels
  11549. chart.renderLabels();
  11550. // Credits
  11551. chart.showCredits(options.credits);
  11552. // Set flag
  11553. chart.hasRendered = true;
  11554. },
  11555. /**
  11556. * Show chart credits based on config options
  11557. */
  11558. showCredits: function (credits) {
  11559. if (credits.enabled && !this.credits) {
  11560. this.credits = this.renderer.text(
  11561. credits.text,
  11562. 0,
  11563. 0
  11564. )
  11565. .on('click', function () {
  11566. if (credits.href) {
  11567. win.location.href = credits.href;
  11568. }
  11569. })
  11570. .attr({
  11571. align: credits.position.align,
  11572. zIndex: 8
  11573. })
  11574. .css(credits.style)
  11575. .add()
  11576. .align(credits.position);
  11577. }
  11578. },
  11579. /**
  11580. * Clean up memory usage
  11581. */
  11582. destroy: function () {
  11583. var chart = this,
  11584. axes = chart.axes,
  11585. series = chart.series,
  11586. container = chart.container,
  11587. i,
  11588. parentNode = container && container.parentNode;
  11589. // fire the chart.destoy event
  11590. fireEvent(chart, 'destroy');
  11591. // Delete the chart from charts lookup array
  11592. charts[chart.index] = UNDEFINED;
  11593. chartCount--;
  11594. chart.renderTo.removeAttribute('data-highcharts-chart');
  11595. // remove events
  11596. removeEvent(chart);
  11597. // ==== Destroy collections:
  11598. // Destroy axes
  11599. i = axes.length;
  11600. while (i--) {
  11601. axes[i] = axes[i].destroy();
  11602. }
  11603. // Destroy each series
  11604. i = series.length;
  11605. while (i--) {
  11606. series[i] = series[i].destroy();
  11607. }
  11608. // ==== Destroy chart properties:
  11609. each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage',
  11610. 'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer', 'scroller',
  11611. 'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'], function (name) {
  11612. var prop = chart[name];
  11613. if (prop && prop.destroy) {
  11614. chart[name] = prop.destroy();
  11615. }
  11616. });
  11617. // remove container and all SVG
  11618. if (container) { // can break in IE when destroyed before finished loading
  11619. container.innerHTML = '';
  11620. removeEvent(container);
  11621. if (parentNode) {
  11622. discardElement(container);
  11623. }
  11624. }
  11625. // clean it all up
  11626. for (i in chart) {
  11627. delete chart[i];
  11628. }
  11629. },
  11630. /**
  11631. * VML namespaces can't be added until after complete. Listening
  11632. * for Perini's doScroll hack is not enough.
  11633. */
  11634. isReadyToRender: function () {
  11635. var chart = this;
  11636. // Note: win == win.top is required
  11637. if ((!hasSVG && (win == win.top && doc.readyState !== 'complete')) || (useCanVG && !win.canvg)) { // eslint-disable-line eqeqeq
  11638. if (useCanVG) {
  11639. // Delay rendering until canvg library is downloaded and ready
  11640. CanVGController.push(function () {
  11641. chart.firstRender();
  11642. }, chart.options.global.canvasToolsURL);
  11643. } else {
  11644. doc.attachEvent('onreadystatechange', function () {
  11645. doc.detachEvent('onreadystatechange', chart.firstRender);
  11646. if (doc.readyState === 'complete') {
  11647. chart.firstRender();
  11648. }
  11649. });
  11650. }
  11651. return false;
  11652. }
  11653. return true;
  11654. },
  11655. /**
  11656. * Prepare for first rendering after all data are loaded
  11657. */
  11658. firstRender: function () {
  11659. var chart = this,
  11660. options = chart.options;
  11661. // Check whether the chart is ready to render
  11662. if (!chart.isReadyToRender()) {
  11663. return;
  11664. }
  11665. // Create the container
  11666. chart.getContainer();
  11667. // Run an early event after the container and renderer are established
  11668. fireEvent(chart, 'init');
  11669. chart.resetMargins();
  11670. chart.setChartSize();
  11671. // Set the common chart properties (mainly invert) from the given series
  11672. chart.propFromSeries();
  11673. // get axes
  11674. chart.getAxes();
  11675. // Initialize the series
  11676. each(options.series || [], function (serieOptions) {
  11677. chart.initSeries(serieOptions);
  11678. });
  11679. chart.linkSeries();
  11680. // Run an event after axes and series are initialized, but before render. At this stage,
  11681. // the series data is indexed and cached in the xData and yData arrays, so we can access
  11682. // those before rendering. Used in Highstock.
  11683. fireEvent(chart, 'beforeRender');
  11684. // depends on inverted and on margins being set
  11685. if (Highcharts.Pointer) {
  11686. chart.pointer = new Pointer(chart, options);
  11687. }
  11688. chart.render();
  11689. // add canvas
  11690. chart.renderer.draw();
  11691. // Fire the load event if there are no external images
  11692. if (!chart.renderer.imgCount && chart.onload) {
  11693. chart.onload();
  11694. }
  11695. // If the chart was rendered outside the top container, put it back in (#3679)
  11696. chart.cloneRenderTo(true);
  11697. },
  11698. /**
  11699. * On chart load
  11700. */
  11701. onload: function () {
  11702. var chart = this;
  11703. // Run callbacks
  11704. each([this.callback].concat(this.callbacks), function (fn) {
  11705. if (fn && chart.index !== undefined) { // Chart destroyed in its own callback (#3600)
  11706. fn.apply(chart, [chart]);
  11707. }
  11708. });
  11709. fireEvent(chart, 'load');
  11710. // Don't run again
  11711. this.onload = null;
  11712. },
  11713. /**
  11714. * Creates arrays for spacing and margin from given options.
  11715. */
  11716. splashArray: function (target, options) {
  11717. var oVar = options[target],
  11718. tArray = isObject(oVar) ? oVar : [oVar, oVar, oVar, oVar];
  11719. return [pick(options[target + 'Top'], tArray[0]),
  11720. pick(options[target + 'Right'], tArray[1]),
  11721. pick(options[target + 'Bottom'], tArray[2]),
  11722. pick(options[target + 'Left'], tArray[3])];
  11723. }
  11724. }; // end Chart
  11725. var CenteredSeriesMixin = Highcharts.CenteredSeriesMixin = {
  11726. /**
  11727. * Get the center of the pie based on the size and center options relative to the
  11728. * plot area. Borrowed by the polar and gauge series types.
  11729. */
  11730. getCenter: function () {
  11731. var options = this.options,
  11732. chart = this.chart,
  11733. slicingRoom = 2 * (options.slicedOffset || 0),
  11734. handleSlicingRoom,
  11735. plotWidth = chart.plotWidth - 2 * slicingRoom,
  11736. plotHeight = chart.plotHeight - 2 * slicingRoom,
  11737. centerOption = options.center,
  11738. positions = [pick(centerOption[0], '50%'), pick(centerOption[1], '50%'), options.size || '100%', options.innerSize || 0],
  11739. smallestSize = mathMin(plotWidth, plotHeight),
  11740. i,
  11741. value;
  11742. for (i = 0; i < 4; ++i) {
  11743. value = positions[i];
  11744. handleSlicingRoom = i < 2 || (i === 2 && /%$/.test(value));
  11745. // i == 0: centerX, relative to width
  11746. // i == 1: centerY, relative to height
  11747. // i == 2: size, relative to smallestSize
  11748. // i == 3: innerSize, relative to size
  11749. positions[i] = relativeLength(value, [plotWidth, plotHeight, smallestSize, positions[2]][i]) +
  11750. (handleSlicingRoom ? slicingRoom : 0);
  11751. }
  11752. // innerSize cannot be larger than size (#3632)
  11753. if (positions[3] > positions[2]) {
  11754. positions[3] = positions[2];
  11755. }
  11756. return positions;
  11757. }
  11758. };
  11759. /**
  11760. * The Point object and prototype. Inheritable and used as base for PiePoint
  11761. */
  11762. var Point = function () {};
  11763. Point.prototype = {
  11764. /**
  11765. * Initialize the point
  11766. * @param {Object} series The series object containing this point
  11767. * @param {Object} options The data in either number, array or object format
  11768. */
  11769. init: function (series, options, x) {
  11770. var point = this,
  11771. colors;
  11772. point.series = series;
  11773. point.color = series.color; // #3445
  11774. point.applyOptions(options, x);
  11775. point.pointAttr = {};
  11776. if (series.options.colorByPoint) {
  11777. colors = series.options.colors || series.chart.options.colors;
  11778. point.color = point.color || colors[series.colorCounter++];
  11779. // loop back to zero
  11780. if (series.colorCounter === colors.length) {
  11781. series.colorCounter = 0;
  11782. }
  11783. }
  11784. series.chart.pointCount++;
  11785. return point;
  11786. },
  11787. /**
  11788. * Apply the options containing the x and y data and possible some extra properties.
  11789. * This is called on point init or from point.update.
  11790. *
  11791. * @param {Object} options
  11792. */
  11793. applyOptions: function (options, x) {
  11794. var point = this,
  11795. series = point.series,
  11796. pointValKey = series.options.pointValKey || series.pointValKey;
  11797. options = Point.prototype.optionsToObject.call(this, options);
  11798. // copy options directly to point
  11799. extend(point, options);
  11800. point.options = point.options ? extend(point.options, options) : options;
  11801. // Since options are copied into the Point instance, some accidental options must be shielded (#5681)
  11802. if (options.group) {
  11803. delete point.group;
  11804. }
  11805. // For higher dimension series types. For instance, for ranges, point.y is mapped to point.low.
  11806. if (pointValKey) {
  11807. point.y = point[pointValKey];
  11808. }
  11809. point.isNull = pick(
  11810. point.isValid && !point.isValid(),
  11811. point.x === null || !isNumber(point.y, true)
  11812. ); // #3571, check for NaN
  11813. // If no x is set by now, get auto incremented value. All points must have an
  11814. // x value, however the y value can be null to create a gap in the series
  11815. if ('name' in point && x === undefined && series.xAxis && series.xAxis.hasNames) {
  11816. point.x = series.xAxis.nameToX(point);
  11817. }
  11818. if (point.x === undefined && series) {
  11819. if (x === undefined) {
  11820. point.x = series.autoIncrement(point);
  11821. } else {
  11822. point.x = x;
  11823. }
  11824. }
  11825. return point;
  11826. },
  11827. /**
  11828. * Transform number or array configs into objects
  11829. */
  11830. optionsToObject: function (options) {
  11831. var ret = {},
  11832. series = this.series,
  11833. keys = series.options.keys,
  11834. pointArrayMap = keys || series.pointArrayMap || ['y'],
  11835. valueCount = pointArrayMap.length,
  11836. firstItemType,
  11837. i = 0,
  11838. j = 0;
  11839. if (isNumber(options) || options === null) {
  11840. ret[pointArrayMap[0]] = options;
  11841. } else if (isArray(options)) {
  11842. // with leading x value
  11843. if (!keys && options.length > valueCount) {
  11844. firstItemType = typeof options[0];
  11845. if (firstItemType === 'string') {
  11846. ret.name = options[0];
  11847. } else if (firstItemType === 'number') {
  11848. ret.x = options[0];
  11849. }
  11850. i++;
  11851. }
  11852. while (j < valueCount) {
  11853. if (!keys || options[i] !== undefined) { // Skip undefined positions for keys
  11854. ret[pointArrayMap[j]] = options[i];
  11855. }
  11856. i++;
  11857. j++;
  11858. }
  11859. } else if (typeof options === 'object') {
  11860. ret = options;
  11861. // This is the fastest way to detect if there are individual point dataLabels that need
  11862. // to be considered in drawDataLabels. These can only occur in object configs.
  11863. if (options.dataLabels) {
  11864. series._hasPointLabels = true;
  11865. }
  11866. // Same approach as above for markers
  11867. if (options.marker) {
  11868. series._hasPointMarkers = true;
  11869. }
  11870. }
  11871. return ret;
  11872. },
  11873. /**
  11874. * Destroy a point to clear memory. Its reference still stays in series.data.
  11875. */
  11876. destroy: function () {
  11877. var point = this,
  11878. series = point.series,
  11879. chart = series.chart,
  11880. hoverPoints = chart.hoverPoints,
  11881. prop;
  11882. chart.pointCount--;
  11883. if (hoverPoints) {
  11884. point.setState();
  11885. erase(hoverPoints, point);
  11886. if (!hoverPoints.length) {
  11887. chart.hoverPoints = null;
  11888. }
  11889. }
  11890. if (point === chart.hoverPoint) {
  11891. point.onMouseOut();
  11892. }
  11893. // remove all events
  11894. if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive
  11895. removeEvent(point);
  11896. point.destroyElements();
  11897. }
  11898. if (point.legendItem) { // pies have legend items
  11899. chart.legend.destroyItem(point);
  11900. }
  11901. for (prop in point) {
  11902. point[prop] = null;
  11903. }
  11904. },
  11905. /**
  11906. * Destroy SVG elements associated with the point
  11907. */
  11908. destroyElements: function () {
  11909. var point = this,
  11910. props = ['graphic', 'dataLabel', 'dataLabelUpper', 'connector', 'shadowGroup'],
  11911. prop,
  11912. i = 6;
  11913. while (i--) {
  11914. prop = props[i];
  11915. if (point[prop]) {
  11916. point[prop] = point[prop].destroy();
  11917. }
  11918. }
  11919. },
  11920. /**
  11921. * Return the configuration hash needed for the data label and tooltip formatters
  11922. */
  11923. getLabelConfig: function () {
  11924. return {
  11925. x: this.category,
  11926. y: this.y,
  11927. color: this.color,
  11928. key: this.name || this.category,
  11929. series: this.series,
  11930. point: this,
  11931. percentage: this.percentage,
  11932. total: this.total || this.stackTotal
  11933. };
  11934. },
  11935. /**
  11936. * Extendable method for formatting each point's tooltip line
  11937. *
  11938. * @return {String} A string to be concatenated in to the common tooltip text
  11939. */
  11940. tooltipFormatter: function (pointFormat) {
  11941. // Insert options for valueDecimals, valuePrefix, and valueSuffix
  11942. var series = this.series,
  11943. seriesTooltipOptions = series.tooltipOptions,
  11944. valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''),
  11945. valuePrefix = seriesTooltipOptions.valuePrefix || '',
  11946. valueSuffix = seriesTooltipOptions.valueSuffix || '';
  11947. // Loop over the point array map and replace unformatted values with sprintf formatting markup
  11948. each(series.pointArrayMap || ['y'], function (key) {
  11949. key = '{point.' + key; // without the closing bracket
  11950. if (valuePrefix || valueSuffix) {
  11951. pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix);
  11952. }
  11953. pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}');
  11954. });
  11955. return format(pointFormat, {
  11956. point: this,
  11957. series: this.series
  11958. });
  11959. },
  11960. /**
  11961. * Fire an event on the Point object.
  11962. * @param {String} eventType
  11963. * @param {Object} eventArgs Additional event arguments
  11964. * @param {Function} defaultFunction Default event handler
  11965. */
  11966. firePointEvent: function (eventType, eventArgs, defaultFunction) {
  11967. var point = this,
  11968. series = this.series,
  11969. seriesOptions = series.options;
  11970. // load event handlers on demand to save time on mouseover/out
  11971. if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) {
  11972. this.importEvents();
  11973. }
  11974. // add default handler if in selection mode
  11975. if (eventType === 'click' && seriesOptions.allowPointSelect) {
  11976. defaultFunction = function (event) {
  11977. // Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera
  11978. if (point.select) { // Could be destroyed by prior event handlers (#2911)
  11979. point.select(null, event.ctrlKey || event.metaKey || event.shiftKey);
  11980. }
  11981. };
  11982. }
  11983. fireEvent(this, eventType, eventArgs, defaultFunction);
  11984. },
  11985. visible: true
  11986. };
  11987. /**
  11988. * @classDescription The base function which all other series types inherit from. The data in the series is stored
  11989. * in various arrays.
  11990. *
  11991. * - First, series.options.data contains all the original config options for
  11992. * each point whether added by options or methods like series.addPoint.
  11993. * - Next, series.data contains those values converted to points, but in case the series data length
  11994. * exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It
  11995. * only contains the points that have been created on demand.
  11996. * - Then there's series.points that contains all currently visible point objects. In case of cropping,
  11997. * the cropped-away points are not part of this array. The series.points array starts at series.cropStart
  11998. * compared to series.data and series.options.data. If however the series data is grouped, these can't
  11999. * be correlated one to one.
  12000. * - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points.
  12001. * - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points.
  12002. *
  12003. * @param {Object} chart
  12004. * @param {Object} options
  12005. */
  12006. var Series = Highcharts.Series = function () {};
  12007. Series.prototype = {
  12008. isCartesian: true,
  12009. type: 'line',
  12010. pointClass: Point,
  12011. sorted: true, // requires the data to be sorted
  12012. requireSorting: true,
  12013. pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
  12014. stroke: 'lineColor',
  12015. 'stroke-width': 'lineWidth',
  12016. fill: 'fillColor',
  12017. r: 'radius'
  12018. },
  12019. directTouch: false,
  12020. axisTypes: ['xAxis', 'yAxis'],
  12021. colorCounter: 0,
  12022. parallelArrays: ['x', 'y'], // each point's x and y values are stored in this.xData and this.yData
  12023. init: function (chart, options) {
  12024. var series = this,
  12025. eventType,
  12026. events,
  12027. chartSeries = chart.series,
  12028. sortByIndex = function (a, b) {
  12029. return pick(a.options.index, a._i) - pick(b.options.index, b._i);
  12030. };
  12031. series.chart = chart;
  12032. series.options = options = series.setOptions(options); // merge with plotOptions
  12033. series.linkedSeries = [];
  12034. // bind the axes
  12035. series.bindAxes();
  12036. // set some variables
  12037. extend(series, {
  12038. name: options.name,
  12039. state: NORMAL_STATE,
  12040. pointAttr: {},
  12041. visible: options.visible !== false, // true by default
  12042. selected: options.selected === true // false by default
  12043. });
  12044. // special
  12045. if (useCanVG) {
  12046. options.animation = false;
  12047. }
  12048. // register event listeners
  12049. events = options.events;
  12050. for (eventType in events) {
  12051. addEvent(series, eventType, events[eventType]);
  12052. }
  12053. if (
  12054. (events && events.click) ||
  12055. (options.point && options.point.events && options.point.events.click) ||
  12056. options.allowPointSelect
  12057. ) {
  12058. chart.runTrackerClick = true;
  12059. }
  12060. series.getColor();
  12061. series.getSymbol();
  12062. // Set the data
  12063. each(series.parallelArrays, function (key) {
  12064. series[key + 'Data'] = [];
  12065. });
  12066. series.setData(options.data, false);
  12067. // Mark cartesian
  12068. if (series.isCartesian) {
  12069. chart.hasCartesianSeries = true;
  12070. }
  12071. // Register it in the chart
  12072. chartSeries.push(series);
  12073. series._i = chartSeries.length - 1;
  12074. // Sort series according to index option (#248, #1123, #2456)
  12075. stableSort(chartSeries, sortByIndex);
  12076. if (this.yAxis) {
  12077. stableSort(this.yAxis.series, sortByIndex);
  12078. }
  12079. each(chartSeries, function (series, i) {
  12080. series.index = i;
  12081. series.name = series.name || 'Series ' + (i + 1);
  12082. });
  12083. },
  12084. /**
  12085. * Set the xAxis and yAxis properties of cartesian series, and register the series
  12086. * in the axis.series array
  12087. */
  12088. bindAxes: function () {
  12089. var series = this,
  12090. seriesOptions = series.options,
  12091. chart = series.chart,
  12092. axisOptions;
  12093. each(series.axisTypes || [], function (AXIS) { // repeat for xAxis and yAxis
  12094. each(chart[AXIS], function (axis) { // loop through the chart's axis objects
  12095. axisOptions = axis.options;
  12096. // apply if the series xAxis or yAxis option mathches the number of the
  12097. // axis, or if undefined, use the first axis
  12098. if ((seriesOptions[AXIS] === axisOptions.index) ||
  12099. (seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) ||
  12100. (seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) {
  12101. // register this series in the axis.series lookup
  12102. axis.series.push(series);
  12103. // set this series.xAxis or series.yAxis reference
  12104. series[AXIS] = axis;
  12105. // mark dirty for redraw
  12106. axis.isDirty = true;
  12107. }
  12108. });
  12109. // The series needs an X and an Y axis
  12110. if (!series[AXIS] && series.optionalAxis !== AXIS) {
  12111. error(18, true);
  12112. }
  12113. });
  12114. },
  12115. /**
  12116. * For simple series types like line and column, the data values are held in arrays like
  12117. * xData and yData for quick lookup to find extremes and more. For multidimensional series
  12118. * like bubble and map, this can be extended with arrays like zData and valueData by
  12119. * adding to the series.parallelArrays array.
  12120. */
  12121. updateParallelArrays: function (point, i) {
  12122. var series = point.series,
  12123. args = arguments,
  12124. fn = isNumber(i) ?
  12125. // Insert the value in the given position
  12126. function (key) {
  12127. var val = key === 'y' && series.toYData ? series.toYData(point) : point[key];
  12128. series[key + 'Data'][i] = val;
  12129. } :
  12130. // Apply the method specified in i with the following arguments as arguments
  12131. function (key) {
  12132. Array.prototype[i].apply(series[key + 'Data'], Array.prototype.slice.call(args, 2));
  12133. };
  12134. each(series.parallelArrays, fn);
  12135. },
  12136. /**
  12137. * Return an auto incremented x value based on the pointStart and pointInterval options.
  12138. * This is only used if an x value is not given for the point that calls autoIncrement.
  12139. */
  12140. autoIncrement: function () {
  12141. var options = this.options,
  12142. xIncrement = this.xIncrement,
  12143. date,
  12144. pointInterval,
  12145. pointIntervalUnit = options.pointIntervalUnit;
  12146. xIncrement = pick(xIncrement, options.pointStart, 0);
  12147. this.pointInterval = pointInterval = pick(this.pointInterval, options.pointInterval, 1);
  12148. // Added code for pointInterval strings
  12149. if (pointIntervalUnit) {
  12150. date = new Date(xIncrement);
  12151. if (pointIntervalUnit === 'day') {
  12152. date = +date[setDate](date[getDate]() + pointInterval);
  12153. } else if (pointIntervalUnit === 'month') {
  12154. date = +date[setMonth](date[getMonth]() + pointInterval);
  12155. } else if (pointIntervalUnit === 'year') {
  12156. date = +date[setFullYear](date[getFullYear]() + pointInterval);
  12157. }
  12158. pointInterval = date - xIncrement;
  12159. }
  12160. this.xIncrement = xIncrement + pointInterval;
  12161. return xIncrement;
  12162. },
  12163. /**
  12164. * Set the series options by merging from the options tree
  12165. * @param {Object} itemOptions
  12166. */
  12167. setOptions: function (itemOptions) {
  12168. var chart = this.chart,
  12169. chartOptions = chart.options,
  12170. plotOptions = chartOptions.plotOptions,
  12171. userOptions = chart.userOptions || {},
  12172. userPlotOptions = userOptions.plotOptions || {},
  12173. typeOptions = plotOptions[this.type],
  12174. options,
  12175. zones;
  12176. this.userOptions = itemOptions;
  12177. // General series options take precedence over type options because otherwise, default
  12178. // type options like column.animation would be overwritten by the general option.
  12179. // But issues have been raised here (#3881), and the solution may be to distinguish
  12180. // between default option and userOptions like in the tooltip below.
  12181. options = merge(
  12182. typeOptions,
  12183. plotOptions.series,
  12184. itemOptions
  12185. );
  12186. // The tooltip options are merged between global and series specific options
  12187. this.tooltipOptions = merge(
  12188. defaultOptions.tooltip,
  12189. defaultOptions.plotOptions[this.type].tooltip,
  12190. userOptions.tooltip,
  12191. userPlotOptions.series && userPlotOptions.series.tooltip,
  12192. userPlotOptions[this.type] && userPlotOptions[this.type].tooltip,
  12193. itemOptions.tooltip
  12194. );
  12195. // Delete marker object if not allowed (#1125)
  12196. if (typeOptions.marker === null) {
  12197. delete options.marker;
  12198. }
  12199. // Handle color zones
  12200. this.zoneAxis = options.zoneAxis;
  12201. zones = this.zones = (options.zones || []).slice();
  12202. if ((options.negativeColor || options.negativeFillColor) && !options.zones) {
  12203. zones.push({
  12204. value: options[this.zoneAxis + 'Threshold'] || options.threshold || 0,
  12205. color: options.negativeColor,
  12206. fillColor: options.negativeFillColor
  12207. });
  12208. }
  12209. if (zones.length) { // Push one extra zone for the rest
  12210. if (defined(zones[zones.length - 1].value)) {
  12211. zones.push({
  12212. color: this.color,
  12213. fillColor: this.fillColor
  12214. });
  12215. }
  12216. }
  12217. return options;
  12218. },
  12219. getCyclic: function (prop, value, defaults) {
  12220. var i,
  12221. userOptions = this.userOptions,
  12222. indexName = '_' + prop + 'Index',
  12223. counterName = prop + 'Counter';
  12224. if (!value) {
  12225. if (defined(userOptions[indexName])) { // after Series.update()
  12226. i = userOptions[indexName];
  12227. } else {
  12228. userOptions[indexName] = i = this.chart[counterName] % defaults.length;
  12229. this.chart[counterName] += 1;
  12230. }
  12231. value = defaults[i];
  12232. }
  12233. this[prop] = value;
  12234. },
  12235. /**
  12236. * Get the series' color
  12237. */
  12238. getColor: function () {
  12239. if (this.options.colorByPoint) {
  12240. this.options.color = null; // #4359, selected slice got series.color even when colorByPoint was set.
  12241. } else {
  12242. this.getCyclic('color', this.options.color || defaultPlotOptions[this.type].color, this.chart.options.colors);
  12243. }
  12244. },
  12245. /**
  12246. * Get the series' symbol
  12247. */
  12248. getSymbol: function () {
  12249. var seriesMarkerOption = this.options.marker;
  12250. this.getCyclic('symbol', seriesMarkerOption.symbol, this.chart.options.symbols);
  12251. // don't substract radius in image symbols (#604)
  12252. if (/^url/.test(this.symbol)) {
  12253. seriesMarkerOption.radius = 0;
  12254. }
  12255. },
  12256. drawLegendSymbol: LegendSymbolMixin.drawLineMarker,
  12257. /**
  12258. * Replace the series data with a new set of data
  12259. * @param {Object} data
  12260. * @param {Object} redraw
  12261. */
  12262. setData: function (data, redraw, animation, updatePoints) {
  12263. var series = this,
  12264. oldData = series.points,
  12265. oldDataLength = (oldData && oldData.length) || 0,
  12266. dataLength,
  12267. options = series.options,
  12268. chart = series.chart,
  12269. firstPoint = null,
  12270. xAxis = series.xAxis,
  12271. i,
  12272. turboThreshold = options.turboThreshold,
  12273. pt,
  12274. xData = this.xData,
  12275. yData = this.yData,
  12276. pointArrayMap = series.pointArrayMap,
  12277. valueCount = pointArrayMap && pointArrayMap.length;
  12278. data = data || [];
  12279. dataLength = data.length;
  12280. redraw = pick(redraw, true);
  12281. // If the point count is the same as is was, just run Point.update which is
  12282. // cheaper, allows animation, and keeps references to points.
  12283. if (updatePoints !== false && dataLength && oldDataLength === dataLength && !series.cropped && !series.hasGroupedData && series.visible) {
  12284. each(data, function (point, i) {
  12285. // .update doesn't exist on a linked, hidden series (#3709)
  12286. if (oldData[i].update && point !== options.data[i]) {
  12287. oldData[i].update(point, false, null, false);
  12288. }
  12289. });
  12290. } else {
  12291. // Reset properties
  12292. series.xIncrement = null;
  12293. series.colorCounter = 0; // for series with colorByPoint (#1547)
  12294. // Update parallel arrays
  12295. each(this.parallelArrays, function (key) {
  12296. series[key + 'Data'].length = 0;
  12297. });
  12298. // In turbo mode, only one- or twodimensional arrays of numbers are allowed. The
  12299. // first value is tested, and we assume that all the rest are defined the same
  12300. // way. Although the 'for' loops are similar, they are repeated inside each
  12301. // if-else conditional for max performance.
  12302. if (turboThreshold && dataLength > turboThreshold) {
  12303. // find the first non-null point
  12304. i = 0;
  12305. while (firstPoint === null && i < dataLength) {
  12306. firstPoint = data[i];
  12307. i++;
  12308. }
  12309. if (isNumber(firstPoint)) { // assume all points are numbers
  12310. for (i = 0; i < dataLength; i++) {
  12311. xData[i] = this.autoIncrement();
  12312. yData[i] = data[i];
  12313. }
  12314. } else if (isArray(firstPoint)) { // assume all points are arrays
  12315. if (valueCount) { // [x, low, high] or [x, o, h, l, c]
  12316. for (i = 0; i < dataLength; i++) {
  12317. pt = data[i];
  12318. xData[i] = pt[0];
  12319. yData[i] = pt.slice(1, valueCount + 1);
  12320. }
  12321. } else { // [x, y]
  12322. for (i = 0; i < dataLength; i++) {
  12323. pt = data[i];
  12324. xData[i] = pt[0];
  12325. yData[i] = pt[1];
  12326. }
  12327. }
  12328. } else {
  12329. error(12); // Highcharts expects configs to be numbers or arrays in turbo mode
  12330. }
  12331. } else {
  12332. for (i = 0; i < dataLength; i++) {
  12333. if (data[i] !== UNDEFINED) { // stray commas in oldIE
  12334. pt = { series: series };
  12335. series.pointClass.prototype.applyOptions.apply(pt, [data[i]]);
  12336. series.updateParallelArrays(pt, i);
  12337. }
  12338. }
  12339. }
  12340. // Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON
  12341. if (isString(yData[0])) {
  12342. error(14, true);
  12343. }
  12344. series.data = [];
  12345. series.options.data = series.userOptions.data = data;
  12346. // destroy old points
  12347. i = oldDataLength;
  12348. while (i--) {
  12349. if (oldData[i] && oldData[i].destroy) {
  12350. oldData[i].destroy();
  12351. }
  12352. }
  12353. // reset minRange (#878)
  12354. if (xAxis) {
  12355. xAxis.minRange = xAxis.userMinRange;
  12356. }
  12357. // redraw
  12358. series.isDirty = series.isDirtyData = chart.isDirtyBox = true;
  12359. animation = false;
  12360. }
  12361. // Typically for pie series, points need to be processed and generated
  12362. // prior to rendering the legend
  12363. if (options.legendType === 'point') {
  12364. this.processData();
  12365. this.generatePoints();
  12366. }
  12367. if (redraw) {
  12368. chart.redraw(animation);
  12369. }
  12370. },
  12371. /**
  12372. * Process the data by cropping away unused data points if the series is longer
  12373. * than the crop threshold. This saves computing time for lage series.
  12374. */
  12375. processData: function (force) {
  12376. var series = this,
  12377. processedXData = series.xData, // copied during slice operation below
  12378. processedYData = series.yData,
  12379. dataLength = processedXData.length,
  12380. croppedData,
  12381. cropStart = 0,
  12382. cropped,
  12383. distance,
  12384. closestPointRange,
  12385. xAxis = series.xAxis,
  12386. i, // loop variable
  12387. options = series.options,
  12388. cropThreshold = options.cropThreshold,
  12389. getExtremesFromAll = series.getExtremesFromAll || options.getExtremesFromAll, // #4599
  12390. isCartesian = series.isCartesian,
  12391. xExtremes,
  12392. val2lin = xAxis && xAxis.val2lin,
  12393. isLog = xAxis && xAxis.isLog,
  12394. min,
  12395. max;
  12396. // If the series data or axes haven't changed, don't go through this. Return false to pass
  12397. // the message on to override methods like in data grouping.
  12398. if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) {
  12399. return false;
  12400. }
  12401. if (xAxis) {
  12402. xExtremes = xAxis.getExtremes(); // corrected for log axis (#3053)
  12403. min = xExtremes.min;
  12404. max = xExtremes.max;
  12405. }
  12406. // optionally filter out points outside the plot area
  12407. if (isCartesian && series.sorted && !getExtremesFromAll && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) {
  12408. // it's outside current extremes
  12409. if (processedXData[dataLength - 1] < min || processedXData[0] > max) {
  12410. processedXData = [];
  12411. processedYData = [];
  12412. // only crop if it's actually spilling out
  12413. } else if (processedXData[0] < min || processedXData[dataLength - 1] > max) {
  12414. croppedData = this.cropData(series.xData, series.yData, min, max);
  12415. processedXData = croppedData.xData;
  12416. processedYData = croppedData.yData;
  12417. cropStart = croppedData.start;
  12418. cropped = true;
  12419. }
  12420. }
  12421. // Find the closest distance between processed points
  12422. i = processedXData.length || 1;
  12423. while (--i) {
  12424. distance = isLog ?
  12425. val2lin(processedXData[i]) - val2lin(processedXData[i - 1]) :
  12426. processedXData[i] - processedXData[i - 1];
  12427. if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) {
  12428. closestPointRange = distance;
  12429. // Unsorted data is not supported by the line tooltip, as well as data grouping and
  12430. // navigation in Stock charts (#725) and width calculation of columns (#1900)
  12431. } else if (distance < 0 && series.requireSorting) {
  12432. error(15);
  12433. }
  12434. }
  12435. // Record the properties
  12436. series.cropped = cropped; // undefined or true
  12437. series.cropStart = cropStart;
  12438. series.processedXData = processedXData;
  12439. series.processedYData = processedYData;
  12440. series.closestPointRange = closestPointRange;
  12441. },
  12442. /**
  12443. * Iterate over xData and crop values between min and max. Returns object containing crop start/end
  12444. * cropped xData with corresponding part of yData, dataMin and dataMax within the cropped range
  12445. */
  12446. cropData: function (xData, yData, min, max) {
  12447. var dataLength = xData.length,
  12448. cropStart = 0,
  12449. cropEnd = dataLength,
  12450. cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside
  12451. i,
  12452. j;
  12453. // iterate up to find slice start
  12454. for (i = 0; i < dataLength; i++) {
  12455. if (xData[i] >= min) {
  12456. cropStart = mathMax(0, i - cropShoulder);
  12457. break;
  12458. }
  12459. }
  12460. // proceed to find slice end
  12461. for (j = i; j < dataLength; j++) {
  12462. if (xData[j] > max) {
  12463. cropEnd = j + cropShoulder;
  12464. break;
  12465. }
  12466. }
  12467. return {
  12468. xData: xData.slice(cropStart, cropEnd),
  12469. yData: yData.slice(cropStart, cropEnd),
  12470. start: cropStart,
  12471. end: cropEnd
  12472. };
  12473. },
  12474. /**
  12475. * Generate the data point after the data has been processed by cropping away
  12476. * unused points and optionally grouped in Highcharts Stock.
  12477. */
  12478. generatePoints: function () {
  12479. var series = this,
  12480. options = series.options,
  12481. dataOptions = options.data,
  12482. data = series.data,
  12483. dataLength,
  12484. processedXData = series.processedXData,
  12485. processedYData = series.processedYData,
  12486. pointClass = series.pointClass,
  12487. processedDataLength = processedXData.length,
  12488. cropStart = series.cropStart || 0,
  12489. cursor,
  12490. hasGroupedData = series.hasGroupedData,
  12491. point,
  12492. points = [],
  12493. i;
  12494. if (!data && !hasGroupedData) {
  12495. var arr = [];
  12496. arr.length = dataOptions.length;
  12497. data = series.data = arr;
  12498. }
  12499. for (i = 0; i < processedDataLength; i++) {
  12500. cursor = cropStart + i;
  12501. if (!hasGroupedData) {
  12502. if (data[cursor]) {
  12503. point = data[cursor];
  12504. } else if (dataOptions[cursor] !== UNDEFINED) { // #970
  12505. data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]);
  12506. }
  12507. points[i] = point;
  12508. } else {
  12509. // splat the y data in case of ohlc data array
  12510. points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i])));
  12511. points[i].dataGroup = series.groupMap[i];
  12512. }
  12513. points[i].index = cursor; // For faster access in Point.update
  12514. }
  12515. // Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when
  12516. // swithching view from non-grouped data to grouped data (#637)
  12517. if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) {
  12518. for (i = 0; i < dataLength; i++) {
  12519. if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points
  12520. i += processedDataLength;
  12521. }
  12522. if (data[i]) {
  12523. data[i].destroyElements();
  12524. data[i].plotX = UNDEFINED; // #1003
  12525. }
  12526. }
  12527. }
  12528. series.data = data;
  12529. series.points = points;
  12530. },
  12531. /**
  12532. * Calculate Y extremes for visible data
  12533. */
  12534. getExtremes: function (yData) {
  12535. var xAxis = this.xAxis,
  12536. yAxis = this.yAxis,
  12537. xData = this.processedXData,
  12538. yDataLength,
  12539. activeYData = [],
  12540. activeCounter = 0,
  12541. xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis
  12542. xMin = xExtremes.min,
  12543. xMax = xExtremes.max,
  12544. validValue,
  12545. withinRange,
  12546. x,
  12547. y,
  12548. i,
  12549. j;
  12550. yData = yData || this.stackedYData || this.processedYData || [];
  12551. yDataLength = yData.length;
  12552. for (i = 0; i < yDataLength; i++) {
  12553. x = xData[i];
  12554. y = yData[i];
  12555. // For points within the visible range, including the first point outside the
  12556. // visible range, consider y extremes
  12557. validValue = (isNumber(y, true) || isArray(y)) && (!yAxis.isLog || (y.length || y > 0));
  12558. withinRange = this.getExtremesFromAll || this.options.getExtremesFromAll || this.cropped ||
  12559. ((xData[i + 1] || x) >= xMin && (xData[i - 1] || x) <= xMax);
  12560. if (validValue && withinRange) {
  12561. j = y.length;
  12562. if (j) { // array, like ohlc or range data
  12563. while (j--) {
  12564. if (y[j] !== null) {
  12565. activeYData[activeCounter++] = y[j];
  12566. }
  12567. }
  12568. } else {
  12569. activeYData[activeCounter++] = y;
  12570. }
  12571. }
  12572. }
  12573. this.dataMin = arrayMin(activeYData);
  12574. this.dataMax = arrayMax(activeYData);
  12575. },
  12576. /**
  12577. * Translate data points from raw data values to chart specific positioning data
  12578. * needed later in drawPoints, drawGraph and drawTracker.
  12579. */
  12580. translate: function () {
  12581. if (!this.processedXData) { // hidden series
  12582. this.processData();
  12583. }
  12584. this.generatePoints();
  12585. var series = this,
  12586. options = series.options,
  12587. stacking = options.stacking,
  12588. xAxis = series.xAxis,
  12589. categories = xAxis.categories,
  12590. yAxis = series.yAxis,
  12591. points = series.points,
  12592. dataLength = points.length,
  12593. hasModifyValue = !!series.modifyValue,
  12594. i,
  12595. pointPlacement = options.pointPlacement,
  12596. dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement),
  12597. threshold = options.threshold,
  12598. stackThreshold = options.startFromThreshold ? threshold : 0,
  12599. plotX,
  12600. plotY,
  12601. lastPlotX,
  12602. stackIndicator,
  12603. closestPointRangePx = Number.MAX_VALUE;
  12604. // Translate each point
  12605. for (i = 0; i < dataLength; i++) {
  12606. var point = points[i],
  12607. xValue = point.x,
  12608. yValue = point.y,
  12609. yBottom = point.low,
  12610. stack = stacking && yAxis.stacks[(series.negStacks && yValue < (stackThreshold ? 0 : threshold) ? '-' : '') + series.stackKey],
  12611. pointStack,
  12612. stackValues;
  12613. // Discard disallowed y values for log axes (#3434)
  12614. if (yAxis.isLog && yValue !== null && yValue <= 0) {
  12615. point.isNull = true;
  12616. }
  12617. // Get the plotX translation
  12618. point.plotX = plotX = correctFloat( // #5236
  12619. mathMin(mathMax(-1e5, xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags')), 1e5) // #3923
  12620. );
  12621. // Calculate the bottom y value for stacked series
  12622. if (stacking && series.visible && !point.isNull && stack && stack[xValue]) {
  12623. stackIndicator = series.getStackIndicator(stackIndicator, xValue, series.index);
  12624. pointStack = stack[xValue];
  12625. stackValues = pointStack.points[stackIndicator.key];
  12626. yBottom = stackValues[0];
  12627. yValue = stackValues[1];
  12628. if (yBottom === stackThreshold && stackIndicator.key === stack[xValue].base) {
  12629. yBottom = pick(threshold, yAxis.min);
  12630. }
  12631. if (yAxis.isLog && yBottom <= 0) { // #1200, #1232
  12632. yBottom = null;
  12633. }
  12634. point.total = point.stackTotal = pointStack.total;
  12635. point.percentage = pointStack.total && (point.y / pointStack.total * 100);
  12636. point.stackY = yValue;
  12637. // Place the stack label
  12638. pointStack.setOffset(series.pointXOffset || 0, series.barW || 0);
  12639. }
  12640. // Set translated yBottom or remove it
  12641. point.yBottom = defined(yBottom) ?
  12642. yAxis.translate(yBottom, 0, 1, 0, 1) :
  12643. null;
  12644. // general hook, used for Highstock compare mode
  12645. if (hasModifyValue) {
  12646. yValue = series.modifyValue(yValue, point);
  12647. }
  12648. // Set the the plotY value, reset it for redraws
  12649. point.plotY = plotY = (typeof yValue === 'number' && yValue !== Infinity) ?
  12650. mathMin(mathMax(-1e5, yAxis.translate(yValue, 0, 1, 0, 1)), 1e5) : // #3201
  12651. UNDEFINED;
  12652. point.isInside = plotY !== UNDEFINED && plotY >= 0 && plotY <= yAxis.len && // #3519
  12653. plotX >= 0 && plotX <= xAxis.len;
  12654. // Set client related positions for mouse tracking
  12655. point.clientX = dynamicallyPlaced ? correctFloat(xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement)) : plotX; // #1514, #5383, #5518
  12656. point.negative = point.y < (threshold || 0);
  12657. // some API data
  12658. point.category = categories && categories[point.x] !== UNDEFINED ?
  12659. categories[point.x] : point.x;
  12660. // Determine auto enabling of markers (#3635, #5099)
  12661. if (!point.isNull) {
  12662. if (lastPlotX !== undefined) {
  12663. closestPointRangePx = mathMin(closestPointRangePx, mathAbs(plotX - lastPlotX));
  12664. }
  12665. lastPlotX = plotX;
  12666. }
  12667. }
  12668. series.closestPointRangePx = closestPointRangePx;
  12669. },
  12670. /**
  12671. * Return the series points with null points filtered out
  12672. */
  12673. getValidPoints: function (points, insideOnly) {
  12674. var chart = this.chart;
  12675. return grep(points || this.points || [], function isValidPoint(point) { // #3916, #5029
  12676. if (insideOnly && !chart.isInsidePlot(point.plotX, point.plotY, chart.inverted)) { // #5085
  12677. return false;
  12678. }
  12679. return !point.isNull;
  12680. });
  12681. },
  12682. /**
  12683. * Set the clipping for the series. For animated series it is called twice, first to initiate
  12684. * animating the clip then the second time without the animation to set the final clip.
  12685. */
  12686. setClip: function (animation) {
  12687. var chart = this.chart,
  12688. options = this.options,
  12689. renderer = chart.renderer,
  12690. inverted = chart.inverted,
  12691. seriesClipBox = this.clipBox,
  12692. clipBox = seriesClipBox || chart.clipBox,
  12693. sharedClipKey = this.sharedClipKey || ['_sharedClip', animation && animation.duration, animation && animation.easing, clipBox.height, options.xAxis, options.yAxis].join(','), // #4526
  12694. clipRect = chart[sharedClipKey],
  12695. markerClipRect = chart[sharedClipKey + 'm'];
  12696. // If a clipping rectangle with the same properties is currently present in the chart, use that.
  12697. if (!clipRect) {
  12698. // When animation is set, prepare the initial positions
  12699. if (animation) {
  12700. clipBox.width = 0;
  12701. chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect(
  12702. -99, // include the width of the first marker
  12703. inverted ? -chart.plotLeft : -chart.plotTop,
  12704. 99,
  12705. inverted ? chart.chartWidth : chart.chartHeight
  12706. );
  12707. }
  12708. chart[sharedClipKey] = clipRect = renderer.clipRect(clipBox);
  12709. // Create hashmap for series indexes
  12710. clipRect.count = { length: 0 };
  12711. }
  12712. if (animation) {
  12713. if (!clipRect.count[this.index]) {
  12714. clipRect.count[this.index] = true;
  12715. clipRect.count.length += 1;
  12716. }
  12717. }
  12718. if (options.clip !== false) {
  12719. this.group.clip(animation || seriesClipBox ? clipRect : chart.clipRect);
  12720. this.markerGroup.clip(markerClipRect);
  12721. this.sharedClipKey = sharedClipKey;
  12722. }
  12723. // Remove the shared clipping rectangle when all series are shown
  12724. if (!animation) {
  12725. if (clipRect.count[this.index]) {
  12726. delete clipRect.count[this.index];
  12727. clipRect.count.length -= 1;
  12728. }
  12729. if (clipRect.count.length === 0 && sharedClipKey && chart[sharedClipKey]) {
  12730. if (!seriesClipBox) {
  12731. chart[sharedClipKey] = chart[sharedClipKey].destroy();
  12732. }
  12733. if (chart[sharedClipKey + 'm']) {
  12734. chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy();
  12735. }
  12736. }
  12737. }
  12738. },
  12739. /**
  12740. * Animate in the series
  12741. */
  12742. animate: function (init) {
  12743. var series = this,
  12744. chart = series.chart,
  12745. clipRect,
  12746. animation = animObject(series.options.animation),
  12747. sharedClipKey;
  12748. // Initialize the animation. Set up the clipping rectangle.
  12749. if (init) {
  12750. series.setClip(animation);
  12751. // Run the animation
  12752. } else {
  12753. sharedClipKey = this.sharedClipKey;
  12754. clipRect = chart[sharedClipKey];
  12755. if (clipRect) {
  12756. clipRect.animate({
  12757. width: chart.plotSizeX
  12758. }, animation);
  12759. }
  12760. if (chart[sharedClipKey + 'm']) {
  12761. chart[sharedClipKey + 'm'].animate({
  12762. width: chart.plotSizeX + 99
  12763. }, animation);
  12764. }
  12765. // Delete this function to allow it only once
  12766. series.animate = null;
  12767. }
  12768. },
  12769. /**
  12770. * This runs after animation to land on the final plot clipping
  12771. */
  12772. afterAnimate: function () {
  12773. this.setClip();
  12774. fireEvent(this, 'afterAnimate');
  12775. },
  12776. /**
  12777. * Draw the markers
  12778. */
  12779. drawPoints: function () {
  12780. var series = this,
  12781. pointAttr,
  12782. points = series.points,
  12783. chart = series.chart,
  12784. plotX,
  12785. plotY,
  12786. i,
  12787. point,
  12788. radius,
  12789. symbol,
  12790. isImage,
  12791. graphic,
  12792. options = series.options,
  12793. seriesMarkerOptions = options.marker,
  12794. seriesPointAttr = series.pointAttr[''],
  12795. pointMarkerOptions,
  12796. hasPointMarker,
  12797. enabled,
  12798. isInside,
  12799. markerGroup = series.markerGroup,
  12800. xAxis = series.xAxis,
  12801. globallyEnabled = pick(
  12802. seriesMarkerOptions.enabled,
  12803. xAxis.isRadial,
  12804. series.closestPointRangePx > 2 * seriesMarkerOptions.radius
  12805. );
  12806. if (seriesMarkerOptions.enabled !== false || series._hasPointMarkers) {
  12807. i = points.length;
  12808. while (i--) {
  12809. point = points[i];
  12810. plotX = mathFloor(point.plotX); // #1843
  12811. plotY = point.plotY;
  12812. graphic = point.graphic;
  12813. pointMarkerOptions = point.marker || {};
  12814. hasPointMarker = !!point.marker;
  12815. enabled = (globallyEnabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled;
  12816. isInside = point.isInside;
  12817. // only draw the point if y is defined
  12818. if (enabled && isNumber(plotY) && point.y !== null) {
  12819. // shortcuts
  12820. pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || seriesPointAttr;
  12821. radius = pointAttr.r;
  12822. symbol = pick(pointMarkerOptions.symbol, series.symbol);
  12823. isImage = symbol.indexOf('url') === 0;
  12824. if (graphic) { // update
  12825. graphic[isInside ? 'show' : 'hide'](true) // Since the marker group isn't clipped, each individual marker must be toggled
  12826. .attr(pointAttr) // #4759
  12827. .animate(extend({
  12828. x: plotX - radius,
  12829. y: plotY - radius
  12830. }, graphic.symbolName ? { // don't apply to image symbols #507
  12831. width: 2 * radius,
  12832. height: 2 * radius
  12833. } : {}));
  12834. } else if (isInside && (radius > 0 || isImage)) {
  12835. point.graphic = graphic = chart.renderer.symbol(
  12836. symbol,
  12837. plotX - radius,
  12838. plotY - radius,
  12839. 2 * radius,
  12840. 2 * radius,
  12841. hasPointMarker ? pointMarkerOptions : seriesMarkerOptions
  12842. )
  12843. .attr(pointAttr)
  12844. .add(markerGroup);
  12845. }
  12846. } else if (graphic) {
  12847. point.graphic = graphic.destroy(); // #1269
  12848. }
  12849. }
  12850. }
  12851. },
  12852. /**
  12853. * Convert state properties from API naming conventions to SVG attributes
  12854. *
  12855. * @param {Object} options API options object
  12856. * @param {Object} base1 SVG attribute object to inherit from
  12857. * @param {Object} base2 Second level SVG attribute object to inherit from
  12858. */
  12859. convertAttribs: function (options, base1, base2, base3) {
  12860. var conversion = this.pointAttrToOptions,
  12861. attr,
  12862. option,
  12863. obj = {};
  12864. options = options || {};
  12865. base1 = base1 || {};
  12866. base2 = base2 || {};
  12867. base3 = base3 || {};
  12868. for (attr in conversion) {
  12869. option = conversion[attr];
  12870. obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]);
  12871. }
  12872. return obj;
  12873. },
  12874. /**
  12875. * Get the state attributes. Each series type has its own set of attributes
  12876. * that are allowed to change on a point's state change. Series wide attributes are stored for
  12877. * all series, and additionally point specific attributes are stored for all
  12878. * points with individual marker options. If such options are not defined for the point,
  12879. * a reference to the series wide attributes is stored in point.pointAttr.
  12880. */
  12881. getAttribs: function () {
  12882. var series = this,
  12883. seriesOptions = series.options,
  12884. normalOptions = defaultPlotOptions[series.type].marker ? seriesOptions.marker : seriesOptions,
  12885. stateOptions = normalOptions.states,
  12886. stateOptionsHover = stateOptions[HOVER_STATE],
  12887. pointStateOptionsHover,
  12888. seriesColor = series.color,
  12889. seriesNegativeColor = series.options.negativeColor,
  12890. normalDefaults = {
  12891. stroke: seriesColor,
  12892. fill: seriesColor
  12893. },
  12894. points = series.points || [], // #927
  12895. i,
  12896. j,
  12897. threshold,
  12898. point,
  12899. seriesPointAttr = [],
  12900. pointAttr,
  12901. pointAttrToOptions = series.pointAttrToOptions,
  12902. hasPointSpecificOptions = series.hasPointSpecificOptions,
  12903. defaultLineColor = normalOptions.lineColor,
  12904. defaultFillColor = normalOptions.fillColor,
  12905. turboThreshold = seriesOptions.turboThreshold,
  12906. zones = series.zones,
  12907. zoneAxis = series.zoneAxis || 'y',
  12908. zoneColor,
  12909. attr,
  12910. key;
  12911. // series type specific modifications
  12912. if (seriesOptions.marker) { // line, spline, area, areaspline, scatter
  12913. // if no hover radius is given, default to normal radius + 2
  12914. stateOptionsHover.radius = +stateOptionsHover.radius || +normalOptions.radius + +stateOptionsHover.radiusPlus;
  12915. stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + stateOptionsHover.lineWidthPlus;
  12916. } else { // column, bar, pie
  12917. // if no hover color is given, brighten the normal color
  12918. stateOptionsHover.color = stateOptionsHover.color ||
  12919. Color(stateOptionsHover.color || seriesColor)
  12920. .brighten(stateOptionsHover.brightness).get();
  12921. // if no hover negativeColor is given, brighten the normal negativeColor
  12922. stateOptionsHover.negativeColor = stateOptionsHover.negativeColor ||
  12923. Color(stateOptionsHover.negativeColor || seriesNegativeColor)
  12924. .brighten(stateOptionsHover.brightness).get();
  12925. }
  12926. // general point attributes for the series normal state
  12927. seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults);
  12928. // HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius
  12929. each([HOVER_STATE, SELECT_STATE], function (state) {
  12930. seriesPointAttr[state] =
  12931. series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]);
  12932. });
  12933. // set it
  12934. series.pointAttr = seriesPointAttr;
  12935. // Generate the point-specific attribute collections if specific point
  12936. // options are given. If not, create a referance to the series wide point
  12937. // attributes
  12938. i = points.length;
  12939. if (!turboThreshold || i < turboThreshold || hasPointSpecificOptions) {
  12940. while (i--) {
  12941. point = points[i];
  12942. normalOptions = (point.options && point.options.marker) || point.options;
  12943. if (normalOptions && normalOptions.enabled === false) {
  12944. normalOptions.radius = 0;
  12945. }
  12946. zoneColor = null;
  12947. if (zones.length) {
  12948. j = 0;
  12949. threshold = zones[j];
  12950. while (point[zoneAxis] >= threshold.value) {
  12951. threshold = zones[++j];
  12952. }
  12953. point.color = point.fillColor = zoneColor = pick(threshold.color, series.color); // #3636, #4267, #4430 - inherit color from series, when color is undefined
  12954. }
  12955. hasPointSpecificOptions = seriesOptions.colorByPoint || point.color; // #868
  12956. // check if the point has specific visual options
  12957. if (point.options) {
  12958. for (key in pointAttrToOptions) {
  12959. if (defined(normalOptions[pointAttrToOptions[key]])) {
  12960. hasPointSpecificOptions = true;
  12961. }
  12962. }
  12963. }
  12964. // a specific marker config object is defined for the individual point:
  12965. // create it's own attribute collection
  12966. if (hasPointSpecificOptions) {
  12967. normalOptions = normalOptions || {};
  12968. pointAttr = [];
  12969. stateOptions = normalOptions.states || {}; // reassign for individual point
  12970. pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {};
  12971. // Handle colors for column and pies
  12972. if (!seriesOptions.marker || (point.negative && !pointStateOptionsHover.fillColor && !stateOptionsHover.fillColor)) { // column, bar, point or negative threshold for series with markers (#3636)
  12973. // If no hover color is given, brighten the normal color. #1619, #2579
  12974. pointStateOptionsHover[series.pointAttrToOptions.fill] = pointStateOptionsHover.color || (!point.options.color && stateOptionsHover[(point.negative && seriesNegativeColor ? 'negativeColor' : 'color')]) ||
  12975. Color(point.color)
  12976. .brighten(pointStateOptionsHover.brightness || stateOptionsHover.brightness)
  12977. .get();
  12978. }
  12979. // normal point state inherits series wide normal state
  12980. attr = { color: point.color }; // #868
  12981. if (!defaultFillColor) { // Individual point color or negative color markers (#2219)
  12982. attr.fillColor = point.color;
  12983. }
  12984. if (!defaultLineColor) {
  12985. attr.lineColor = point.color; // Bubbles take point color, line markers use white
  12986. }
  12987. // Color is explicitly set to null or undefined (#1288, #4068)
  12988. if (normalOptions.hasOwnProperty('color') && !normalOptions.color) {
  12989. delete normalOptions.color;
  12990. }
  12991. // When zone is set, but series.states.hover.color is not set, apply zone color on hover, #4670:
  12992. if (zoneColor && !stateOptionsHover.fillColor) {
  12993. pointStateOptionsHover.fillColor = zoneColor;
  12994. }
  12995. pointAttr[NORMAL_STATE] = series.convertAttribs(extend(attr, normalOptions), seriesPointAttr[NORMAL_STATE]);
  12996. // inherit from point normal and series hover
  12997. pointAttr[HOVER_STATE] = series.convertAttribs(
  12998. stateOptions[HOVER_STATE],
  12999. seriesPointAttr[HOVER_STATE],
  13000. pointAttr[NORMAL_STATE]
  13001. );
  13002. // inherit from point normal and series hover
  13003. pointAttr[SELECT_STATE] = series.convertAttribs(
  13004. stateOptions[SELECT_STATE],
  13005. seriesPointAttr[SELECT_STATE],
  13006. pointAttr[NORMAL_STATE]
  13007. );
  13008. // no marker config object is created: copy a reference to the series-wide
  13009. // attribute collection
  13010. } else {
  13011. pointAttr = seriesPointAttr;
  13012. }
  13013. point.pointAttr = pointAttr;
  13014. }
  13015. }
  13016. },
  13017. /**
  13018. * Clear DOM objects and free up memory
  13019. */
  13020. destroy: function () {
  13021. var series = this,
  13022. chart = series.chart,
  13023. issue134 = /AppleWebKit\/533/.test(userAgent),
  13024. destroy,
  13025. i,
  13026. data = series.data || [],
  13027. point,
  13028. prop,
  13029. axis;
  13030. // add event hook
  13031. fireEvent(series, 'destroy');
  13032. // remove all events
  13033. removeEvent(series);
  13034. // erase from axes
  13035. each(series.axisTypes || [], function (AXIS) {
  13036. axis = series[AXIS];
  13037. if (axis) {
  13038. erase(axis.series, series);
  13039. axis.isDirty = axis.forceRedraw = true;
  13040. }
  13041. });
  13042. // remove legend items
  13043. if (series.legendItem) {
  13044. series.chart.legend.destroyItem(series);
  13045. }
  13046. // destroy all points with their elements
  13047. i = data.length;
  13048. while (i--) {
  13049. point = data[i];
  13050. if (point && point.destroy) {
  13051. point.destroy();
  13052. }
  13053. }
  13054. series.points = null;
  13055. // Clear the animation timeout if we are destroying the series during initial animation
  13056. clearTimeout(series.animationTimeout);
  13057. // Destroy all SVGElements associated to the series
  13058. for (prop in series) {
  13059. if (series[prop] instanceof SVGElement && !series[prop].survive) { // Survive provides a hook for not destroying
  13060. // issue 134 workaround
  13061. destroy = issue134 && prop === 'group' ?
  13062. 'hide' :
  13063. 'destroy';
  13064. series[prop][destroy]();
  13065. }
  13066. }
  13067. // remove from hoverSeries
  13068. if (chart.hoverSeries === series) {
  13069. chart.hoverSeries = null;
  13070. }
  13071. erase(chart.series, series);
  13072. // clear all members
  13073. for (prop in series) {
  13074. delete series[prop];
  13075. }
  13076. },
  13077. /**
  13078. * Get the graph path
  13079. */
  13080. getGraphPath: function (points, nullsAsZeroes, connectCliffs) {
  13081. var series = this,
  13082. options = series.options,
  13083. step = options.step,
  13084. reversed,
  13085. graphPath = [],
  13086. xMap = [],
  13087. gap;
  13088. points = points || series.points;
  13089. // Bottom of a stack is reversed
  13090. reversed = points.reversed;
  13091. if (reversed) {
  13092. points.reverse();
  13093. }
  13094. // Reverse the steps (#5004)
  13095. step = { right: 1, center: 2 }[step] || (step && 3);
  13096. if (step && reversed) {
  13097. step = 4 - step;
  13098. }
  13099. // Remove invalid points, especially in spline (#5015)
  13100. if (options.connectNulls && !nullsAsZeroes && !connectCliffs) {
  13101. points = this.getValidPoints(points);
  13102. }
  13103. // Build the line
  13104. each(points, function (point, i) {
  13105. var plotX = point.plotX,
  13106. plotY = point.plotY,
  13107. lastPoint = points[i - 1],
  13108. pathToPoint; // the path to this point from the previous
  13109. if ((point.leftCliff || (lastPoint && lastPoint.rightCliff)) && !connectCliffs) {
  13110. gap = true; // ... and continue
  13111. }
  13112. // Line series, nullsAsZeroes is not handled
  13113. if (point.isNull && !defined(nullsAsZeroes) && i > 0) {
  13114. gap = !options.connectNulls;
  13115. // Area series, nullsAsZeroes is set
  13116. } else if (point.isNull && !nullsAsZeroes) {
  13117. gap = true;
  13118. } else {
  13119. if (i === 0 || gap) {
  13120. pathToPoint = [M, point.plotX, point.plotY];
  13121. } else if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object
  13122. pathToPoint = series.getPointSpline(points, point, i);
  13123. } else if (step) {
  13124. if (step === 1) { // right
  13125. pathToPoint = [
  13126. L,
  13127. lastPoint.plotX,
  13128. plotY
  13129. ];
  13130. } else if (step === 2) { // center
  13131. pathToPoint = [
  13132. L,
  13133. (lastPoint.plotX + plotX) / 2,
  13134. lastPoint.plotY,
  13135. L,
  13136. (lastPoint.plotX + plotX) / 2,
  13137. plotY
  13138. ];
  13139. } else {
  13140. pathToPoint = [
  13141. L,
  13142. plotX,
  13143. lastPoint.plotY
  13144. ];
  13145. }
  13146. pathToPoint.push(L, plotX, plotY);
  13147. } else {
  13148. // normal line to next point
  13149. pathToPoint = [
  13150. L,
  13151. plotX,
  13152. plotY
  13153. ];
  13154. }
  13155. // Prepare for animation. When step is enabled, there are two path nodes for each x value.
  13156. xMap.push(point.x);
  13157. if (step) {
  13158. xMap.push(point.x);
  13159. }
  13160. graphPath.push.apply(graphPath, pathToPoint);
  13161. gap = false;
  13162. }
  13163. });
  13164. graphPath.xMap = xMap;
  13165. series.graphPath = graphPath;
  13166. return graphPath;
  13167. },
  13168. /**
  13169. * Draw the actual graph
  13170. */
  13171. drawGraph: function () {
  13172. var series = this,
  13173. options = this.options,
  13174. props = [['graph', options.lineColor || this.color, options.dashStyle]],
  13175. lineWidth = options.lineWidth,
  13176. roundCap = options.linecap !== 'square',
  13177. graphPath = (this.gappedPath || this.getGraphPath).call(this),
  13178. zones = this.zones;
  13179. each(zones, function (threshold, i) {
  13180. props.push(['zoneGraph' + i, threshold.color || series.color, threshold.dashStyle || options.dashStyle]);
  13181. });
  13182. // Draw the graph
  13183. each(props, function (prop, i) {
  13184. var graphKey = prop[0],
  13185. graph = series[graphKey],
  13186. attribs;
  13187. if (graph) {
  13188. graph.endX = graphPath.xMap;
  13189. graph.animate({ d: graphPath });
  13190. } else if (lineWidth && graphPath.length) { // #1487
  13191. attribs = {
  13192. stroke: prop[1],
  13193. 'stroke-width': lineWidth,
  13194. fill: 'none',
  13195. zIndex: 1 // #1069
  13196. };
  13197. if (prop[2]) {
  13198. attribs.dashstyle = prop[2];
  13199. } else if (roundCap) {
  13200. attribs['stroke-linecap'] = attribs['stroke-linejoin'] = 'round';
  13201. }
  13202. graph = series[graphKey] = series.chart.renderer.path(graphPath)
  13203. .attr(attribs)
  13204. .add(series.group)
  13205. .shadow((i < 2) && options.shadow); // add shadow to normal series (0) or to first zone (1) #3932
  13206. }
  13207. // Helpers for animation
  13208. if (graph) {
  13209. graph.startX = graphPath.xMap;
  13210. //graph.shiftUnit = options.step ? 2 : 1;
  13211. graph.isArea = graphPath.isArea; // For arearange animation
  13212. }
  13213. });
  13214. },
  13215. /**
  13216. * Clip the graphs into the positive and negative coloured graphs
  13217. */
  13218. applyZones: function () {
  13219. var series = this,
  13220. chart = this.chart,
  13221. renderer = chart.renderer,
  13222. zones = this.zones,
  13223. translatedFrom,
  13224. translatedTo,
  13225. clips = this.clips || [],
  13226. clipAttr,
  13227. graph = this.graph,
  13228. area = this.area,
  13229. chartSizeMax = mathMax(chart.chartWidth, chart.chartHeight),
  13230. axis = this[(this.zoneAxis || 'y') + 'Axis'],
  13231. extremes,
  13232. reversed,
  13233. inverted = chart.inverted,
  13234. horiz,
  13235. pxRange,
  13236. pxPosMin,
  13237. pxPosMax,
  13238. ignoreZones = false;
  13239. if (zones.length && (graph || area) && axis && axis.min !== UNDEFINED) {
  13240. reversed = axis.reversed;
  13241. horiz = axis.horiz;
  13242. // The use of the Color Threshold assumes there are no gaps
  13243. // so it is safe to hide the original graph and area
  13244. if (graph) {
  13245. graph.hide();
  13246. }
  13247. if (area) {
  13248. area.hide();
  13249. }
  13250. // Create the clips
  13251. extremes = axis.getExtremes();
  13252. each(zones, function (threshold, i) {
  13253. translatedFrom = reversed ?
  13254. (horiz ? chart.plotWidth : 0) :
  13255. (horiz ? 0 : axis.toPixels(extremes.min));
  13256. translatedFrom = mathMin(mathMax(pick(translatedTo, translatedFrom), 0), chartSizeMax);
  13257. translatedTo = mathMin(mathMax(mathRound(axis.toPixels(pick(threshold.value, extremes.max), true)), 0), chartSizeMax);
  13258. if (ignoreZones) {
  13259. translatedFrom = translatedTo = axis.toPixels(extremes.max);
  13260. }
  13261. pxRange = Math.abs(translatedFrom - translatedTo);
  13262. pxPosMin = mathMin(translatedFrom, translatedTo);
  13263. pxPosMax = mathMax(translatedFrom, translatedTo);
  13264. if (axis.isXAxis) {
  13265. clipAttr = {
  13266. x: inverted ? pxPosMax : pxPosMin,
  13267. y: 0,
  13268. width: pxRange,
  13269. height: chartSizeMax
  13270. };
  13271. if (!horiz) {
  13272. clipAttr.x = chart.plotHeight - clipAttr.x;
  13273. }
  13274. } else {
  13275. clipAttr = {
  13276. x: 0,
  13277. y: inverted ? pxPosMax : pxPosMin,
  13278. width: chartSizeMax,
  13279. height: pxRange
  13280. };
  13281. if (horiz) {
  13282. clipAttr.y = chart.plotWidth - clipAttr.y;
  13283. }
  13284. }
  13285. /// VML SUPPPORT
  13286. if (inverted && renderer.isVML) {
  13287. if (axis.isXAxis) {
  13288. clipAttr = {
  13289. x: 0,
  13290. y: reversed ? pxPosMin : pxPosMax,
  13291. height: clipAttr.width,
  13292. width: chart.chartWidth
  13293. };
  13294. } else {
  13295. clipAttr = {
  13296. x: clipAttr.y - chart.plotLeft - chart.spacingBox.x,
  13297. y: 0,
  13298. width: clipAttr.height,
  13299. height: chart.chartHeight
  13300. };
  13301. }
  13302. }
  13303. /// END OF VML SUPPORT
  13304. if (clips[i]) {
  13305. clips[i].animate(clipAttr);
  13306. } else {
  13307. clips[i] = renderer.clipRect(clipAttr);
  13308. if (graph) {
  13309. series['zoneGraph' + i].clip(clips[i]);
  13310. }
  13311. if (area) {
  13312. series['zoneArea' + i].clip(clips[i]);
  13313. }
  13314. }
  13315. // if this zone extends out of the axis, ignore the others
  13316. ignoreZones = threshold.value > extremes.max;
  13317. });
  13318. this.clips = clips;
  13319. }
  13320. },
  13321. /**
  13322. * Initialize and perform group inversion on series.group and series.markerGroup
  13323. */
  13324. invertGroups: function () {
  13325. var series = this,
  13326. chart = series.chart;
  13327. // Pie, go away (#1736)
  13328. if (!series.xAxis) {
  13329. return;
  13330. }
  13331. // A fixed size is needed for inversion to work
  13332. function setInvert() {
  13333. var size = {
  13334. width: series.yAxis.len,
  13335. height: series.xAxis.len
  13336. };
  13337. each(['group', 'markerGroup'], function (groupName) {
  13338. if (series[groupName]) {
  13339. series[groupName].attr(size).invert();
  13340. }
  13341. });
  13342. }
  13343. addEvent(chart, 'resize', setInvert); // do it on resize
  13344. addEvent(series, 'destroy', function () {
  13345. removeEvent(chart, 'resize', setInvert);
  13346. });
  13347. // Do it now
  13348. setInvert(); // do it now
  13349. // On subsequent render and redraw, just do setInvert without setting up events again
  13350. series.invertGroups = setInvert;
  13351. },
  13352. /**
  13353. * General abstraction for creating plot groups like series.group, series.dataLabelsGroup and
  13354. * series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size.
  13355. */
  13356. plotGroup: function (prop, name, visibility, zIndex, parent) {
  13357. var group = this[prop],
  13358. isNew = !group;
  13359. // Generate it on first call
  13360. if (isNew) {
  13361. this[prop] = group = this.chart.renderer.g(name)
  13362. .attr({
  13363. zIndex: zIndex || 0.1 // IE8 and pointer logic use this
  13364. })
  13365. .add(parent);
  13366. group.addClass('highcharts-series-' + this.index);
  13367. }
  13368. // Place it on first and subsequent (redraw) calls
  13369. group.attr({ visibility: visibility })[isNew ? 'attr' : 'animate'](this.getPlotBox());
  13370. return group;
  13371. },
  13372. /**
  13373. * Get the translation and scale for the plot area of this series
  13374. */
  13375. getPlotBox: function () {
  13376. var chart = this.chart,
  13377. xAxis = this.xAxis,
  13378. yAxis = this.yAxis;
  13379. // Swap axes for inverted (#2339)
  13380. if (chart.inverted) {
  13381. xAxis = yAxis;
  13382. yAxis = this.xAxis;
  13383. }
  13384. return {
  13385. translateX: xAxis ? xAxis.left : chart.plotLeft,
  13386. translateY: yAxis ? yAxis.top : chart.plotTop,
  13387. scaleX: 1, // #1623
  13388. scaleY: 1
  13389. };
  13390. },
  13391. /**
  13392. * Render the graph and markers
  13393. */
  13394. render: function () {
  13395. var series = this,
  13396. chart = series.chart,
  13397. group,
  13398. options = series.options,
  13399. // Animation doesn't work in IE8 quirks when the group div is hidden,
  13400. // and looks bad in other oldIE
  13401. animDuration = !!series.animate && chart.renderer.isSVG && animObject(options.animation).duration,
  13402. visibility = series.visible ? 'inherit' : 'hidden', // #2597
  13403. zIndex = options.zIndex,
  13404. hasRendered = series.hasRendered,
  13405. chartSeriesGroup = chart.seriesGroup;
  13406. // the group
  13407. group = series.plotGroup(
  13408. 'group',
  13409. 'series',
  13410. visibility,
  13411. zIndex,
  13412. chartSeriesGroup
  13413. );
  13414. series.markerGroup = series.plotGroup(
  13415. 'markerGroup',
  13416. 'markers',
  13417. visibility,
  13418. zIndex,
  13419. chartSeriesGroup
  13420. );
  13421. // initiate the animation
  13422. if (animDuration) {
  13423. series.animate(true);
  13424. }
  13425. // cache attributes for shapes
  13426. series.getAttribs();
  13427. // SVGRenderer needs to know this before drawing elements (#1089, #1795)
  13428. group.inverted = series.isCartesian ? chart.inverted : false;
  13429. // draw the graph if any
  13430. if (series.drawGraph) {
  13431. series.drawGraph();
  13432. series.applyZones();
  13433. }
  13434. each(series.points, function (point) {
  13435. if (point.redraw) {
  13436. point.redraw();
  13437. }
  13438. });
  13439. // draw the data labels (inn pies they go before the points)
  13440. if (series.drawDataLabels) {
  13441. series.drawDataLabels();
  13442. }
  13443. // draw the points
  13444. if (series.visible) {
  13445. series.drawPoints();
  13446. }
  13447. // draw the mouse tracking area
  13448. if (series.drawTracker && series.options.enableMouseTracking !== false) {
  13449. series.drawTracker();
  13450. }
  13451. // Handle inverted series and tracker groups
  13452. if (chart.inverted) {
  13453. series.invertGroups();
  13454. }
  13455. // Initial clipping, must be defined after inverting groups for VML. Applies to columns etc. (#3839).
  13456. if (options.clip !== false && !series.sharedClipKey && !hasRendered) {
  13457. group.clip(chart.clipRect);
  13458. }
  13459. // Run the animation
  13460. if (animDuration) {
  13461. series.animate();
  13462. }
  13463. // Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option
  13464. // which should be available to the user).
  13465. if (!hasRendered) {
  13466. series.animationTimeout = syncTimeout(function () {
  13467. series.afterAnimate();
  13468. }, animDuration);
  13469. }
  13470. series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
  13471. // (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
  13472. series.hasRendered = true;
  13473. },
  13474. /**
  13475. * Redraw the series after an update in the axes.
  13476. */
  13477. redraw: function () {
  13478. var series = this,
  13479. chart = series.chart,
  13480. wasDirty = series.isDirty || series.isDirtyData, // cache it here as it is set to false in render, but used after
  13481. group = series.group,
  13482. xAxis = series.xAxis,
  13483. yAxis = series.yAxis;
  13484. // reposition on resize
  13485. if (group) {
  13486. if (chart.inverted) {
  13487. group.attr({
  13488. width: chart.plotWidth,
  13489. height: chart.plotHeight
  13490. });
  13491. }
  13492. group.animate({
  13493. translateX: pick(xAxis && xAxis.left, chart.plotLeft),
  13494. translateY: pick(yAxis && yAxis.top, chart.plotTop)
  13495. });
  13496. }
  13497. series.translate();
  13498. series.render();
  13499. if (wasDirty) { // #3868, #3945
  13500. delete this.kdTree;
  13501. }
  13502. },
  13503. /**
  13504. * KD Tree && PointSearching Implementation
  13505. */
  13506. kdDimensions: 1,
  13507. kdAxisArray: ['clientX', 'plotY'],
  13508. searchPoint: function (e, compareX) {
  13509. var series = this,
  13510. xAxis = series.xAxis,
  13511. yAxis = series.yAxis,
  13512. inverted = series.chart.inverted;
  13513. return this.searchKDTree({
  13514. clientX: inverted ? xAxis.len - e.chartY + xAxis.pos : e.chartX - xAxis.pos,
  13515. plotY: inverted ? yAxis.len - e.chartX + yAxis.pos : e.chartY - yAxis.pos
  13516. }, compareX);
  13517. },
  13518. buildKDTree: function () {
  13519. var series = this,
  13520. dimensions = series.kdDimensions;
  13521. // Internal function
  13522. function _kdtree(points, depth, dimensions) {
  13523. var axis,
  13524. median,
  13525. length = points && points.length;
  13526. if (length) {
  13527. // alternate between the axis
  13528. axis = series.kdAxisArray[depth % dimensions];
  13529. // sort point array
  13530. points.sort(function (a, b) {
  13531. return a[axis] - b[axis];
  13532. });
  13533. median = Math.floor(length / 2);
  13534. // build and return nod
  13535. return {
  13536. point: points[median],
  13537. left: _kdtree(points.slice(0, median), depth + 1, dimensions),
  13538. right: _kdtree(points.slice(median + 1), depth + 1, dimensions)
  13539. };
  13540. }
  13541. }
  13542. // Start the recursive build process with a clone of the points array and null points filtered out (#3873)
  13543. function startRecursive() {
  13544. series.kdTree = _kdtree(
  13545. series.getValidPoints(
  13546. null,
  13547. !series.directTouch // For line-type series restrict to plot area, but column-type series not (#3916, #4511)
  13548. ),
  13549. dimensions,
  13550. dimensions
  13551. );
  13552. }
  13553. delete series.kdTree;
  13554. // For testing tooltips, don't build async
  13555. syncTimeout(startRecursive, series.options.kdNow ? 0 : 1);
  13556. },
  13557. searchKDTree: function (point, compareX) {
  13558. var series = this,
  13559. kdX = this.kdAxisArray[0],
  13560. kdY = this.kdAxisArray[1],
  13561. kdComparer = compareX ? 'distX' : 'dist';
  13562. // Set the one and two dimensional distance on the point object
  13563. function setDistance(p1, p2) {
  13564. var x = (defined(p1[kdX]) && defined(p2[kdX])) ? Math.pow(p1[kdX] - p2[kdX], 2) : null,
  13565. y = (defined(p1[kdY]) && defined(p2[kdY])) ? Math.pow(p1[kdY] - p2[kdY], 2) : null,
  13566. r = (x || 0) + (y || 0);
  13567. p2.dist = defined(r) ? Math.sqrt(r) : Number.MAX_VALUE;
  13568. p2.distX = defined(x) ? Math.sqrt(x) : Number.MAX_VALUE;
  13569. }
  13570. function _search(search, tree, depth, dimensions) {
  13571. var point = tree.point,
  13572. axis = series.kdAxisArray[depth % dimensions],
  13573. tdist,
  13574. sideA,
  13575. sideB,
  13576. ret = point,
  13577. nPoint1,
  13578. nPoint2;
  13579. setDistance(search, point);
  13580. // Pick side based on distance to splitting point
  13581. tdist = search[axis] - point[axis];
  13582. sideA = tdist < 0 ? 'left' : 'right';
  13583. sideB = tdist < 0 ? 'right' : 'left';
  13584. // End of tree
  13585. if (tree[sideA]) {
  13586. nPoint1 = _search(search, tree[sideA], depth + 1, dimensions);
  13587. ret = (nPoint1[kdComparer] < ret[kdComparer] ? nPoint1 : point);
  13588. }
  13589. if (tree[sideB]) {
  13590. // compare distance to current best to splitting point to decide wether to check side B or not
  13591. if (Math.sqrt(tdist * tdist) < ret[kdComparer]) {
  13592. nPoint2 = _search(search, tree[sideB], depth + 1, dimensions);
  13593. ret = (nPoint2[kdComparer] < ret[kdComparer] ? nPoint2 : ret);
  13594. }
  13595. }
  13596. return ret;
  13597. }
  13598. if (!this.kdTree) {
  13599. this.buildKDTree();
  13600. }
  13601. if (this.kdTree) {
  13602. return _search(point,
  13603. this.kdTree, this.kdDimensions, this.kdDimensions);
  13604. }
  13605. }
  13606. }; // end Series prototype
  13607. /**
  13608. * The class for stack items
  13609. */
  13610. function StackItem(axis, options, isNegative, x, stackOption) {
  13611. var inverted = axis.chart.inverted;
  13612. this.axis = axis;
  13613. // Tells if the stack is negative
  13614. this.isNegative = isNegative;
  13615. // Save the options to be able to style the label
  13616. this.options = options;
  13617. // Save the x value to be able to position the label later
  13618. this.x = x;
  13619. // Initialize total value
  13620. this.total = null;
  13621. // This will keep each points' extremes stored by series.index and point index
  13622. this.points = {};
  13623. // Save the stack option on the series configuration object, and whether to treat it as percent
  13624. this.stack = stackOption;
  13625. this.leftCliff = 0;
  13626. this.rightCliff = 0;
  13627. // The align options and text align varies on whether the stack is negative and
  13628. // if the chart is inverted or not.
  13629. // First test the user supplied value, then use the dynamic.
  13630. this.alignOptions = {
  13631. align: options.align || (inverted ? (isNegative ? 'left' : 'right') : 'center'),
  13632. verticalAlign: options.verticalAlign || (inverted ? 'middle' : (isNegative ? 'bottom' : 'top')),
  13633. y: pick(options.y, inverted ? 4 : (isNegative ? 14 : -6)),
  13634. x: pick(options.x, inverted ? (isNegative ? -6 : 6) : 0)
  13635. };
  13636. this.textAlign = options.textAlign || (inverted ? (isNegative ? 'right' : 'left') : 'center');
  13637. }
  13638. StackItem.prototype = {
  13639. destroy: function () {
  13640. destroyObjectProperties(this, this.axis);
  13641. },
  13642. /**
  13643. * Renders the stack total label and adds it to the stack label group.
  13644. */
  13645. render: function (group) {
  13646. var options = this.options,
  13647. formatOption = options.format,
  13648. str = formatOption ?
  13649. format(formatOption, this) :
  13650. options.formatter.call(this); // format the text in the label
  13651. // Change the text to reflect the new total and set visibility to hidden in case the serie is hidden
  13652. if (this.label) {
  13653. this.label.attr({ text: str, visibility: 'hidden' });
  13654. // Create new label
  13655. } else {
  13656. this.label =
  13657. this.axis.chart.renderer.text(str, null, null, options.useHTML) // dummy positions, actual position updated with setOffset method in columnseries
  13658. .css(options.style) // apply style
  13659. .attr({
  13660. align: this.textAlign, // fix the text-anchor
  13661. rotation: options.rotation, // rotation
  13662. visibility: HIDDEN // hidden until setOffset is called
  13663. })
  13664. .add(group); // add to the labels-group
  13665. }
  13666. },
  13667. /**
  13668. * Sets the offset that the stack has from the x value and repositions the label.
  13669. */
  13670. setOffset: function (xOffset, xWidth) {
  13671. var stackItem = this,
  13672. axis = stackItem.axis,
  13673. chart = axis.chart,
  13674. inverted = chart.inverted,
  13675. reversed = axis.reversed,
  13676. neg = (this.isNegative && !reversed) || (!this.isNegative && reversed), // #4056
  13677. y = axis.translate(axis.usePercentage ? 100 : this.total, 0, 0, 0, 1), // stack value translated mapped to chart coordinates
  13678. yZero = axis.translate(0), // stack origin
  13679. h = mathAbs(y - yZero), // stack height
  13680. x = chart.xAxis[0].translate(this.x) + xOffset, // stack x position
  13681. plotHeight = chart.plotHeight,
  13682. stackBox = { // this is the box for the complete stack
  13683. x: inverted ? (neg ? y : y - h) : x,
  13684. y: inverted ? plotHeight - x - xWidth : (neg ? (plotHeight - y - h) : plotHeight - y),
  13685. width: inverted ? h : xWidth,
  13686. height: inverted ? xWidth : h
  13687. },
  13688. label = this.label,
  13689. alignAttr;
  13690. if (label) {
  13691. label.align(this.alignOptions, null, stackBox); // align the label to the box
  13692. // Set visibility (#678)
  13693. alignAttr = label.alignAttr;
  13694. label[this.options.crop === false || chart.isInsidePlot(alignAttr.x, alignAttr.y) ? 'show' : 'hide'](true);
  13695. }
  13696. }
  13697. };
  13698. /**
  13699. * Generate stacks for each series and calculate stacks total values
  13700. */
  13701. Chart.prototype.getStacks = function () {
  13702. var chart = this;
  13703. // reset stacks for each yAxis
  13704. each(chart.yAxis, function (axis) {
  13705. if (axis.stacks && axis.hasVisibleSeries) {
  13706. axis.oldStacks = axis.stacks;
  13707. }
  13708. });
  13709. each(chart.series, function (series) {
  13710. if (series.options.stacking && (series.visible === true || chart.options.chart.ignoreHiddenSeries === false)) {
  13711. series.stackKey = series.type + pick(series.options.stack, '');
  13712. }
  13713. });
  13714. };
  13715. // Stacking methods defined on the Axis prototype
  13716. /**
  13717. * Build the stacks from top down
  13718. */
  13719. Axis.prototype.buildStacks = function () {
  13720. var axisSeries = this.series,
  13721. series,
  13722. reversedStacks = pick(this.options.reversedStacks, true),
  13723. len = axisSeries.length,
  13724. i;
  13725. if (!this.isXAxis) {
  13726. this.usePercentage = false;
  13727. i = len;
  13728. while (i--) {
  13729. axisSeries[reversedStacks ? i : len - i - 1].setStackedPoints();
  13730. }
  13731. i = len;
  13732. while (i--) {
  13733. series = axisSeries[reversedStacks ? i : len - i - 1];
  13734. if (series.setStackCliffs) {
  13735. series.setStackCliffs();
  13736. }
  13737. }
  13738. // Loop up again to compute percent stack
  13739. if (this.usePercentage) {
  13740. for (i = 0; i < len; i++) {
  13741. axisSeries[i].setPercentStacks();
  13742. }
  13743. }
  13744. }
  13745. };
  13746. Axis.prototype.renderStackTotals = function () {
  13747. var axis = this,
  13748. chart = axis.chart,
  13749. renderer = chart.renderer,
  13750. stacks = axis.stacks,
  13751. stackKey,
  13752. oneStack,
  13753. stackCategory,
  13754. stackTotalGroup = axis.stackTotalGroup;
  13755. // Create a separate group for the stack total labels
  13756. if (!stackTotalGroup) {
  13757. axis.stackTotalGroup = stackTotalGroup =
  13758. renderer.g('stack-labels')
  13759. .attr({
  13760. visibility: VISIBLE,
  13761. zIndex: 6
  13762. })
  13763. .add();
  13764. }
  13765. // plotLeft/Top will change when y axis gets wider so we need to translate the
  13766. // stackTotalGroup at every render call. See bug #506 and #516
  13767. stackTotalGroup.translate(chart.plotLeft, chart.plotTop);
  13768. // Render each stack total
  13769. for (stackKey in stacks) {
  13770. oneStack = stacks[stackKey];
  13771. for (stackCategory in oneStack) {
  13772. oneStack[stackCategory].render(stackTotalGroup);
  13773. }
  13774. }
  13775. };
  13776. /**
  13777. * Set all the stacks to initial states and destroy unused ones.
  13778. */
  13779. Axis.prototype.resetStacks = function () {
  13780. var stacks = this.stacks,
  13781. type,
  13782. i;
  13783. if (!this.isXAxis) {
  13784. for (type in stacks) {
  13785. for (i in stacks[type]) {
  13786. // Clean up memory after point deletion (#1044, #4320)
  13787. if (stacks[type][i].touched < this.stacksTouched) {
  13788. stacks[type][i].destroy();
  13789. delete stacks[type][i];
  13790. // Reset stacks
  13791. } else {
  13792. stacks[type][i].total = null;
  13793. stacks[type][i].cum = 0;
  13794. }
  13795. }
  13796. }
  13797. }
  13798. };
  13799. Axis.prototype.cleanStacks = function () {
  13800. var stacks, type, i;
  13801. if (!this.isXAxis) {
  13802. if (this.oldStacks) {
  13803. stacks = this.stacks = this.oldStacks;
  13804. }
  13805. // reset stacks
  13806. for (type in stacks) {
  13807. for (i in stacks[type]) {
  13808. stacks[type][i].cum = stacks[type][i].total;
  13809. }
  13810. }
  13811. }
  13812. };
  13813. // Stacking methods defnied for Series prototype
  13814. /**
  13815. * Adds series' points value to corresponding stack
  13816. */
  13817. Series.prototype.setStackedPoints = function () {
  13818. if (!this.options.stacking || (this.visible !== true && this.chart.options.chart.ignoreHiddenSeries !== false)) {
  13819. return;
  13820. }
  13821. var series = this,
  13822. xData = series.processedXData,
  13823. yData = series.processedYData,
  13824. stackedYData = [],
  13825. yDataLength = yData.length,
  13826. seriesOptions = series.options,
  13827. threshold = seriesOptions.threshold,
  13828. stackThreshold = seriesOptions.startFromThreshold ? threshold : 0,
  13829. stackOption = seriesOptions.stack,
  13830. stacking = seriesOptions.stacking,
  13831. stackKey = series.stackKey,
  13832. negKey = '-' + stackKey,
  13833. negStacks = series.negStacks,
  13834. yAxis = series.yAxis,
  13835. stacks = yAxis.stacks,
  13836. oldStacks = yAxis.oldStacks,
  13837. stackIndicator,
  13838. isNegative,
  13839. stack,
  13840. other,
  13841. key,
  13842. pointKey,
  13843. i,
  13844. x,
  13845. y;
  13846. yAxis.stacksTouched += 1;
  13847. // loop over the non-null y values and read them into a local array
  13848. for (i = 0; i < yDataLength; i++) {
  13849. x = xData[i];
  13850. y = yData[i];
  13851. stackIndicator = series.getStackIndicator(stackIndicator, x, series.index);
  13852. pointKey = stackIndicator.key;
  13853. // Read stacked values into a stack based on the x value,
  13854. // the sign of y and the stack key. Stacking is also handled for null values (#739)
  13855. isNegative = negStacks && y < (stackThreshold ? 0 : threshold);
  13856. key = isNegative ? negKey : stackKey;
  13857. // Create empty object for this stack if it doesn't exist yet
  13858. if (!stacks[key]) {
  13859. stacks[key] = {};
  13860. }
  13861. // Initialize StackItem for this x
  13862. if (!stacks[key][x]) {
  13863. if (oldStacks[key] && oldStacks[key][x]) {
  13864. stacks[key][x] = oldStacks[key][x];
  13865. stacks[key][x].total = null;
  13866. } else {
  13867. stacks[key][x] = new StackItem(yAxis, yAxis.options.stackLabels, isNegative, x, stackOption);
  13868. }
  13869. }
  13870. // If the StackItem doesn't exist, create it first
  13871. stack = stacks[key][x];
  13872. if (y !== null) {
  13873. stack.points[pointKey] = stack.points[series.index] = [pick(stack.cum, stackThreshold)];
  13874. // Record the base of the stack
  13875. if (!defined(stack.cum)) {
  13876. stack.base = pointKey;
  13877. }
  13878. stack.touched = yAxis.stacksTouched;
  13879. // In area charts, if there are multiple points on the same X value, let the
  13880. // area fill the full span of those points
  13881. if (stackIndicator.index > 0 && series.singleStacks === false) {
  13882. stack.points[pointKey][0] = stack.points[series.index + ',' + x + ',0'][0];
  13883. }
  13884. }
  13885. // Add value to the stack total
  13886. if (stacking === 'percent') {
  13887. // Percent stacked column, totals are the same for the positive and negative stacks
  13888. other = isNegative ? stackKey : negKey;
  13889. if (negStacks && stacks[other] && stacks[other][x]) {
  13890. other = stacks[other][x];
  13891. stack.total = other.total = mathMax(other.total, stack.total) + mathAbs(y) || 0;
  13892. // Percent stacked areas
  13893. } else {
  13894. stack.total = correctFloat(stack.total + (mathAbs(y) || 0));
  13895. }
  13896. } else {
  13897. stack.total = correctFloat(stack.total + (y || 0));
  13898. }
  13899. stack.cum = pick(stack.cum, stackThreshold) + (y || 0);
  13900. if (y !== null) {
  13901. stack.points[pointKey].push(stack.cum);
  13902. stackedYData[i] = stack.cum;
  13903. }
  13904. }
  13905. if (stacking === 'percent') {
  13906. yAxis.usePercentage = true;
  13907. }
  13908. this.stackedYData = stackedYData; // To be used in getExtremes
  13909. // Reset old stacks
  13910. yAxis.oldStacks = {};
  13911. };
  13912. /**
  13913. * Iterate over all stacks and compute the absolute values to percent
  13914. */
  13915. Series.prototype.setPercentStacks = function () {
  13916. var series = this,
  13917. stackKey = series.stackKey,
  13918. stacks = series.yAxis.stacks,
  13919. processedXData = series.processedXData,
  13920. stackIndicator;
  13921. each([stackKey, '-' + stackKey], function (key) {
  13922. var i = processedXData.length,
  13923. x,
  13924. stack,
  13925. pointExtremes,
  13926. totalFactor;
  13927. while (i--) {
  13928. x = processedXData[i];
  13929. stackIndicator = series.getStackIndicator(stackIndicator, x, series.index);
  13930. stack = stacks[key] && stacks[key][x];
  13931. pointExtremes = stack && stack.points[stackIndicator.key];
  13932. if (pointExtremes) {
  13933. totalFactor = stack.total ? 100 / stack.total : 0;
  13934. pointExtremes[0] = correctFloat(pointExtremes[0] * totalFactor); // Y bottom value
  13935. pointExtremes[1] = correctFloat(pointExtremes[1] * totalFactor); // Y value
  13936. series.stackedYData[i] = pointExtremes[1];
  13937. }
  13938. }
  13939. });
  13940. };
  13941. /**
  13942. * Get stack indicator, according to it's x-value, to determine points with the same x-value
  13943. */
  13944. Series.prototype.getStackIndicator = function (stackIndicator, x, index) {
  13945. if (!defined(stackIndicator) || stackIndicator.x !== x) {
  13946. stackIndicator = {
  13947. x: x,
  13948. index: 0
  13949. };
  13950. } else {
  13951. stackIndicator.index++;
  13952. }
  13953. stackIndicator.key = [index, x, stackIndicator.index].join(',');
  13954. return stackIndicator;
  13955. };
  13956. // Extend the Chart prototype for dynamic methods
  13957. extend(Chart.prototype, {
  13958. /**
  13959. * Add a series dynamically after time
  13960. *
  13961. * @param {Object} options The config options
  13962. * @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true.
  13963. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  13964. * configuration
  13965. *
  13966. * @return {Object} series The newly created series object
  13967. */
  13968. addSeries: function (options, redraw, animation) {
  13969. var series,
  13970. chart = this;
  13971. if (options) {
  13972. redraw = pick(redraw, true); // defaults to true
  13973. fireEvent(chart, 'addSeries', { options: options }, function () {
  13974. series = chart.initSeries(options);
  13975. chart.isDirtyLegend = true; // the series array is out of sync with the display
  13976. chart.linkSeries();
  13977. if (redraw) {
  13978. chart.redraw(animation);
  13979. }
  13980. });
  13981. }
  13982. return series;
  13983. },
  13984. /**
  13985. * Add an axis to the chart
  13986. * @param {Object} options The axis option
  13987. * @param {Boolean} isX Whether it is an X axis or a value axis
  13988. */
  13989. addAxis: function (options, isX, redraw, animation) {
  13990. var key = isX ? 'xAxis' : 'yAxis',
  13991. chartOptions = this.options,
  13992. userOptions = merge(options, {
  13993. index: this[key].length,
  13994. isX: isX
  13995. });
  13996. new Axis(this, userOptions); // eslint-disable-line no-new
  13997. // Push the new axis options to the chart options
  13998. chartOptions[key] = splat(chartOptions[key] || {});
  13999. chartOptions[key].push(userOptions);
  14000. if (pick(redraw, true)) {
  14001. this.redraw(animation);
  14002. }
  14003. },
  14004. /**
  14005. * Dim the chart and show a loading text or symbol
  14006. * @param {String} str An optional text to show in the loading label instead of the default one
  14007. */
  14008. showLoading: function (str) {
  14009. var chart = this,
  14010. options = chart.options,
  14011. loadingDiv = chart.loadingDiv,
  14012. loadingOptions = options.loading,
  14013. setLoadingSize = function () {
  14014. if (loadingDiv) {
  14015. css(loadingDiv, {
  14016. left: chart.plotLeft + PX,
  14017. top: chart.plotTop + PX,
  14018. width: chart.plotWidth + PX,
  14019. height: chart.plotHeight + PX
  14020. });
  14021. }
  14022. };
  14023. // create the layer at the first call
  14024. if (!loadingDiv) {
  14025. chart.loadingDiv = loadingDiv = createElement(DIV, {
  14026. className: PREFIX + 'loading'
  14027. }, extend(loadingOptions.style, {
  14028. zIndex: 10,
  14029. display: NONE
  14030. }), chart.container);
  14031. chart.loadingSpan = createElement(
  14032. 'span',
  14033. null,
  14034. loadingOptions.labelStyle,
  14035. loadingDiv
  14036. );
  14037. addEvent(chart, 'redraw', setLoadingSize); // #1080
  14038. }
  14039. // update text
  14040. chart.loadingSpan.innerHTML = str || options.lang.loading;
  14041. // show it
  14042. if (!chart.loadingShown) {
  14043. css(loadingDiv, {
  14044. opacity: 0,
  14045. display: ''
  14046. });
  14047. animate(loadingDiv, {
  14048. opacity: loadingOptions.style.opacity
  14049. }, {
  14050. duration: loadingOptions.showDuration || 0
  14051. });
  14052. chart.loadingShown = true;
  14053. }
  14054. setLoadingSize();
  14055. },
  14056. /**
  14057. * Hide the loading layer
  14058. */
  14059. hideLoading: function () {
  14060. var options = this.options,
  14061. loadingDiv = this.loadingDiv;
  14062. if (loadingDiv) {
  14063. animate(loadingDiv, {
  14064. opacity: 0
  14065. }, {
  14066. duration: options.loading.hideDuration || 100,
  14067. complete: function () {
  14068. css(loadingDiv, { display: NONE });
  14069. }
  14070. });
  14071. }
  14072. this.loadingShown = false;
  14073. }
  14074. });
  14075. // extend the Point prototype for dynamic methods
  14076. extend(Point.prototype, {
  14077. /**
  14078. * Update the point with new options (typically x/y data) and optionally redraw the series.
  14079. *
  14080. * @param {Object} options Point options as defined in the series.data array
  14081. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  14082. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  14083. * configuration
  14084. *
  14085. */
  14086. update: function (options, redraw, animation, runEvent) {
  14087. var point = this,
  14088. series = point.series,
  14089. graphic = point.graphic,
  14090. i,
  14091. chart = series.chart,
  14092. seriesOptions = series.options;
  14093. redraw = pick(redraw, true);
  14094. function update() {
  14095. point.applyOptions(options);
  14096. // Update visuals
  14097. if (point.y === null && graphic) { // #4146
  14098. point.graphic = graphic.destroy();
  14099. }
  14100. if (isObject(options, true)) {
  14101. // Defer the actual redraw until getAttribs has been called (#3260)
  14102. point.redraw = function () {
  14103. if (graphic && graphic.element) {
  14104. if (options && options.marker && options.marker.symbol) {
  14105. point.graphic = graphic.destroy();
  14106. }
  14107. }
  14108. if (options && options.dataLabels && point.dataLabel) { // #2468
  14109. point.dataLabel = point.dataLabel.destroy();
  14110. }
  14111. point.redraw = null;
  14112. };
  14113. }
  14114. // record changes in the parallel arrays
  14115. i = point.index;
  14116. series.updateParallelArrays(point, i);
  14117. // Record the options to options.data. If there is an object from before,
  14118. // use point options, otherwise use raw options. (#4701)
  14119. seriesOptions.data[i] = isObject(seriesOptions.data[i], true) ? point.options : options;
  14120. // redraw
  14121. series.isDirty = series.isDirtyData = true;
  14122. if (!series.fixedBox && series.hasCartesianSeries) { // #1906, #2320
  14123. chart.isDirtyBox = true;
  14124. }
  14125. if (seriesOptions.legendType === 'point') { // #1831, #1885
  14126. chart.isDirtyLegend = true;
  14127. }
  14128. if (redraw) {
  14129. chart.redraw(animation);
  14130. }
  14131. }
  14132. // Fire the event with a default handler of doing the update
  14133. if (runEvent === false) { // When called from setData
  14134. update();
  14135. } else {
  14136. point.firePointEvent('update', { options: options }, update);
  14137. }
  14138. },
  14139. /**
  14140. * Remove a point and optionally redraw the series and if necessary the axes
  14141. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  14142. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  14143. * configuration
  14144. */
  14145. remove: function (redraw, animation) {
  14146. this.series.removePoint(inArray(this, this.series.data), redraw, animation);
  14147. }
  14148. });
  14149. // Extend the series prototype for dynamic methods
  14150. extend(Series.prototype, {
  14151. /**
  14152. * Add a point dynamically after chart load time
  14153. * @param {Object} options Point options as given in series.data
  14154. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  14155. * @param {Boolean} shift If shift is true, a point is shifted off the start
  14156. * of the series as one is appended to the end.
  14157. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  14158. * configuration
  14159. */
  14160. addPoint: function (options, redraw, shift, animation) {
  14161. var series = this,
  14162. seriesOptions = series.options,
  14163. data = series.data,
  14164. chart = series.chart,
  14165. names = series.xAxis && series.xAxis.names,
  14166. dataOptions = seriesOptions.data,
  14167. point,
  14168. isInTheMiddle,
  14169. xData = series.xData,
  14170. i,
  14171. x;
  14172. // Optional redraw, defaults to true
  14173. redraw = pick(redraw, true);
  14174. // Get options and push the point to xData, yData and series.options. In series.generatePoints
  14175. // the Point instance will be created on demand and pushed to the series.data array.
  14176. point = { series: series };
  14177. series.pointClass.prototype.applyOptions.apply(point, [options]);
  14178. x = point.x;
  14179. // Get the insertion point
  14180. i = xData.length;
  14181. if (series.requireSorting && x < xData[i - 1]) {
  14182. isInTheMiddle = true;
  14183. while (i && xData[i - 1] > x) {
  14184. i--;
  14185. }
  14186. }
  14187. series.updateParallelArrays(point, 'splice', i, 0, 0); // insert undefined item
  14188. series.updateParallelArrays(point, i); // update it
  14189. if (names && point.name) {
  14190. names[x] = point.name;
  14191. }
  14192. dataOptions.splice(i, 0, options);
  14193. if (isInTheMiddle) {
  14194. series.data.splice(i, 0, null);
  14195. series.processData();
  14196. }
  14197. // Generate points to be added to the legend (#1329)
  14198. if (seriesOptions.legendType === 'point') {
  14199. series.generatePoints();
  14200. }
  14201. // Shift the first point off the parallel arrays
  14202. if (shift) {
  14203. if (data[0] && data[0].remove) {
  14204. data[0].remove(false);
  14205. } else {
  14206. data.shift();
  14207. series.updateParallelArrays(point, 'shift');
  14208. dataOptions.shift();
  14209. }
  14210. }
  14211. // redraw
  14212. series.isDirty = true;
  14213. series.isDirtyData = true;
  14214. if (redraw) {
  14215. series.getAttribs(); // #1937
  14216. chart.redraw(animation); // Animation is set anyway on redraw, #5665
  14217. }
  14218. },
  14219. /**
  14220. * Remove a point (rendered or not), by index
  14221. */
  14222. removePoint: function (i, redraw, animation) {
  14223. var series = this,
  14224. data = series.data,
  14225. point = data[i],
  14226. points = series.points,
  14227. chart = series.chart,
  14228. remove = function () {
  14229. if (points && points.length === data.length) { // #4935
  14230. points.splice(i, 1);
  14231. }
  14232. data.splice(i, 1);
  14233. series.options.data.splice(i, 1);
  14234. series.updateParallelArrays(point || { series: series }, 'splice', i, 1);
  14235. if (point) {
  14236. point.destroy();
  14237. }
  14238. // redraw
  14239. series.isDirty = true;
  14240. series.isDirtyData = true;
  14241. if (redraw) {
  14242. chart.redraw();
  14243. }
  14244. };
  14245. setAnimation(animation, chart);
  14246. redraw = pick(redraw, true);
  14247. // Fire the event with a default handler of removing the point
  14248. if (point) {
  14249. point.firePointEvent('remove', null, remove);
  14250. } else {
  14251. remove();
  14252. }
  14253. },
  14254. /**
  14255. * Remove a series and optionally redraw the chart
  14256. *
  14257. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  14258. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  14259. * configuration
  14260. */
  14261. remove: function (redraw, animation, withEvent) {
  14262. var series = this,
  14263. chart = series.chart;
  14264. function remove() {
  14265. // Destroy elements
  14266. series.destroy();
  14267. // Redraw
  14268. chart.isDirtyLegend = chart.isDirtyBox = true;
  14269. chart.linkSeries();
  14270. if (pick(redraw, true)) {
  14271. chart.redraw(animation);
  14272. }
  14273. }
  14274. // Fire the event with a default handler of removing the point
  14275. if (withEvent !== false) {
  14276. fireEvent(series, 'remove', null, remove);
  14277. } else {
  14278. remove();
  14279. }
  14280. },
  14281. /**
  14282. * Update the series with a new set of options
  14283. */
  14284. update: function (newOptions, redraw) {
  14285. var series = this,
  14286. chart = this.chart,
  14287. // must use user options when changing type because this.options is merged
  14288. // in with type specific plotOptions
  14289. oldOptions = this.userOptions,
  14290. oldType = this.type,
  14291. proto = seriesTypes[oldType].prototype,
  14292. preserve = ['group', 'markerGroup', 'dataLabelsGroup'],
  14293. n;
  14294. // If we're changing type or zIndex, create new groups (#3380, #3404)
  14295. if ((newOptions.type && newOptions.type !== oldType) || newOptions.zIndex !== undefined) {
  14296. preserve.length = 0;
  14297. }
  14298. // Make sure groups are not destroyed (#3094)
  14299. each(preserve, function (prop) {
  14300. preserve[prop] = series[prop];
  14301. delete series[prop];
  14302. });
  14303. // Do the merge, with some forced options
  14304. newOptions = merge(oldOptions, {
  14305. animation: false,
  14306. index: this.index,
  14307. pointStart: this.xData[0] // when updating after addPoint
  14308. }, { data: this.options.data }, newOptions);
  14309. // Destroy the series and delete all properties. Reinsert all methods
  14310. // and properties from the new type prototype (#2270, #3719)
  14311. this.remove(false, null, false);
  14312. for (n in proto) {
  14313. this[n] = UNDEFINED;
  14314. }
  14315. extend(this, seriesTypes[newOptions.type || oldType].prototype);
  14316. // Re-register groups (#3094)
  14317. each(preserve, function (prop) {
  14318. series[prop] = preserve[prop];
  14319. });
  14320. this.init(chart, newOptions);
  14321. chart.linkSeries(); // Links are lost in this.remove (#3028)
  14322. if (pick(redraw, true)) {
  14323. chart.redraw(false);
  14324. }
  14325. }
  14326. });
  14327. // Extend the Axis.prototype for dynamic methods
  14328. extend(Axis.prototype, {
  14329. /**
  14330. * Update the axis with a new options structure
  14331. */
  14332. update: function (newOptions, redraw) {
  14333. var chart = this.chart;
  14334. newOptions = chart.options[this.coll][this.options.index] = merge(this.userOptions, newOptions);
  14335. this.destroy(true);
  14336. this.init(chart, extend(newOptions, { events: UNDEFINED }));
  14337. chart.isDirtyBox = true;
  14338. if (pick(redraw, true)) {
  14339. chart.redraw();
  14340. }
  14341. },
  14342. /**
  14343. * Remove the axis from the chart
  14344. */
  14345. remove: function (redraw) {
  14346. var chart = this.chart,
  14347. key = this.coll, // xAxis or yAxis
  14348. axisSeries = this.series,
  14349. i = axisSeries.length;
  14350. // Remove associated series (#2687)
  14351. while (i--) {
  14352. if (axisSeries[i]) {
  14353. axisSeries[i].remove(false);
  14354. }
  14355. }
  14356. // Remove the axis
  14357. erase(chart.axes, this);
  14358. erase(chart[key], this);
  14359. chart.options[key].splice(this.options.index, 1);
  14360. each(chart[key], function (axis, i) { // Re-index, #1706
  14361. axis.options.index = i;
  14362. });
  14363. this.destroy();
  14364. chart.isDirtyBox = true;
  14365. if (pick(redraw, true)) {
  14366. chart.redraw();
  14367. }
  14368. },
  14369. /**
  14370. * Update the axis title by options
  14371. */
  14372. setTitle: function (newTitleOptions, redraw) {
  14373. this.update({ title: newTitleOptions }, redraw);
  14374. },
  14375. /**
  14376. * Set new axis categories and optionally redraw
  14377. * @param {Array} categories
  14378. * @param {Boolean} redraw
  14379. */
  14380. setCategories: function (categories, redraw) {
  14381. this.update({ categories: categories }, redraw);
  14382. }
  14383. });
  14384. /**
  14385. * LineSeries object
  14386. */
  14387. var LineSeries = extendClass(Series);
  14388. seriesTypes.line = LineSeries;
  14389. /**
  14390. * Set the default options for area
  14391. */
  14392. defaultPlotOptions.area = merge(defaultSeriesOptions, {
  14393. softThreshold: false,
  14394. threshold: 0
  14395. // trackByArea: false,
  14396. // lineColor: null, // overrides color, but lets fillColor be unaltered
  14397. // fillOpacity: 0.75,
  14398. // fillColor: null
  14399. });
  14400. /**
  14401. * AreaSeries object
  14402. */
  14403. var AreaSeries = extendClass(Series, {
  14404. type: 'area',
  14405. singleStacks: false,
  14406. /**
  14407. * Return an array of stacked points, where null and missing points are replaced by
  14408. * dummy points in order for gaps to be drawn correctly in stacks.
  14409. */
  14410. getStackPoints: function () {
  14411. var series = this,
  14412. segment = [],
  14413. keys = [],
  14414. xAxis = this.xAxis,
  14415. yAxis = this.yAxis,
  14416. stack = yAxis.stacks[this.stackKey],
  14417. pointMap = {},
  14418. points = this.points,
  14419. seriesIndex = series.index,
  14420. yAxisSeries = yAxis.series,
  14421. seriesLength = yAxisSeries.length,
  14422. visibleSeries,
  14423. upOrDown = pick(yAxis.options.reversedStacks, true) ? 1 : -1,
  14424. i,
  14425. x;
  14426. if (this.options.stacking) {
  14427. // Create a map where we can quickly look up the points by their X value.
  14428. for (i = 0; i < points.length; i++) {
  14429. pointMap[points[i].x] = points[i];
  14430. }
  14431. // Sort the keys (#1651)
  14432. for (x in stack) {
  14433. if (stack[x].total !== null) { // nulled after switching between grouping and not (#1651, #2336)
  14434. keys.push(x);
  14435. }
  14436. }
  14437. keys.sort(function (a, b) {
  14438. return a - b;
  14439. });
  14440. visibleSeries = map(yAxisSeries, function () {
  14441. return this.visible;
  14442. });
  14443. each(keys, function (x, idx) {
  14444. var y = 0,
  14445. stackPoint,
  14446. stackedValues;
  14447. if (pointMap[x] && !pointMap[x].isNull) {
  14448. segment.push(pointMap[x]);
  14449. // Find left and right cliff. -1 goes left, 1 goes right.
  14450. each([-1, 1], function (direction) {
  14451. var nullName = direction === 1 ? 'rightNull' : 'leftNull',
  14452. cliffName = direction === 1 ? 'rightCliff' : 'leftCliff',
  14453. cliff = 0,
  14454. otherStack = stack[keys[idx + direction]];
  14455. // If there is a stack next to this one, to the left or to the right...
  14456. if (otherStack) {
  14457. i = seriesIndex;
  14458. while (i >= 0 && i < seriesLength) { // Can go either up or down, depending on reversedStacks
  14459. stackPoint = otherStack.points[i];
  14460. if (!stackPoint) {
  14461. // If the next point in this series is missing, mark the point
  14462. // with point.leftNull or point.rightNull = true.
  14463. if (i === seriesIndex) {
  14464. pointMap[x][nullName] = true;
  14465. // If there are missing points in the next stack in any of the
  14466. // series below this one, we need to substract the missing values
  14467. // and add a hiatus to the left or right.
  14468. } else if (visibleSeries[i]) {
  14469. stackedValues = stack[x].points[i];
  14470. if (stackedValues) {
  14471. cliff -= stackedValues[1] - stackedValues[0];
  14472. }
  14473. }
  14474. }
  14475. // When reversedStacks is true, loop up, else loop down
  14476. i += upOrDown;
  14477. }
  14478. }
  14479. pointMap[x][cliffName] = cliff;
  14480. });
  14481. // There is no point for this X value in this series, so we
  14482. // insert a dummy point in order for the areas to be drawn
  14483. // correctly.
  14484. } else {
  14485. // Loop down the stack to find the series below this one that has
  14486. // a value (#1991)
  14487. i = seriesIndex;
  14488. while (i >= 0 && i < seriesLength) {
  14489. stackPoint = stack[x].points[i];
  14490. if (stackPoint) {
  14491. y = stackPoint[1];
  14492. break;
  14493. }
  14494. // When reversedStacks is true, loop up, else loop down
  14495. i += upOrDown;
  14496. }
  14497. y = yAxis.toPixels(y, true);
  14498. segment.push({
  14499. isNull: true,
  14500. plotX: xAxis.toPixels(x, true),
  14501. plotY: y,
  14502. yBottom: y
  14503. });
  14504. }
  14505. });
  14506. }
  14507. return segment;
  14508. },
  14509. getGraphPath: function (points) {
  14510. var getGraphPath = Series.prototype.getGraphPath,
  14511. graphPath,
  14512. options = this.options,
  14513. stacking = options.stacking,
  14514. yAxis = this.yAxis,
  14515. topPath,
  14516. //topPoints = [],
  14517. bottomPath,
  14518. bottomPoints = [],
  14519. graphPoints = [],
  14520. seriesIndex = this.index,
  14521. i,
  14522. areaPath,
  14523. plotX,
  14524. stacks = yAxis.stacks[this.stackKey],
  14525. threshold = options.threshold,
  14526. translatedThreshold = yAxis.getThreshold(options.threshold),
  14527. isNull,
  14528. yBottom,
  14529. connectNulls = options.connectNulls || stacking === 'percent',
  14530. /**
  14531. * To display null points in underlying stacked series, this series graph must be
  14532. * broken, and the area also fall down to fill the gap left by the null point. #2069
  14533. */
  14534. addDummyPoints = function (i, otherI, side) {
  14535. var point = points[i],
  14536. stackedValues = stacking && stacks[point.x].points[seriesIndex],
  14537. nullVal = point[side + 'Null'] || 0,
  14538. cliffVal = point[side + 'Cliff'] || 0,
  14539. top,
  14540. bottom,
  14541. isNull = true;
  14542. if (cliffVal || nullVal) {
  14543. top = (nullVal ? stackedValues[0] : stackedValues[1]) + cliffVal;
  14544. bottom = stackedValues[0] + cliffVal;
  14545. isNull = !!nullVal;
  14546. } else if (!stacking && points[otherI] && points[otherI].isNull) {
  14547. top = bottom = threshold;
  14548. }
  14549. // Add to the top and bottom line of the area
  14550. if (top !== undefined) {
  14551. graphPoints.push({
  14552. plotX: plotX,
  14553. plotY: top === null ? translatedThreshold : yAxis.getThreshold(top),
  14554. isNull: isNull
  14555. });
  14556. bottomPoints.push({
  14557. plotX: plotX,
  14558. plotY: bottom === null ? translatedThreshold : yAxis.getThreshold(bottom),
  14559. doCurve: false // #1041, gaps in areaspline areas
  14560. });
  14561. }
  14562. };
  14563. // Find what points to use
  14564. points = points || this.points;
  14565. // Fill in missing points
  14566. if (stacking) {
  14567. points = this.getStackPoints();
  14568. }
  14569. for (i = 0; i < points.length; i++) {
  14570. isNull = points[i].isNull;
  14571. plotX = pick(points[i].rectPlotX, points[i].plotX);
  14572. yBottom = pick(points[i].yBottom, translatedThreshold);
  14573. if (!isNull || connectNulls) {
  14574. if (!connectNulls) {
  14575. addDummyPoints(i, i - 1, 'left');
  14576. }
  14577. if (!(isNull && !stacking && connectNulls)) { // Skip null point when stacking is false and connectNulls true
  14578. graphPoints.push(points[i]);
  14579. bottomPoints.push({
  14580. x: i,
  14581. plotX: plotX,
  14582. plotY: yBottom
  14583. });
  14584. }
  14585. if (!connectNulls) {
  14586. addDummyPoints(i, i + 1, 'right');
  14587. }
  14588. }
  14589. }
  14590. topPath = getGraphPath.call(this, graphPoints, true, true);
  14591. bottomPoints.reversed = true;
  14592. bottomPath = getGraphPath.call(this, bottomPoints, true, true);
  14593. if (bottomPath.length) {
  14594. bottomPath[0] = L;
  14595. }
  14596. areaPath = topPath.concat(bottomPath);
  14597. graphPath = getGraphPath.call(this, graphPoints, false, connectNulls); // TODO: don't set leftCliff and rightCliff when connectNulls?
  14598. areaPath.xMap = topPath.xMap;
  14599. this.areaPath = areaPath;
  14600. return graphPath;
  14601. },
  14602. /**
  14603. * Draw the graph and the underlying area. This method calls the Series base
  14604. * function and adds the area. The areaPath is calculated in the getSegmentPath
  14605. * method called from Series.prototype.drawGraph.
  14606. */
  14607. drawGraph: function () {
  14608. // Define or reset areaPath
  14609. this.areaPath = [];
  14610. // Call the base method
  14611. Series.prototype.drawGraph.apply(this);
  14612. // Define local variables
  14613. var series = this,
  14614. areaPath = this.areaPath,
  14615. options = this.options,
  14616. zones = this.zones,
  14617. props = [['area', this.color, options.fillColor]]; // area name, main color, fill color
  14618. each(zones, function (threshold, i) {
  14619. props.push(['zoneArea' + i, threshold.color || series.color, threshold.fillColor || options.fillColor]);
  14620. });
  14621. each(props, function (prop) {
  14622. var areaKey = prop[0],
  14623. area = series[areaKey],
  14624. attr;
  14625. // Create or update the area
  14626. if (area) { // update
  14627. area.endX = areaPath.xMap;
  14628. area.animate({ d: areaPath });
  14629. } else { // create
  14630. attr = {
  14631. fill: prop[2] || prop[1],
  14632. zIndex: 0 // #1069
  14633. };
  14634. if (!prop[2]) {
  14635. attr['fill-opacity'] = pick(options.fillOpacity, 0.75);
  14636. }
  14637. area = series[areaKey] = series.chart.renderer.path(areaPath)
  14638. .attr(attr)
  14639. .add(series.group);
  14640. area.isArea = true;
  14641. }
  14642. area.startX = areaPath.xMap;
  14643. area.shiftUnit = options.step ? 2 : 1;
  14644. });
  14645. },
  14646. drawLegendSymbol: LegendSymbolMixin.drawRectangle
  14647. });
  14648. seriesTypes.area = AreaSeries;
  14649. /**
  14650. * Set the default options for spline
  14651. */
  14652. defaultPlotOptions.spline = merge(defaultSeriesOptions);
  14653. /**
  14654. * SplineSeries object
  14655. */
  14656. var SplineSeries = extendClass(Series, {
  14657. type: 'spline',
  14658. /**
  14659. * Get the spline segment from a given point's previous neighbour to the given point
  14660. */
  14661. getPointSpline: function (points, point, i) {
  14662. var smoothing = 1.5, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc
  14663. denom = smoothing + 1,
  14664. plotX = point.plotX,
  14665. plotY = point.plotY,
  14666. lastPoint = points[i - 1],
  14667. nextPoint = points[i + 1],
  14668. leftContX,
  14669. leftContY,
  14670. rightContX,
  14671. rightContY,
  14672. ret;
  14673. function doCurve(otherPoint) {
  14674. return otherPoint && !otherPoint.isNull && otherPoint.doCurve !== false;
  14675. }
  14676. // Find control points
  14677. if (doCurve(lastPoint) && doCurve(nextPoint)) {
  14678. var lastX = lastPoint.plotX,
  14679. lastY = lastPoint.plotY,
  14680. nextX = nextPoint.plotX,
  14681. nextY = nextPoint.plotY,
  14682. correction = 0;
  14683. leftContX = (smoothing * plotX + lastX) / denom;
  14684. leftContY = (smoothing * plotY + lastY) / denom;
  14685. rightContX = (smoothing * plotX + nextX) / denom;
  14686. rightContY = (smoothing * plotY + nextY) / denom;
  14687. // Have the two control points make a straight line through main point
  14688. if (rightContX !== leftContX) { // #5016, division by zero
  14689. correction = ((rightContY - leftContY) * (rightContX - plotX)) /
  14690. (rightContX - leftContX) + plotY - rightContY;
  14691. }
  14692. leftContY += correction;
  14693. rightContY += correction;
  14694. // to prevent false extremes, check that control points are between
  14695. // neighbouring points' y values
  14696. if (leftContY > lastY && leftContY > plotY) {
  14697. leftContY = mathMax(lastY, plotY);
  14698. rightContY = 2 * plotY - leftContY; // mirror of left control point
  14699. } else if (leftContY < lastY && leftContY < plotY) {
  14700. leftContY = mathMin(lastY, plotY);
  14701. rightContY = 2 * plotY - leftContY;
  14702. }
  14703. if (rightContY > nextY && rightContY > plotY) {
  14704. rightContY = mathMax(nextY, plotY);
  14705. leftContY = 2 * plotY - rightContY;
  14706. } else if (rightContY < nextY && rightContY < plotY) {
  14707. rightContY = mathMin(nextY, plotY);
  14708. leftContY = 2 * plotY - rightContY;
  14709. }
  14710. // record for drawing in next point
  14711. point.rightContX = rightContX;
  14712. point.rightContY = rightContY;
  14713. }
  14714. // Visualize control points for debugging
  14715. /*
  14716. if (leftContX) {
  14717. this.chart.renderer.circle(leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 2)
  14718. .attr({
  14719. stroke: 'red',
  14720. 'stroke-width': 2,
  14721. fill: 'none',
  14722. zIndex: 9
  14723. })
  14724. .add();
  14725. this.chart.renderer.path(['M', leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop,
  14726. 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
  14727. .attr({
  14728. stroke: 'red',
  14729. 'stroke-width': 2,
  14730. zIndex: 9
  14731. })
  14732. .add();
  14733. }
  14734. if (rightContX) {
  14735. this.chart.renderer.circle(rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 2)
  14736. .attr({
  14737. stroke: 'green',
  14738. 'stroke-width': 2,
  14739. fill: 'none',
  14740. zIndex: 9
  14741. })
  14742. .add();
  14743. this.chart.renderer.path(['M', rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop,
  14744. 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
  14745. .attr({
  14746. stroke: 'green',
  14747. 'stroke-width': 2,
  14748. zIndex: 9
  14749. })
  14750. .add();
  14751. }
  14752. // */
  14753. ret = [
  14754. 'C',
  14755. pick(lastPoint.rightContX, lastPoint.plotX),
  14756. pick(lastPoint.rightContY, lastPoint.plotY),
  14757. pick(leftContX, plotX),
  14758. pick(leftContY, plotY),
  14759. plotX,
  14760. plotY
  14761. ];
  14762. lastPoint.rightContX = lastPoint.rightContY = null; // reset for updating series later
  14763. return ret;
  14764. }
  14765. });
  14766. seriesTypes.spline = SplineSeries;
  14767. /**
  14768. * Set the default options for areaspline
  14769. */
  14770. defaultPlotOptions.areaspline = merge(defaultPlotOptions.area);
  14771. /**
  14772. * AreaSplineSeries object
  14773. */
  14774. var areaProto = AreaSeries.prototype,
  14775. AreaSplineSeries = extendClass(SplineSeries, {
  14776. type: 'areaspline',
  14777. getStackPoints: areaProto.getStackPoints,
  14778. getGraphPath: areaProto.getGraphPath,
  14779. setStackCliffs: areaProto.setStackCliffs,
  14780. drawGraph: areaProto.drawGraph,
  14781. drawLegendSymbol: LegendSymbolMixin.drawRectangle
  14782. });
  14783. seriesTypes.areaspline = AreaSplineSeries;
  14784. /**
  14785. * Set the default options for column
  14786. */
  14787. defaultPlotOptions.column = merge(defaultSeriesOptions, {
  14788. borderColor: '#FFFFFF',
  14789. //borderWidth: 1,
  14790. borderRadius: 0,
  14791. //colorByPoint: undefined,
  14792. groupPadding: 0.2,
  14793. //grouping: true,
  14794. marker: null, // point options are specified in the base options
  14795. pointPadding: 0.1,
  14796. //pointWidth: null,
  14797. minPointLength: 0,
  14798. cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes
  14799. pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories
  14800. states: {
  14801. hover: {
  14802. brightness: 0.1,
  14803. shadow: false,
  14804. halo: false
  14805. },
  14806. select: {
  14807. color: '#C0C0C0',
  14808. borderColor: '#000000',
  14809. shadow: false
  14810. }
  14811. },
  14812. dataLabels: {
  14813. align: null, // auto
  14814. verticalAlign: null, // auto
  14815. y: null
  14816. },
  14817. softThreshold: false,
  14818. startFromThreshold: true, // false doesn't work well: http://jsfiddle.net/highcharts/hz8fopan/14/
  14819. stickyTracking: false,
  14820. tooltip: {
  14821. distance: 6
  14822. },
  14823. threshold: 0
  14824. });
  14825. /**
  14826. * ColumnSeries object
  14827. */
  14828. var ColumnSeries = extendClass(Series, {
  14829. type: 'column',
  14830. pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
  14831. stroke: 'borderColor',
  14832. fill: 'color',
  14833. r: 'borderRadius'
  14834. },
  14835. cropShoulder: 0,
  14836. directTouch: true, // When tooltip is not shared, this series (and derivatives) requires direct touch/hover. KD-tree does not apply.
  14837. trackerGroups: ['group', 'dataLabelsGroup'],
  14838. negStacks: true, // use separate negative stacks, unlike area stacks where a negative
  14839. // point is substracted from previous (#1910)
  14840. /**
  14841. * Initialize the series
  14842. */
  14843. init: function () {
  14844. Series.prototype.init.apply(this, arguments);
  14845. var series = this,
  14846. chart = series.chart;
  14847. // if the series is added dynamically, force redraw of other
  14848. // series affected by a new column
  14849. if (chart.hasRendered) {
  14850. each(chart.series, function (otherSeries) {
  14851. if (otherSeries.type === series.type) {
  14852. otherSeries.isDirty = true;
  14853. }
  14854. });
  14855. }
  14856. },
  14857. /**
  14858. * Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding,
  14859. * pointWidth etc.
  14860. */
  14861. getColumnMetrics: function () {
  14862. var series = this,
  14863. options = series.options,
  14864. xAxis = series.xAxis,
  14865. yAxis = series.yAxis,
  14866. reversedXAxis = xAxis.reversed,
  14867. stackKey,
  14868. stackGroups = {},
  14869. columnCount = 0;
  14870. // Get the total number of column type series.
  14871. // This is called on every series. Consider moving this logic to a
  14872. // chart.orderStacks() function and call it on init, addSeries and removeSeries
  14873. if (options.grouping === false) {
  14874. columnCount = 1;
  14875. } else {
  14876. each(series.chart.series, function (otherSeries) {
  14877. var otherOptions = otherSeries.options,
  14878. otherYAxis = otherSeries.yAxis,
  14879. columnIndex;
  14880. if (otherSeries.type === series.type && otherSeries.visible &&
  14881. yAxis.len === otherYAxis.len && yAxis.pos === otherYAxis.pos) { // #642, #2086
  14882. if (otherOptions.stacking) {
  14883. stackKey = otherSeries.stackKey;
  14884. if (stackGroups[stackKey] === UNDEFINED) {
  14885. stackGroups[stackKey] = columnCount++;
  14886. }
  14887. columnIndex = stackGroups[stackKey];
  14888. } else if (otherOptions.grouping !== false) { // #1162
  14889. columnIndex = columnCount++;
  14890. }
  14891. otherSeries.columnIndex = columnIndex;
  14892. }
  14893. });
  14894. }
  14895. var categoryWidth = mathMin(
  14896. mathAbs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || xAxis.tickInterval || 1), // #2610
  14897. xAxis.len // #1535
  14898. ),
  14899. groupPadding = categoryWidth * options.groupPadding,
  14900. groupWidth = categoryWidth - 2 * groupPadding,
  14901. pointOffsetWidth = groupWidth / columnCount,
  14902. pointWidth = mathMin(
  14903. options.maxPointWidth || xAxis.len,
  14904. pick(options.pointWidth, pointOffsetWidth * (1 - 2 * options.pointPadding))
  14905. ),
  14906. pointPadding = (pointOffsetWidth - pointWidth) / 2,
  14907. colIndex = (series.columnIndex || 0) + (reversedXAxis ? 1 : 0), // #1251, #3737
  14908. pointXOffset = pointPadding + (groupPadding + colIndex *
  14909. pointOffsetWidth - (categoryWidth / 2)) *
  14910. (reversedXAxis ? -1 : 1);
  14911. // Save it for reading in linked series (Error bars particularly)
  14912. series.columnMetrics = {
  14913. width: pointWidth,
  14914. offset: pointXOffset
  14915. };
  14916. return series.columnMetrics;
  14917. },
  14918. /**
  14919. * Make the columns crisp. The edges are rounded to the nearest full pixel.
  14920. */
  14921. crispCol: function (x, y, w, h) {
  14922. var chart = this.chart,
  14923. borderWidth = this.borderWidth,
  14924. xCrisp = -(borderWidth % 2 ? 0.5 : 0),
  14925. yCrisp = borderWidth % 2 ? 0.5 : 1,
  14926. right,
  14927. bottom,
  14928. fromTop;
  14929. if (chart.inverted && chart.renderer.isVML) {
  14930. yCrisp += 1;
  14931. }
  14932. // Horizontal. We need to first compute the exact right edge, then round it
  14933. // and compute the width from there.
  14934. right = Math.round(x + w) + xCrisp;
  14935. x = Math.round(x) + xCrisp;
  14936. w = right - x;
  14937. // Vertical
  14938. bottom = Math.round(y + h) + yCrisp;
  14939. fromTop = mathAbs(y) <= 0.5 && bottom > 0.5; // #4504, #4656
  14940. y = Math.round(y) + yCrisp;
  14941. h = bottom - y;
  14942. // Top edges are exceptions
  14943. if (fromTop && h) { // #5146
  14944. y -= 1;
  14945. h += 1;
  14946. }
  14947. return {
  14948. x: x,
  14949. y: y,
  14950. width: w,
  14951. height: h
  14952. };
  14953. },
  14954. /**
  14955. * Translate each point to the plot area coordinate system and find shape positions
  14956. */
  14957. translate: function () {
  14958. var series = this,
  14959. chart = series.chart,
  14960. options = series.options,
  14961. borderWidth = series.borderWidth = pick(
  14962. options.borderWidth,
  14963. series.closestPointRange * series.xAxis.transA < 2 ? 0 : 1 // #3635
  14964. ),
  14965. yAxis = series.yAxis,
  14966. threshold = options.threshold,
  14967. translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold),
  14968. minPointLength = pick(options.minPointLength, 5),
  14969. metrics = series.getColumnMetrics(),
  14970. pointWidth = metrics.width,
  14971. seriesBarW = series.barW = mathMax(pointWidth, 1 + 2 * borderWidth), // postprocessed for border width
  14972. pointXOffset = series.pointXOffset = metrics.offset;
  14973. if (chart.inverted) {
  14974. translatedThreshold -= 0.5; // #3355
  14975. }
  14976. // When the pointPadding is 0, we want the columns to be packed tightly, so we allow individual
  14977. // columns to have individual sizes. When pointPadding is greater, we strive for equal-width
  14978. // columns (#2694).
  14979. if (options.pointPadding) {
  14980. seriesBarW = mathCeil(seriesBarW);
  14981. }
  14982. Series.prototype.translate.apply(series);
  14983. // Record the new values
  14984. each(series.points, function (point) {
  14985. var yBottom = mathMin(pick(point.yBottom, translatedThreshold), 9e4), // #3575
  14986. safeDistance = 999 + mathAbs(yBottom),
  14987. plotY = mathMin(mathMax(-safeDistance, point.plotY), yAxis.len + safeDistance), // Don't draw too far outside plot area (#1303, #2241, #4264)
  14988. barX = point.plotX + pointXOffset,
  14989. barW = seriesBarW,
  14990. barY = mathMin(plotY, yBottom),
  14991. up,
  14992. barH = mathMax(plotY, yBottom) - barY;
  14993. // Handle options.minPointLength
  14994. if (mathAbs(barH) < minPointLength) {
  14995. if (minPointLength) {
  14996. barH = minPointLength;
  14997. up = (!yAxis.reversed && !point.negative) || (yAxis.reversed && point.negative);
  14998. barY = mathAbs(barY - translatedThreshold) > minPointLength ? // stacked
  14999. yBottom - minPointLength : // keep position
  15000. translatedThreshold - (up ? minPointLength : 0); // #1485, #4051
  15001. }
  15002. }
  15003. // Cache for access in polar
  15004. point.barX = barX;
  15005. point.pointWidth = pointWidth;
  15006. // Fix the tooltip on center of grouped columns (#1216, #424, #3648)
  15007. point.tooltipPos = chart.inverted ?
  15008. [yAxis.len + yAxis.pos - chart.plotLeft - plotY, series.xAxis.len - barX - barW / 2, barH] :
  15009. [barX + barW / 2, plotY + yAxis.pos - chart.plotTop, barH];
  15010. // Register shape type and arguments to be used in drawPoints
  15011. point.shapeType = 'rect';
  15012. point.shapeArgs = series.crispCol.apply(
  15013. series,
  15014. point.isNull ?
  15015. [point.plotX, yAxis.len / 2, 0, 0] : // #3169, drilldown from null must have a position to work from
  15016. [barX, barY, barW, barH]
  15017. );
  15018. });
  15019. },
  15020. getSymbol: noop,
  15021. /**
  15022. * Use a solid rectangle like the area series types
  15023. */
  15024. drawLegendSymbol: LegendSymbolMixin.drawRectangle,
  15025. /**
  15026. * Columns have no graph
  15027. */
  15028. drawGraph: noop,
  15029. /**
  15030. * Draw the columns. For bars, the series.group is rotated, so the same coordinates
  15031. * apply for columns and bars. This method is inherited by scatter series.
  15032. *
  15033. */
  15034. drawPoints: function () {
  15035. var series = this,
  15036. chart = this.chart,
  15037. options = series.options,
  15038. renderer = chart.renderer,
  15039. animationLimit = options.animationLimit || 250,
  15040. shapeArgs,
  15041. pointAttr;
  15042. // draw the columns
  15043. each(series.points, function (point) {
  15044. var plotY = point.plotY,
  15045. graphic = point.graphic,
  15046. borderAttr;
  15047. if (isNumber(plotY) && point.y !== null) {
  15048. shapeArgs = point.shapeArgs;
  15049. borderAttr = defined(series.borderWidth) ? {
  15050. 'stroke-width': series.borderWidth
  15051. } : {};
  15052. pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || series.pointAttr[NORMAL_STATE];
  15053. if (graphic) { // update
  15054. stop(graphic);
  15055. graphic.attr(borderAttr).attr(pointAttr)[chart.pointCount < animationLimit ? 'animate' : 'attr'](merge(shapeArgs)); // #4267
  15056. } else {
  15057. point.graphic = graphic = renderer[point.shapeType](shapeArgs)
  15058. .attr(borderAttr)
  15059. .attr(pointAttr)
  15060. .add(point.group || series.group)
  15061. .shadow(options.shadow, null, options.stacking && !options.borderRadius);
  15062. }
  15063. } else if (graphic) {
  15064. point.graphic = graphic.destroy(); // #1269
  15065. }
  15066. });
  15067. },
  15068. /**
  15069. * Animate the column heights one by one from zero
  15070. * @param {Boolean} init Whether to initialize the animation or run it
  15071. */
  15072. animate: function (init) {
  15073. var series = this,
  15074. yAxis = this.yAxis,
  15075. options = series.options,
  15076. inverted = this.chart.inverted,
  15077. attr = {},
  15078. translatedThreshold;
  15079. if (hasSVG) { // VML is too slow anyway
  15080. if (init) {
  15081. attr.scaleY = 0.001;
  15082. translatedThreshold = mathMin(yAxis.pos + yAxis.len, mathMax(yAxis.pos, yAxis.toPixels(options.threshold)));
  15083. if (inverted) {
  15084. attr.translateX = translatedThreshold - yAxis.len;
  15085. } else {
  15086. attr.translateY = translatedThreshold;
  15087. }
  15088. series.group.attr(attr);
  15089. } else { // run the animation
  15090. attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos;
  15091. series.group.animate(attr, extend(animObject(series.options.animation), {
  15092. // Do the scale synchronously to ensure smooth updating (#5030)
  15093. step: function (val, fx) {
  15094. series.group.attr({
  15095. scaleY: mathMax(0.001, fx.pos) // #5250
  15096. });
  15097. }
  15098. }));
  15099. // delete this function to allow it only once
  15100. series.animate = null;
  15101. }
  15102. }
  15103. },
  15104. /**
  15105. * Remove this series from the chart
  15106. */
  15107. remove: function () {
  15108. var series = this,
  15109. chart = series.chart;
  15110. // column and bar series affects other series of the same type
  15111. // as they are either stacked or grouped
  15112. if (chart.hasRendered) {
  15113. each(chart.series, function (otherSeries) {
  15114. if (otherSeries.type === series.type) {
  15115. otherSeries.isDirty = true;
  15116. }
  15117. });
  15118. }
  15119. Series.prototype.remove.apply(series, arguments);
  15120. }
  15121. });
  15122. seriesTypes.column = ColumnSeries;
  15123. /**
  15124. * Set the default options for bar
  15125. */
  15126. defaultPlotOptions.bar = merge(defaultPlotOptions.column);
  15127. /**
  15128. * The Bar series class
  15129. */
  15130. var BarSeries = extendClass(ColumnSeries, {
  15131. type: 'bar',
  15132. inverted: true
  15133. });
  15134. seriesTypes.bar = BarSeries;
  15135. /**
  15136. * Set the default options for scatter
  15137. */
  15138. defaultPlotOptions.scatter = merge(defaultSeriesOptions, {
  15139. lineWidth: 0,
  15140. marker: {
  15141. enabled: true // Overrides auto-enabling in line series (#3647)
  15142. },
  15143. tooltip: {
  15144. headerFormat: '<span style="color:{point.color}">\u25CF</span> <span style="font-size: 10px;"> {series.name}</span><br/>',
  15145. pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>'
  15146. }
  15147. });
  15148. /**
  15149. * The scatter series class
  15150. */
  15151. var ScatterSeries = extendClass(Series, {
  15152. type: 'scatter',
  15153. sorted: false,
  15154. requireSorting: false,
  15155. noSharedTooltip: true,
  15156. trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'],
  15157. takeOrdinalPosition: false, // #2342
  15158. kdDimensions: 2,
  15159. drawGraph: function () {
  15160. if (this.options.lineWidth) {
  15161. Series.prototype.drawGraph.call(this);
  15162. }
  15163. }
  15164. });
  15165. seriesTypes.scatter = ScatterSeries;
  15166. /**
  15167. * Set the default options for pie
  15168. */
  15169. defaultPlotOptions.pie = merge(defaultSeriesOptions, {
  15170. borderColor: '#FFFFFF',
  15171. borderWidth: 1,
  15172. center: [null, null],
  15173. clip: false,
  15174. colorByPoint: true, // always true for pies
  15175. dataLabels: {
  15176. // align: null,
  15177. // connectorWidth: 1,
  15178. // connectorColor: point.color,
  15179. // connectorPadding: 5,
  15180. distance: 30,
  15181. enabled: true,
  15182. formatter: function () { // #2945
  15183. return this.y === null ? undefined : this.point.name;
  15184. },
  15185. // softConnector: true,
  15186. x: 0
  15187. // y: 0
  15188. },
  15189. ignoreHiddenPoint: true,
  15190. //innerSize: 0,
  15191. legendType: 'point',
  15192. marker: null, // point options are specified in the base options
  15193. size: null,
  15194. showInLegend: false,
  15195. slicedOffset: 10,
  15196. states: {
  15197. hover: {
  15198. brightness: 0.1,
  15199. shadow: false
  15200. }
  15201. },
  15202. stickyTracking: false,
  15203. tooltip: {
  15204. followPointer: true
  15205. }
  15206. });
  15207. /**
  15208. * Extended point object for pies
  15209. */
  15210. var PiePoint = extendClass(Point, {
  15211. /**
  15212. * Initiate the pie slice
  15213. */
  15214. init: function () {
  15215. Point.prototype.init.apply(this, arguments);
  15216. var point = this,
  15217. toggleSlice;
  15218. point.name = pick(point.name, 'Slice');
  15219. // add event listener for select
  15220. toggleSlice = function (e) {
  15221. point.slice(e.type === 'select');
  15222. };
  15223. addEvent(point, 'select', toggleSlice);
  15224. addEvent(point, 'unselect', toggleSlice);
  15225. return point;
  15226. },
  15227. /**
  15228. * Toggle the visibility of the pie slice
  15229. * @param {Boolean} vis Whether to show the slice or not. If undefined, the
  15230. * visibility is toggled
  15231. */
  15232. setVisible: function (vis, redraw) {
  15233. var point = this,
  15234. series = point.series,
  15235. chart = series.chart,
  15236. ignoreHiddenPoint = series.options.ignoreHiddenPoint;
  15237. redraw = pick(redraw, ignoreHiddenPoint);
  15238. if (vis !== point.visible) {
  15239. // If called without an argument, toggle visibility
  15240. point.visible = point.options.visible = vis = vis === UNDEFINED ? !point.visible : vis;
  15241. series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data
  15242. // Show and hide associated elements. This is performed regardless of redraw or not,
  15243. // because chart.redraw only handles full series.
  15244. each(['graphic', 'dataLabel', 'connector', 'shadowGroup'], function (key) {
  15245. if (point[key]) {
  15246. point[key][vis ? 'show' : 'hide'](true);
  15247. }
  15248. });
  15249. if (point.legendItem) {
  15250. chart.legend.colorizeItem(point, vis);
  15251. }
  15252. // #4170, hide halo after hiding point
  15253. if (!vis && point.state === 'hover') {
  15254. point.setState('');
  15255. }
  15256. // Handle ignore hidden slices
  15257. if (ignoreHiddenPoint) {
  15258. series.isDirty = true;
  15259. }
  15260. if (redraw) {
  15261. chart.redraw();
  15262. }
  15263. }
  15264. },
  15265. /**
  15266. * Set or toggle whether the slice is cut out from the pie
  15267. * @param {Boolean} sliced When undefined, the slice state is toggled
  15268. * @param {Boolean} redraw Whether to redraw the chart. True by default.
  15269. */
  15270. slice: function (sliced, redraw, animation) {
  15271. var point = this,
  15272. series = point.series,
  15273. chart = series.chart,
  15274. translation;
  15275. setAnimation(animation, chart);
  15276. // redraw is true by default
  15277. redraw = pick(redraw, true);
  15278. // if called without an argument, toggle
  15279. point.sliced = point.options.sliced = sliced = defined(sliced) ? sliced : !point.sliced;
  15280. series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data
  15281. translation = sliced ? point.slicedTranslation : {
  15282. translateX: 0,
  15283. translateY: 0
  15284. };
  15285. point.graphic.animate(translation);
  15286. if (point.shadowGroup) {
  15287. point.shadowGroup.animate(translation);
  15288. }
  15289. },
  15290. haloPath: function (size) {
  15291. var shapeArgs = this.shapeArgs,
  15292. chart = this.series.chart;
  15293. 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, {
  15294. innerR: this.shapeArgs.r,
  15295. start: shapeArgs.start,
  15296. end: shapeArgs.end
  15297. });
  15298. }
  15299. });
  15300. /**
  15301. * The Pie series class
  15302. */
  15303. var PieSeries = {
  15304. type: 'pie',
  15305. isCartesian: false,
  15306. pointClass: PiePoint,
  15307. requireSorting: false,
  15308. directTouch: true,
  15309. noSharedTooltip: true,
  15310. trackerGroups: ['group', 'dataLabelsGroup'],
  15311. axisTypes: [],
  15312. pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
  15313. stroke: 'borderColor',
  15314. 'stroke-width': 'borderWidth',
  15315. fill: 'color'
  15316. },
  15317. /**
  15318. * Animate the pies in
  15319. */
  15320. animate: function (init) {
  15321. var series = this,
  15322. points = series.points,
  15323. startAngleRad = series.startAngleRad;
  15324. if (!init) {
  15325. each(points, function (point) {
  15326. var graphic = point.graphic,
  15327. args = point.shapeArgs;
  15328. if (graphic) {
  15329. // start values
  15330. graphic.attr({
  15331. r: point.startR || (series.center[3] / 2), // animate from inner radius (#779)
  15332. start: startAngleRad,
  15333. end: startAngleRad
  15334. });
  15335. // animate
  15336. graphic.animate({
  15337. r: args.r,
  15338. start: args.start,
  15339. end: args.end
  15340. }, series.options.animation);
  15341. }
  15342. });
  15343. // delete this function to allow it only once
  15344. series.animate = null;
  15345. }
  15346. },
  15347. /**
  15348. * Recompute total chart sum and update percentages of points.
  15349. */
  15350. updateTotals: function () {
  15351. var i,
  15352. total = 0,
  15353. points = this.points,
  15354. len = points.length,
  15355. point,
  15356. ignoreHiddenPoint = this.options.ignoreHiddenPoint;
  15357. // Get the total sum
  15358. for (i = 0; i < len; i++) {
  15359. point = points[i];
  15360. // Disallow negative values (#1530, #3623, #5322)
  15361. if (point.y < 0) {
  15362. point.y = null;
  15363. }
  15364. total += (ignoreHiddenPoint && !point.visible) ? 0 : point.y;
  15365. }
  15366. this.total = total;
  15367. // Set each point's properties
  15368. for (i = 0; i < len; i++) {
  15369. point = points[i];
  15370. point.percentage = (total > 0 && (point.visible || !ignoreHiddenPoint)) ? point.y / total * 100 : 0;
  15371. point.total = total;
  15372. }
  15373. },
  15374. /**
  15375. * Extend the generatePoints method by adding total and percentage properties to each point
  15376. */
  15377. generatePoints: function () {
  15378. Series.prototype.generatePoints.call(this);
  15379. this.updateTotals();
  15380. },
  15381. /**
  15382. * Do translation for pie slices
  15383. */
  15384. translate: function (positions) {
  15385. this.generatePoints();
  15386. var series = this,
  15387. cumulative = 0,
  15388. precision = 1000, // issue #172
  15389. options = series.options,
  15390. slicedOffset = options.slicedOffset,
  15391. connectorOffset = slicedOffset + options.borderWidth,
  15392. start,
  15393. end,
  15394. angle,
  15395. startAngle = options.startAngle || 0,
  15396. startAngleRad = series.startAngleRad = mathPI / 180 * (startAngle - 90),
  15397. endAngleRad = series.endAngleRad = mathPI / 180 * ((pick(options.endAngle, startAngle + 360)) - 90),
  15398. circ = endAngleRad - startAngleRad, //2 * mathPI,
  15399. points = series.points,
  15400. radiusX, // the x component of the radius vector for a given point
  15401. radiusY,
  15402. labelDistance = options.dataLabels.distance,
  15403. ignoreHiddenPoint = options.ignoreHiddenPoint,
  15404. i,
  15405. len = points.length,
  15406. point;
  15407. // Get positions - either an integer or a percentage string must be given.
  15408. // If positions are passed as a parameter, we're in a recursive loop for adjusting
  15409. // space for data labels.
  15410. if (!positions) {
  15411. series.center = positions = series.getCenter();
  15412. }
  15413. // utility for getting the x value from a given y, used for anticollision logic in data labels
  15414. series.getX = function (y, left) {
  15415. angle = math.asin(mathMin((y - positions[1]) / (positions[2] / 2 + labelDistance), 1));
  15416. return positions[0] +
  15417. (left ? -1 : 1) *
  15418. (mathCos(angle) * (positions[2] / 2 + labelDistance));
  15419. };
  15420. // Calculate the geometry for each point
  15421. for (i = 0; i < len; i++) {
  15422. point = points[i];
  15423. // set start and end angle
  15424. start = startAngleRad + (cumulative * circ);
  15425. if (!ignoreHiddenPoint || point.visible) {
  15426. cumulative += point.percentage / 100;
  15427. }
  15428. end = startAngleRad + (cumulative * circ);
  15429. // set the shape
  15430. point.shapeType = 'arc';
  15431. point.shapeArgs = {
  15432. x: positions[0],
  15433. y: positions[1],
  15434. r: positions[2] / 2,
  15435. innerR: positions[3] / 2,
  15436. start: mathRound(start * precision) / precision,
  15437. end: mathRound(end * precision) / precision
  15438. };
  15439. // The angle must stay within -90 and 270 (#2645)
  15440. angle = (end + start) / 2;
  15441. if (angle > 1.5 * mathPI) {
  15442. angle -= 2 * mathPI;
  15443. } else if (angle < -mathPI / 2) {
  15444. angle += 2 * mathPI;
  15445. }
  15446. // Center for the sliced out slice
  15447. point.slicedTranslation = {
  15448. translateX: mathRound(mathCos(angle) * slicedOffset),
  15449. translateY: mathRound(mathSin(angle) * slicedOffset)
  15450. };
  15451. // set the anchor point for tooltips
  15452. radiusX = mathCos(angle) * positions[2] / 2;
  15453. radiusY = mathSin(angle) * positions[2] / 2;
  15454. point.tooltipPos = [
  15455. positions[0] + radiusX * 0.7,
  15456. positions[1] + radiusY * 0.7
  15457. ];
  15458. point.half = angle < -mathPI / 2 || angle > mathPI / 2 ? 1 : 0;
  15459. point.angle = angle;
  15460. // set the anchor point for data labels
  15461. connectorOffset = mathMin(connectorOffset, labelDistance / 2); // #1678
  15462. point.labelPos = [
  15463. positions[0] + radiusX + mathCos(angle) * labelDistance, // first break of connector
  15464. positions[1] + radiusY + mathSin(angle) * labelDistance, // a/a
  15465. positions[0] + radiusX + mathCos(angle) * connectorOffset, // second break, right outside pie
  15466. positions[1] + radiusY + mathSin(angle) * connectorOffset, // a/a
  15467. positions[0] + radiusX, // landing point for connector
  15468. positions[1] + radiusY, // a/a
  15469. labelDistance < 0 ? // alignment
  15470. 'center' :
  15471. point.half ? 'right' : 'left', // alignment
  15472. angle // center angle
  15473. ];
  15474. }
  15475. },
  15476. drawGraph: null,
  15477. /**
  15478. * Draw the data points
  15479. */
  15480. drawPoints: function () {
  15481. var series = this,
  15482. chart = series.chart,
  15483. renderer = chart.renderer,
  15484. groupTranslation,
  15485. //center,
  15486. graphic,
  15487. //group,
  15488. shadow = series.options.shadow,
  15489. shadowGroup,
  15490. pointAttr,
  15491. shapeArgs,
  15492. attr;
  15493. if (shadow && !series.shadowGroup) {
  15494. series.shadowGroup = renderer.g('shadow')
  15495. .add(series.group);
  15496. }
  15497. // draw the slices
  15498. each(series.points, function (point) {
  15499. if (point.y !== null) {
  15500. graphic = point.graphic;
  15501. shapeArgs = point.shapeArgs;
  15502. shadowGroup = point.shadowGroup;
  15503. pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE];
  15504. if (!pointAttr.stroke) {
  15505. pointAttr.stroke = pointAttr.fill;
  15506. }
  15507. // put the shadow behind all points
  15508. if (shadow && !shadowGroup) {
  15509. shadowGroup = point.shadowGroup = renderer.g('shadow')
  15510. .add(series.shadowGroup);
  15511. }
  15512. // if the point is sliced, use special translation, else use plot area traslation
  15513. groupTranslation = point.sliced ? point.slicedTranslation : {
  15514. translateX: 0,
  15515. translateY: 0
  15516. };
  15517. //group.translate(groupTranslation[0], groupTranslation[1]);
  15518. if (shadowGroup) {
  15519. shadowGroup.attr(groupTranslation);
  15520. }
  15521. // draw the slice
  15522. if (graphic) {
  15523. graphic
  15524. .setRadialReference(series.center)
  15525. .attr(pointAttr)
  15526. .animate(extend(shapeArgs, groupTranslation));
  15527. } else {
  15528. attr = { 'stroke-linejoin': 'round' };
  15529. if (!point.visible) {
  15530. attr.visibility = 'hidden';
  15531. }
  15532. point.graphic = graphic = renderer[point.shapeType](shapeArgs)
  15533. .setRadialReference(series.center)
  15534. .attr(pointAttr)
  15535. .attr(attr)
  15536. .attr(groupTranslation)
  15537. .add(series.group)
  15538. .shadow(shadow, shadowGroup);
  15539. }
  15540. }
  15541. });
  15542. },
  15543. searchPoint: noop,
  15544. /**
  15545. * Utility for sorting data labels
  15546. */
  15547. sortByAngle: function (points, sign) {
  15548. points.sort(function (a, b) {
  15549. return a.angle !== undefined && (b.angle - a.angle) * sign;
  15550. });
  15551. },
  15552. /**
  15553. * Use a simple symbol from LegendSymbolMixin
  15554. */
  15555. drawLegendSymbol: LegendSymbolMixin.drawRectangle,
  15556. /**
  15557. * Use the getCenter method from drawLegendSymbol
  15558. */
  15559. getCenter: CenteredSeriesMixin.getCenter,
  15560. /**
  15561. * Pies don't have point marker symbols
  15562. */
  15563. getSymbol: noop
  15564. };
  15565. PieSeries = extendClass(Series, PieSeries);
  15566. seriesTypes.pie = PieSeries;
  15567. /**
  15568. * Draw the data labels
  15569. */
  15570. Series.prototype.drawDataLabels = function () {
  15571. var series = this,
  15572. seriesOptions = series.options,
  15573. cursor = seriesOptions.cursor,
  15574. options = seriesOptions.dataLabels,
  15575. points = series.points,
  15576. pointOptions,
  15577. generalOptions,
  15578. hasRendered = series.hasRendered || 0,
  15579. str,
  15580. dataLabelsGroup,
  15581. defer = pick(options.defer, true),
  15582. renderer = series.chart.renderer;
  15583. if (options.enabled || series._hasPointLabels) {
  15584. // Process default alignment of data labels for columns
  15585. if (series.dlProcessOptions) {
  15586. series.dlProcessOptions(options);
  15587. }
  15588. // Create a separate group for the data labels to avoid rotation
  15589. dataLabelsGroup = series.plotGroup(
  15590. 'dataLabelsGroup',
  15591. 'data-labels',
  15592. defer && !hasRendered ? 'hidden' : 'visible', // #5133
  15593. options.zIndex || 6
  15594. );
  15595. if (defer) {
  15596. dataLabelsGroup.attr({ opacity: +hasRendered }); // #3300
  15597. if (!hasRendered) {
  15598. addEvent(series, 'afterAnimate', function () {
  15599. if (series.visible) { // #2597, #3023, #3024
  15600. dataLabelsGroup.show(true);
  15601. }
  15602. dataLabelsGroup[seriesOptions.animation ? 'animate' : 'attr']({ opacity: 1 }, { duration: 200 });
  15603. });
  15604. }
  15605. }
  15606. // Make the labels for each point
  15607. generalOptions = options;
  15608. each(points, function (point) {
  15609. var enabled,
  15610. dataLabel = point.dataLabel,
  15611. labelConfig,
  15612. attr,
  15613. name,
  15614. rotation,
  15615. connector = point.connector,
  15616. isNew = true,
  15617. style,
  15618. moreStyle = {};
  15619. // Determine if each data label is enabled
  15620. pointOptions = point.dlOptions || (point.options && point.options.dataLabels); // dlOptions is used in treemaps
  15621. enabled = pick(pointOptions && pointOptions.enabled, generalOptions.enabled) && point.y !== null; // #2282, #4641
  15622. // If the point is outside the plot area, destroy it. #678, #820
  15623. if (dataLabel && !enabled) {
  15624. point.dataLabel = dataLabel.destroy();
  15625. // Individual labels are disabled if the are explicitly disabled
  15626. // in the point options, or if they fall outside the plot area.
  15627. } else if (enabled) {
  15628. // Create individual options structure that can be extended without
  15629. // affecting others
  15630. options = merge(generalOptions, pointOptions);
  15631. style = options.style;
  15632. rotation = options.rotation;
  15633. // Get the string
  15634. labelConfig = point.getLabelConfig();
  15635. str = options.format ?
  15636. format(options.format, labelConfig) :
  15637. options.formatter.call(labelConfig, options);
  15638. // Determine the color
  15639. style.color = pick(options.color, style.color, series.color, 'black');
  15640. // update existing label
  15641. if (dataLabel) {
  15642. if (defined(str)) {
  15643. dataLabel
  15644. .attr({
  15645. text: str
  15646. });
  15647. isNew = false;
  15648. } else { // #1437 - the label is shown conditionally
  15649. point.dataLabel = dataLabel = dataLabel.destroy();
  15650. if (connector) {
  15651. point.connector = connector.destroy();
  15652. }
  15653. }
  15654. // create new label
  15655. } else if (defined(str)) {
  15656. attr = {
  15657. //align: align,
  15658. fill: options.backgroundColor,
  15659. stroke: options.borderColor,
  15660. 'stroke-width': options.borderWidth,
  15661. r: options.borderRadius || 0,
  15662. rotation: rotation,
  15663. padding: options.padding,
  15664. zIndex: 1
  15665. };
  15666. // Get automated contrast color
  15667. if (style.color === 'contrast') {
  15668. moreStyle.color = options.inside || options.distance < 0 || !!seriesOptions.stacking ?
  15669. renderer.getContrast(point.color || series.color) :
  15670. '#000000';
  15671. }
  15672. if (cursor) {
  15673. moreStyle.cursor = cursor;
  15674. }
  15675. // Remove unused attributes (#947)
  15676. for (name in attr) {
  15677. if (attr[name] === UNDEFINED) {
  15678. delete attr[name];
  15679. }
  15680. }
  15681. dataLabel = point.dataLabel = renderer[rotation ? 'text' : 'label']( // labels don't support rotation
  15682. str,
  15683. 0,
  15684. -9999,
  15685. options.shape,
  15686. null,
  15687. null,
  15688. options.useHTML
  15689. )
  15690. .attr(attr)
  15691. .css(extend(style, moreStyle))
  15692. .add(dataLabelsGroup)
  15693. .shadow(options.shadow);
  15694. }
  15695. if (dataLabel) {
  15696. // Now the data label is created and placed at 0,0, so we need to align it
  15697. series.alignDataLabel(point, dataLabel, options, null, isNew);
  15698. }
  15699. }
  15700. });
  15701. }
  15702. };
  15703. /**
  15704. * Align each individual data label
  15705. */
  15706. Series.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) {
  15707. var chart = this.chart,
  15708. inverted = chart.inverted,
  15709. plotX = pick(point.plotX, -9999),
  15710. plotY = pick(point.plotY, -9999),
  15711. bBox = dataLabel.getBBox(),
  15712. baseline = chart.renderer.fontMetrics(options.style.fontSize).b,
  15713. rotation = options.rotation,
  15714. normRotation,
  15715. negRotation,
  15716. align = options.align,
  15717. rotCorr, // rotation correction
  15718. // Math.round for rounding errors (#2683), alignTo to allow column labels (#2700)
  15719. visible = this.visible && (point.series.forceDL || chart.isInsidePlot(plotX, mathRound(plotY), inverted) ||
  15720. (alignTo && chart.isInsidePlot(plotX, inverted ? alignTo.x + 1 : alignTo.y + alignTo.height - 1, inverted))),
  15721. alignAttr, // the final position;
  15722. justify = pick(options.overflow, 'justify') === 'justify';
  15723. if (visible) {
  15724. // The alignment box is a singular point
  15725. alignTo = extend({
  15726. x: inverted ? chart.plotWidth - plotY : plotX,
  15727. y: mathRound(inverted ? chart.plotHeight - plotX : plotY),
  15728. width: 0,
  15729. height: 0
  15730. }, alignTo);
  15731. // Add the text size for alignment calculation
  15732. extend(options, {
  15733. width: bBox.width,
  15734. height: bBox.height
  15735. });
  15736. // Allow a hook for changing alignment in the last moment, then do the alignment
  15737. if (rotation) {
  15738. justify = false; // Not supported for rotated text
  15739. rotCorr = chart.renderer.rotCorr(baseline, rotation); // #3723
  15740. alignAttr = {
  15741. x: alignTo.x + options.x + alignTo.width / 2 + rotCorr.x,
  15742. y: alignTo.y + options.y + { top: 0, middle: 0.5, bottom: 1 }[options.verticalAlign] * alignTo.height
  15743. };
  15744. dataLabel[isNew ? 'attr' : 'animate'](alignAttr)
  15745. .attr({ // #3003
  15746. align: align
  15747. });
  15748. // Compensate for the rotated label sticking out on the sides
  15749. normRotation = (rotation + 720) % 360;
  15750. negRotation = normRotation > 180 && normRotation < 360;
  15751. if (align === 'left') {
  15752. alignAttr.y -= negRotation ? bBox.height : 0;
  15753. } else if (align === 'center') {
  15754. alignAttr.x -= bBox.width / 2;
  15755. alignAttr.y -= bBox.height / 2;
  15756. } else if (align === 'right') {
  15757. alignAttr.x -= bBox.width;
  15758. alignAttr.y -= negRotation ? 0 : bBox.height;
  15759. }
  15760. } else {
  15761. dataLabel.align(options, null, alignTo);
  15762. alignAttr = dataLabel.alignAttr;
  15763. }
  15764. // Handle justify or crop
  15765. if (justify) {
  15766. this.justifyDataLabel(dataLabel, options, alignAttr, bBox, alignTo, isNew);
  15767. // Now check that the data label is within the plot area
  15768. } else if (pick(options.crop, true)) {
  15769. visible = chart.isInsidePlot(alignAttr.x, alignAttr.y) && chart.isInsidePlot(alignAttr.x + bBox.width, alignAttr.y + bBox.height);
  15770. }
  15771. // When we're using a shape, make it possible with a connector or an arrow pointing to thie point
  15772. if (options.shape && !rotation) {
  15773. dataLabel.attr({
  15774. anchorX: point.plotX,
  15775. anchorY: point.plotY
  15776. });
  15777. }
  15778. }
  15779. // Show or hide based on the final aligned position
  15780. if (!visible) {
  15781. stop(dataLabel);
  15782. dataLabel.attr({ y: -9999 });
  15783. dataLabel.placed = false; // don't animate back in
  15784. }
  15785. };
  15786. /**
  15787. * If data labels fall partly outside the plot area, align them back in, in a way that
  15788. * doesn't hide the point.
  15789. */
  15790. Series.prototype.justifyDataLabel = function (dataLabel, options, alignAttr, bBox, alignTo, isNew) {
  15791. var chart = this.chart,
  15792. align = options.align,
  15793. verticalAlign = options.verticalAlign,
  15794. off,
  15795. justified,
  15796. padding = dataLabel.box ? 0 : (dataLabel.padding || 0);
  15797. // Off left
  15798. off = alignAttr.x + padding;
  15799. if (off < 0) {
  15800. if (align === 'right') {
  15801. options.align = 'left';
  15802. } else {
  15803. options.x = -off;
  15804. }
  15805. justified = true;
  15806. }
  15807. // Off right
  15808. off = alignAttr.x + bBox.width - padding;
  15809. if (off > chart.plotWidth) {
  15810. if (align === 'left') {
  15811. options.align = 'right';
  15812. } else {
  15813. options.x = chart.plotWidth - off;
  15814. }
  15815. justified = true;
  15816. }
  15817. // Off top
  15818. off = alignAttr.y + padding;
  15819. if (off < 0) {
  15820. if (verticalAlign === 'bottom') {
  15821. options.verticalAlign = 'top';
  15822. } else {
  15823. options.y = -off;
  15824. }
  15825. justified = true;
  15826. }
  15827. // Off bottom
  15828. off = alignAttr.y + bBox.height - padding;
  15829. if (off > chart.plotHeight) {
  15830. if (verticalAlign === 'top') {
  15831. options.verticalAlign = 'bottom';
  15832. } else {
  15833. options.y = chart.plotHeight - off;
  15834. }
  15835. justified = true;
  15836. }
  15837. if (justified) {
  15838. dataLabel.placed = !isNew;
  15839. dataLabel.align(options, null, alignTo);
  15840. }
  15841. };
  15842. /**
  15843. * Override the base drawDataLabels method by pie specific functionality
  15844. */
  15845. if (seriesTypes.pie) {
  15846. seriesTypes.pie.prototype.drawDataLabels = function () {
  15847. var series = this,
  15848. data = series.data,
  15849. point,
  15850. chart = series.chart,
  15851. options = series.options.dataLabels,
  15852. connectorPadding = pick(options.connectorPadding, 10),
  15853. connectorWidth = pick(options.connectorWidth, 1),
  15854. plotWidth = chart.plotWidth,
  15855. plotHeight = chart.plotHeight,
  15856. connector,
  15857. connectorPath,
  15858. softConnector = pick(options.softConnector, true),
  15859. distanceOption = options.distance,
  15860. seriesCenter = series.center,
  15861. radius = seriesCenter[2] / 2,
  15862. centerY = seriesCenter[1],
  15863. outside = distanceOption > 0,
  15864. dataLabel,
  15865. dataLabelWidth,
  15866. labelPos,
  15867. labelHeight,
  15868. halves = [// divide the points into right and left halves for anti collision
  15869. [], // right
  15870. [] // left
  15871. ],
  15872. x,
  15873. y,
  15874. visibility,
  15875. rankArr,
  15876. i,
  15877. j,
  15878. overflow = [0, 0, 0, 0], // top, right, bottom, left
  15879. sort = function (a, b) {
  15880. return b.y - a.y;
  15881. };
  15882. // get out if not enabled
  15883. if (!series.visible || (!options.enabled && !series._hasPointLabels)) {
  15884. return;
  15885. }
  15886. // run parent method
  15887. Series.prototype.drawDataLabels.apply(series);
  15888. each(data, function (point) {
  15889. if (point.dataLabel && point.visible) { // #407, #2510
  15890. // Arrange points for detection collision
  15891. halves[point.half].push(point);
  15892. // Reset positions (#4905)
  15893. point.dataLabel._pos = null;
  15894. }
  15895. });
  15896. /* Loop over the points in each half, starting from the top and bottom
  15897. * of the pie to detect overlapping labels.
  15898. */
  15899. i = 2;
  15900. while (i--) {
  15901. var slots = [],
  15902. slotsLength,
  15903. usedSlots = [],
  15904. points = halves[i],
  15905. pos,
  15906. bottom,
  15907. length = points.length,
  15908. slotIndex;
  15909. if (!length) {
  15910. continue;
  15911. }
  15912. // Sort by angle
  15913. series.sortByAngle(points, i - 0.5);
  15914. // Assume equal label heights on either hemisphere (#2630)
  15915. j = labelHeight = 0;
  15916. while (!labelHeight && points[j]) { // #1569
  15917. labelHeight = points[j] && points[j].dataLabel && (points[j].dataLabel.getBBox().height || 21); // 21 is for #968
  15918. j++;
  15919. }
  15920. // Only do anti-collision when we are outside the pie and have connectors (#856)
  15921. if (distanceOption > 0) {
  15922. // Build the slots
  15923. bottom = mathMin(centerY + radius + distanceOption, chart.plotHeight);
  15924. for (pos = mathMax(0, centerY - radius - distanceOption); pos <= bottom; pos += labelHeight) {
  15925. slots.push(pos);
  15926. }
  15927. slotsLength = slots.length;
  15928. /* Visualize the slots
  15929. if (!series.slotElements) {
  15930. series.slotElements = [];
  15931. }
  15932. if (i === 1) {
  15933. series.slotElements.forEach(function (elem) {
  15934. elem.destroy();
  15935. });
  15936. series.slotElements.length = 0;
  15937. }
  15938. slots.forEach(function (pos, no) {
  15939. var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0),
  15940. slotY = pos + chart.plotTop;
  15941. if (isNumber(slotX)) {
  15942. series.slotElements.push(chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1)
  15943. .attr({
  15944. 'stroke-width': 1,
  15945. stroke: 'silver',
  15946. fill: 'rgba(0,0,255,0.1)'
  15947. })
  15948. .add());
  15949. series.slotElements.push(chart.renderer.text('Slot '+ no, slotX, slotY + 4)
  15950. .attr({
  15951. fill: 'silver'
  15952. }).add());
  15953. }
  15954. });
  15955. // */
  15956. // if there are more values than available slots, remove lowest values
  15957. if (length > slotsLength) {
  15958. // create an array for sorting and ranking the points within each quarter
  15959. rankArr = [].concat(points);
  15960. rankArr.sort(sort);
  15961. j = length;
  15962. while (j--) {
  15963. rankArr[j].rank = j;
  15964. }
  15965. j = length;
  15966. while (j--) {
  15967. if (points[j].rank >= slotsLength) {
  15968. points.splice(j, 1);
  15969. }
  15970. }
  15971. length = points.length;
  15972. }
  15973. // The label goes to the nearest open slot, but not closer to the edge than
  15974. // the label's index.
  15975. for (j = 0; j < length; j++) {
  15976. point = points[j];
  15977. labelPos = point.labelPos;
  15978. var closest = 9999,
  15979. distance,
  15980. slotI;
  15981. // find the closest slot index
  15982. for (slotI = 0; slotI < slotsLength; slotI++) {
  15983. distance = mathAbs(slots[slotI] - labelPos[1]);
  15984. if (distance < closest) {
  15985. closest = distance;
  15986. slotIndex = slotI;
  15987. }
  15988. }
  15989. // if that slot index is closer to the edges of the slots, move it
  15990. // to the closest appropriate slot
  15991. if (slotIndex < j && slots[j] !== null) { // cluster at the top
  15992. slotIndex = j;
  15993. } else if (slotsLength < length - j + slotIndex && slots[j] !== null) { // cluster at the bottom
  15994. slotIndex = slotsLength - length + j;
  15995. while (slots[slotIndex] === null) { // make sure it is not taken
  15996. slotIndex++;
  15997. }
  15998. } else {
  15999. // Slot is taken, find next free slot below. In the next run, the next slice will find the
  16000. // slot above these, because it is the closest one
  16001. while (slots[slotIndex] === null) { // make sure it is not taken
  16002. slotIndex++;
  16003. }
  16004. }
  16005. usedSlots.push({ i: slotIndex, y: slots[slotIndex] });
  16006. slots[slotIndex] = null; // mark as taken
  16007. }
  16008. // sort them in order to fill in from the top
  16009. usedSlots.sort(sort);
  16010. }
  16011. // now the used slots are sorted, fill them up sequentially
  16012. for (j = 0; j < length; j++) {
  16013. var slot, naturalY;
  16014. point = points[j];
  16015. labelPos = point.labelPos;
  16016. dataLabel = point.dataLabel;
  16017. visibility = point.visible === false ? HIDDEN : 'inherit';
  16018. naturalY = labelPos[1];
  16019. if (distanceOption > 0) {
  16020. slot = usedSlots.pop();
  16021. slotIndex = slot.i;
  16022. // if the slot next to currrent slot is free, the y value is allowed
  16023. // to fall back to the natural position
  16024. y = slot.y;
  16025. if ((naturalY > y && slots[slotIndex + 1] !== null) ||
  16026. (naturalY < y && slots[slotIndex - 1] !== null)) {
  16027. y = mathMin(mathMax(0, naturalY), chart.plotHeight);
  16028. }
  16029. } else {
  16030. y = naturalY;
  16031. }
  16032. // get the x - use the natural x position for first and last slot, to prevent the top
  16033. // and botton slice connectors from touching each other on either side
  16034. x = options.justify ?
  16035. seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption) :
  16036. series.getX(y === centerY - radius - distanceOption || y === centerY + radius + distanceOption ? naturalY : y, i);
  16037. // Record the placement and visibility
  16038. dataLabel._attr = {
  16039. visibility: visibility,
  16040. align: labelPos[6]
  16041. };
  16042. dataLabel._pos = {
  16043. x: x + options.x +
  16044. ({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0),
  16045. y: y + options.y - 10 // 10 is for the baseline (label vs text)
  16046. };
  16047. dataLabel.connX = x;
  16048. dataLabel.connY = y;
  16049. // Detect overflowing data labels
  16050. if (this.options.size === null) {
  16051. dataLabelWidth = dataLabel.width;
  16052. // Overflow left
  16053. if (x - dataLabelWidth < connectorPadding) {
  16054. overflow[3] = mathMax(mathRound(dataLabelWidth - x + connectorPadding), overflow[3]);
  16055. // Overflow right
  16056. } else if (x + dataLabelWidth > plotWidth - connectorPadding) {
  16057. overflow[1] = mathMax(mathRound(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]);
  16058. }
  16059. // Overflow top
  16060. if (y - labelHeight / 2 < 0) {
  16061. overflow[0] = mathMax(mathRound(-y + labelHeight / 2), overflow[0]);
  16062. // Overflow left
  16063. } else if (y + labelHeight / 2 > plotHeight) {
  16064. overflow[2] = mathMax(mathRound(y + labelHeight / 2 - plotHeight), overflow[2]);
  16065. }
  16066. }
  16067. } // for each point
  16068. } // for each half
  16069. // Do not apply the final placement and draw the connectors until we have verified
  16070. // that labels are not spilling over.
  16071. if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) {
  16072. // Place the labels in the final position
  16073. this.placeDataLabels();
  16074. // Draw the connectors
  16075. if (outside && connectorWidth) {
  16076. each(this.points, function (point) {
  16077. connector = point.connector;
  16078. labelPos = point.labelPos;
  16079. dataLabel = point.dataLabel;
  16080. if (dataLabel && dataLabel._pos && point.visible) {
  16081. visibility = dataLabel._attr.visibility;
  16082. x = dataLabel.connX;
  16083. y = dataLabel.connY;
  16084. connectorPath = softConnector ? [
  16085. M,
  16086. x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
  16087. 'C',
  16088. x, y, // first break, next to the label
  16089. 2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5],
  16090. labelPos[2], labelPos[3], // second break
  16091. L,
  16092. labelPos[4], labelPos[5] // base
  16093. ] : [
  16094. M,
  16095. x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
  16096. L,
  16097. labelPos[2], labelPos[3], // second break
  16098. L,
  16099. labelPos[4], labelPos[5] // base
  16100. ];
  16101. if (connector) {
  16102. connector.animate({ d: connectorPath });
  16103. connector.attr('visibility', visibility);
  16104. } else {
  16105. point.connector = connector = series.chart.renderer.path(connectorPath).attr({
  16106. 'stroke-width': connectorWidth,
  16107. stroke: options.connectorColor || point.color || '#606060',
  16108. visibility: visibility
  16109. //zIndex: 0 // #2722 (reversed)
  16110. })
  16111. .add(series.dataLabelsGroup);
  16112. }
  16113. } else if (connector) {
  16114. point.connector = connector.destroy();
  16115. }
  16116. });
  16117. }
  16118. }
  16119. };
  16120. /**
  16121. * Perform the final placement of the data labels after we have verified that they
  16122. * fall within the plot area.
  16123. */
  16124. seriesTypes.pie.prototype.placeDataLabels = function () {
  16125. each(this.points, function (point) {
  16126. var dataLabel = point.dataLabel,
  16127. _pos;
  16128. if (dataLabel && point.visible) {
  16129. _pos = dataLabel._pos;
  16130. if (_pos) {
  16131. dataLabel.attr(dataLabel._attr);
  16132. dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos);
  16133. dataLabel.moved = true;
  16134. } else if (dataLabel) {
  16135. dataLabel.attr({ y: -9999 });
  16136. }
  16137. }
  16138. });
  16139. };
  16140. seriesTypes.pie.prototype.alignDataLabel = noop;
  16141. /**
  16142. * Verify whether the data labels are allowed to draw, or we should run more translation and data
  16143. * label positioning to keep them inside the plot area. Returns true when data labels are ready
  16144. * to draw.
  16145. */
  16146. seriesTypes.pie.prototype.verifyDataLabelOverflow = function (overflow) {
  16147. var center = this.center,
  16148. options = this.options,
  16149. centerOption = options.center,
  16150. minSize = options.minSize || 80,
  16151. newSize = minSize,
  16152. ret;
  16153. // Handle horizontal size and center
  16154. if (centerOption[0] !== null) { // Fixed center
  16155. newSize = mathMax(center[2] - mathMax(overflow[1], overflow[3]), minSize);
  16156. } else { // Auto center
  16157. newSize = mathMax(
  16158. center[2] - overflow[1] - overflow[3], // horizontal overflow
  16159. minSize
  16160. );
  16161. center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center
  16162. }
  16163. // Handle vertical size and center
  16164. if (centerOption[1] !== null) { // Fixed center
  16165. newSize = mathMax(mathMin(newSize, center[2] - mathMax(overflow[0], overflow[2])), minSize);
  16166. } else { // Auto center
  16167. newSize = mathMax(
  16168. mathMin(
  16169. newSize,
  16170. center[2] - overflow[0] - overflow[2] // vertical overflow
  16171. ),
  16172. minSize
  16173. );
  16174. center[1] += (overflow[0] - overflow[2]) / 2; // vertical center
  16175. }
  16176. // If the size must be decreased, we need to run translate and drawDataLabels again
  16177. if (newSize < center[2]) {
  16178. center[2] = newSize;
  16179. center[3] = Math.min(relativeLength(options.innerSize || 0, newSize), newSize); // #3632
  16180. this.translate(center);
  16181. if (this.drawDataLabels) {
  16182. this.drawDataLabels();
  16183. }
  16184. // Else, return true to indicate that the pie and its labels is within the plot area
  16185. } else {
  16186. ret = true;
  16187. }
  16188. return ret;
  16189. };
  16190. }
  16191. if (seriesTypes.column) {
  16192. /**
  16193. * Override the basic data label alignment by adjusting for the position of the column
  16194. */
  16195. seriesTypes.column.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) {
  16196. var inverted = this.chart.inverted,
  16197. series = point.series,
  16198. dlBox = point.dlBox || point.shapeArgs, // data label box for alignment
  16199. below = pick(point.below, point.plotY > pick(this.translatedThreshold, series.yAxis.len)), // point.below is used in range series
  16200. inside = pick(options.inside, !!this.options.stacking), // draw it inside the box?
  16201. overshoot;
  16202. // Align to the column itself, or the top of it
  16203. if (dlBox) { // Area range uses this method but not alignTo
  16204. alignTo = merge(dlBox);
  16205. if (alignTo.y < 0) {
  16206. alignTo.height += alignTo.y;
  16207. alignTo.y = 0;
  16208. }
  16209. overshoot = alignTo.y + alignTo.height - series.yAxis.len;
  16210. if (overshoot > 0) {
  16211. alignTo.height -= overshoot;
  16212. }
  16213. if (inverted) {
  16214. alignTo = {
  16215. x: series.yAxis.len - alignTo.y - alignTo.height,
  16216. y: series.xAxis.len - alignTo.x - alignTo.width,
  16217. width: alignTo.height,
  16218. height: alignTo.width
  16219. };
  16220. }
  16221. // Compute the alignment box
  16222. if (!inside) {
  16223. if (inverted) {
  16224. alignTo.x += below ? 0 : alignTo.width;
  16225. alignTo.width = 0;
  16226. } else {
  16227. alignTo.y += below ? alignTo.height : 0;
  16228. alignTo.height = 0;
  16229. }
  16230. }
  16231. }
  16232. // When alignment is undefined (typically columns and bars), display the individual
  16233. // point below or above the point depending on the threshold
  16234. options.align = pick(
  16235. options.align,
  16236. !inverted || inside ? 'center' : below ? 'right' : 'left'
  16237. );
  16238. options.verticalAlign = pick(
  16239. options.verticalAlign,
  16240. inverted || inside ? 'middle' : below ? 'top' : 'bottom'
  16241. );
  16242. // Call the parent method
  16243. Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew);
  16244. };
  16245. }
  16246. /**
  16247. * Highcharts module to hide overlapping data labels. This module is included in Highcharts.
  16248. */
  16249. (function (H) {
  16250. var Chart = H.Chart,
  16251. each = H.each,
  16252. pick = H.pick,
  16253. addEvent = H.addEvent;
  16254. // Collect potensial overlapping data labels. Stack labels probably don't need to be
  16255. // considered because they are usually accompanied by data labels that lie inside the columns.
  16256. Chart.prototype.callbacks.push(function (chart) {
  16257. function collectAndHide() {
  16258. var labels = [];
  16259. each(chart.series, function (series) {
  16260. var dlOptions = series.options.dataLabels,
  16261. collections = series.dataLabelCollections || ['dataLabel']; // Range series have two collections
  16262. if ((dlOptions.enabled || series._hasPointLabels) && !dlOptions.allowOverlap && series.visible) { // #3866
  16263. each(collections, function (coll) {
  16264. each(series.points, function (point) {
  16265. if (point[coll]) {
  16266. point[coll].labelrank = pick(point.labelrank, point.shapeArgs && point.shapeArgs.height); // #4118
  16267. labels.push(point[coll]);
  16268. }
  16269. });
  16270. });
  16271. }
  16272. });
  16273. chart.hideOverlappingLabels(labels);
  16274. }
  16275. // Do it now ...
  16276. collectAndHide();
  16277. // ... and after each chart redraw
  16278. addEvent(chart, 'redraw', collectAndHide);
  16279. });
  16280. /**
  16281. * Hide overlapping labels. Labels are moved and faded in and out on zoom to provide a smooth
  16282. * visual imression.
  16283. */
  16284. Chart.prototype.hideOverlappingLabels = function (labels) {
  16285. var len = labels.length,
  16286. label,
  16287. i,
  16288. j,
  16289. label1,
  16290. label2,
  16291. isIntersecting,
  16292. pos1,
  16293. pos2,
  16294. parent1,
  16295. parent2,
  16296. padding,
  16297. intersectRect = function (x1, y1, w1, h1, x2, y2, w2, h2) {
  16298. return !(
  16299. x2 > x1 + w1 ||
  16300. x2 + w2 < x1 ||
  16301. y2 > y1 + h1 ||
  16302. y2 + h2 < y1
  16303. );
  16304. };
  16305. // Mark with initial opacity
  16306. for (i = 0; i < len; i++) {
  16307. label = labels[i];
  16308. if (label) {
  16309. label.oldOpacity = label.opacity;
  16310. label.newOpacity = 1;
  16311. }
  16312. }
  16313. // Prevent a situation in a gradually rising slope, that each label
  16314. // will hide the previous one because the previous one always has
  16315. // lower rank.
  16316. labels.sort(function (a, b) {
  16317. return (b.labelrank || 0) - (a.labelrank || 0);
  16318. });
  16319. // Detect overlapping labels
  16320. for (i = 0; i < len; i++) {
  16321. label1 = labels[i];
  16322. for (j = i + 1; j < len; ++j) {
  16323. label2 = labels[j];
  16324. if (label1 && label2 && label1.placed && label2.placed && label1.newOpacity !== 0 && label2.newOpacity !== 0) {
  16325. pos1 = label1.alignAttr;
  16326. pos2 = label2.alignAttr;
  16327. parent1 = label1.parentGroup; // Different panes have different positions
  16328. parent2 = label2.parentGroup;
  16329. padding = 2 * (label1.box ? 0 : label1.padding); // Substract the padding if no background or border (#4333)
  16330. isIntersecting = intersectRect(
  16331. pos1.x + parent1.translateX,
  16332. pos1.y + parent1.translateY,
  16333. label1.width - padding,
  16334. label1.height - padding,
  16335. pos2.x + parent2.translateX,
  16336. pos2.y + parent2.translateY,
  16337. label2.width - padding,
  16338. label2.height - padding
  16339. );
  16340. if (isIntersecting) {
  16341. (label1.labelrank < label2.labelrank ? label1 : label2).newOpacity = 0;
  16342. }
  16343. }
  16344. }
  16345. }
  16346. // Hide or show
  16347. each(labels, function (label) {
  16348. var complete,
  16349. newOpacity;
  16350. if (label) {
  16351. newOpacity = label.newOpacity;
  16352. if (label.oldOpacity !== newOpacity && label.placed) {
  16353. // Make sure the label is completely hidden to avoid catching clicks (#4362)
  16354. if (newOpacity) {
  16355. label.show(true);
  16356. } else {
  16357. complete = function () {
  16358. label.hide();
  16359. };
  16360. }
  16361. // Animate or set the opacity
  16362. label.alignAttr.opacity = newOpacity;
  16363. label[label.isOld ? 'animate' : 'attr'](label.alignAttr, null, complete);
  16364. }
  16365. label.isOld = true;
  16366. }
  16367. });
  16368. };
  16369. }(Highcharts));
  16370. /**
  16371. * TrackerMixin for points and graphs
  16372. */
  16373. var TrackerMixin = Highcharts.TrackerMixin = {
  16374. drawTrackerPoint: function () {
  16375. var series = this,
  16376. chart = series.chart,
  16377. pointer = chart.pointer,
  16378. cursor = series.options.cursor,
  16379. css = cursor && { cursor: cursor },
  16380. onMouseOver = function (e) {
  16381. var target = e.target,
  16382. point;
  16383. while (target && !point) {
  16384. point = target.point;
  16385. target = target.parentNode;
  16386. }
  16387. if (point !== UNDEFINED && point !== chart.hoverPoint) { // undefined on graph in scatterchart
  16388. point.onMouseOver(e);
  16389. }
  16390. };
  16391. // Add reference to the point
  16392. each(series.points, function (point) {
  16393. if (point.graphic) {
  16394. point.graphic.element.point = point;
  16395. }
  16396. if (point.dataLabel) {
  16397. point.dataLabel.element.point = point;
  16398. }
  16399. });
  16400. // Add the event listeners, we need to do this only once
  16401. if (!series._hasTracking) {
  16402. each(series.trackerGroups, function (key) {
  16403. if (series[key]) { // we don't always have dataLabelsGroup
  16404. series[key]
  16405. .addClass(PREFIX + 'tracker')
  16406. .on('mouseover', onMouseOver)
  16407. .on('mouseout', function (e) {
  16408. pointer.onTrackerMouseOut(e);
  16409. })
  16410. .css(css);
  16411. if (hasTouch) {
  16412. series[key].on('touchstart', onMouseOver);
  16413. }
  16414. }
  16415. });
  16416. series._hasTracking = true;
  16417. }
  16418. },
  16419. /**
  16420. * Draw the tracker object that sits above all data labels and markers to
  16421. * track mouse events on the graph or points. For the line type charts
  16422. * the tracker uses the same graphPath, but with a greater stroke width
  16423. * for better control.
  16424. */
  16425. drawTrackerGraph: function () {
  16426. var series = this,
  16427. options = series.options,
  16428. trackByArea = options.trackByArea,
  16429. trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath),
  16430. trackerPathLength = trackerPath.length,
  16431. chart = series.chart,
  16432. pointer = chart.pointer,
  16433. renderer = chart.renderer,
  16434. snap = chart.options.tooltip.snap,
  16435. tracker = series.tracker,
  16436. cursor = options.cursor,
  16437. css = cursor && { cursor: cursor },
  16438. i,
  16439. onMouseOver = function () {
  16440. if (chart.hoverSeries !== series) {
  16441. series.onMouseOver();
  16442. }
  16443. },
  16444. /*
  16445. * Empirical lowest possible opacities for TRACKER_FILL for an element to stay invisible but clickable
  16446. * IE6: 0.002
  16447. * IE7: 0.002
  16448. * IE8: 0.002
  16449. * IE9: 0.00000000001 (unlimited)
  16450. * IE10: 0.0001 (exporting only)
  16451. * FF: 0.00000000001 (unlimited)
  16452. * Chrome: 0.000001
  16453. * Safari: 0.000001
  16454. * Opera: 0.00000000001 (unlimited)
  16455. */
  16456. TRACKER_FILL = 'rgba(192,192,192,' + (hasSVG ? 0.0001 : 0.002) + ')';
  16457. // Extend end points. A better way would be to use round linecaps,
  16458. // but those are not clickable in VML.
  16459. if (trackerPathLength && !trackByArea) {
  16460. i = trackerPathLength + 1;
  16461. while (i--) {
  16462. if (trackerPath[i] === M) { // extend left side
  16463. trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L);
  16464. }
  16465. if ((i && trackerPath[i] === M) || i === trackerPathLength) { // extend right side
  16466. trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]);
  16467. }
  16468. }
  16469. }
  16470. // handle single points
  16471. /*for (i = 0; i < singlePoints.length; i++) {
  16472. singlePoint = singlePoints[i];
  16473. trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY,
  16474. L, singlePoint.plotX + snap, singlePoint.plotY);
  16475. }*/
  16476. // draw the tracker
  16477. if (tracker) {
  16478. tracker.attr({ d: trackerPath });
  16479. } else { // create
  16480. series.tracker = renderer.path(trackerPath)
  16481. .attr({
  16482. 'stroke-linejoin': 'round', // #1225
  16483. visibility: series.visible ? VISIBLE : HIDDEN,
  16484. stroke: TRACKER_FILL,
  16485. fill: trackByArea ? TRACKER_FILL : NONE,
  16486. 'stroke-width': options.lineWidth + (trackByArea ? 0 : 2 * snap),
  16487. zIndex: 2
  16488. })
  16489. .add(series.group);
  16490. // The tracker is added to the series group, which is clipped, but is covered
  16491. // by the marker group. So the marker group also needs to capture events.
  16492. each([series.tracker, series.markerGroup], function (tracker) {
  16493. tracker.addClass(PREFIX + 'tracker')
  16494. .on('mouseover', onMouseOver)
  16495. .on('mouseout', function (e) {
  16496. pointer.onTrackerMouseOut(e);
  16497. })
  16498. .css(css);
  16499. if (hasTouch) {
  16500. tracker.on('touchstart', onMouseOver);
  16501. }
  16502. });
  16503. }
  16504. }
  16505. };
  16506. /* End TrackerMixin */
  16507. /**
  16508. * Add tracking event listener to the series group, so the point graphics
  16509. * themselves act as trackers
  16510. */
  16511. if (seriesTypes.column) {
  16512. ColumnSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
  16513. }
  16514. if (seriesTypes.pie) {
  16515. seriesTypes.pie.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
  16516. }
  16517. if (seriesTypes.scatter) {
  16518. ScatterSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
  16519. }
  16520. /*
  16521. * Extend Legend for item events
  16522. */
  16523. extend(Legend.prototype, {
  16524. setItemEvents: function (item, legendItem, useHTML, itemStyle, itemHiddenStyle) {
  16525. var legend = this;
  16526. // Set the events on the item group, or in case of useHTML, the item itself (#1249)
  16527. (useHTML ? legendItem : item.legendGroup).on('mouseover', function () {
  16528. item.setState(HOVER_STATE);
  16529. legendItem.css(legend.options.itemHoverStyle);
  16530. })
  16531. .on('mouseout', function () {
  16532. legendItem.css(item.visible ? itemStyle : itemHiddenStyle);
  16533. item.setState();
  16534. })
  16535. .on('click', function (event) {
  16536. var strLegendItemClick = 'legendItemClick',
  16537. fnLegendItemClick = function () {
  16538. if (item.setVisible) {
  16539. item.setVisible();
  16540. }
  16541. };
  16542. // Pass over the click/touch event. #4.
  16543. event = {
  16544. browserEvent: event
  16545. };
  16546. // click the name or symbol
  16547. if (item.firePointEvent) { // point
  16548. item.firePointEvent(strLegendItemClick, event, fnLegendItemClick);
  16549. } else {
  16550. fireEvent(item, strLegendItemClick, event, fnLegendItemClick);
  16551. }
  16552. });
  16553. },
  16554. createCheckboxForItem: function (item) {
  16555. var legend = this;
  16556. item.checkbox = createElement('input', {
  16557. type: 'checkbox',
  16558. checked: item.selected,
  16559. defaultChecked: item.selected // required by IE7
  16560. }, legend.options.itemCheckboxStyle, legend.chart.container);
  16561. addEvent(item.checkbox, 'click', function (event) {
  16562. var target = event.target;
  16563. fireEvent(
  16564. item.series || item,
  16565. 'checkboxClick',
  16566. { // #3712
  16567. checked: target.checked,
  16568. item: item
  16569. },
  16570. function () {
  16571. item.select();
  16572. }
  16573. );
  16574. });
  16575. }
  16576. });
  16577. /*
  16578. * Add pointer cursor to legend itemstyle in defaultOptions
  16579. */
  16580. defaultOptions.legend.itemStyle.cursor = 'pointer';
  16581. /*
  16582. * Extend the Chart object with interaction
  16583. */
  16584. extend(Chart.prototype, {
  16585. /**
  16586. * Display the zoom button
  16587. */
  16588. showResetZoom: function () {
  16589. var chart = this,
  16590. lang = defaultOptions.lang,
  16591. btnOptions = chart.options.chart.resetZoomButton,
  16592. theme = btnOptions.theme,
  16593. states = theme.states,
  16594. alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox';
  16595. function zoomOut() {
  16596. chart.zoomOut();
  16597. }
  16598. this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, zoomOut, theme, states && states.hover)
  16599. .attr({
  16600. align: btnOptions.position.align,
  16601. title: lang.resetZoomTitle
  16602. })
  16603. .add()
  16604. .align(btnOptions.position, false, alignTo);
  16605. },
  16606. /**
  16607. * Zoom out to 1:1
  16608. */
  16609. zoomOut: function () {
  16610. var chart = this;
  16611. fireEvent(chart, 'selection', { resetSelection: true }, function () {
  16612. chart.zoom();
  16613. });
  16614. },
  16615. /**
  16616. * Zoom into a given portion of the chart given by axis coordinates
  16617. * @param {Object} event
  16618. */
  16619. zoom: function (event) {
  16620. var chart = this,
  16621. hasZoomed,
  16622. pointer = chart.pointer,
  16623. displayButton = false,
  16624. resetZoomButton;
  16625. // If zoom is called with no arguments, reset the axes
  16626. if (!event || event.resetSelection) {
  16627. each(chart.axes, function (axis) {
  16628. hasZoomed = axis.zoom();
  16629. });
  16630. } else { // else, zoom in on all axes
  16631. each(event.xAxis.concat(event.yAxis), function (axisData) {
  16632. var axis = axisData.axis,
  16633. isXAxis = axis.isXAxis;
  16634. // don't zoom more than minRange
  16635. if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) {
  16636. hasZoomed = axis.zoom(axisData.min, axisData.max);
  16637. if (axis.displayBtn) {
  16638. displayButton = true;
  16639. }
  16640. }
  16641. });
  16642. }
  16643. // Show or hide the Reset zoom button
  16644. resetZoomButton = chart.resetZoomButton;
  16645. if (displayButton && !resetZoomButton) {
  16646. chart.showResetZoom();
  16647. } else if (!displayButton && isObject(resetZoomButton)) {
  16648. chart.resetZoomButton = resetZoomButton.destroy();
  16649. }
  16650. // Redraw
  16651. if (hasZoomed) {
  16652. chart.redraw(
  16653. pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation
  16654. );
  16655. }
  16656. },
  16657. /**
  16658. * Pan the chart by dragging the mouse across the pane. This function is called
  16659. * on mouse move, and the distance to pan is computed from chartX compared to
  16660. * the first chartX position in the dragging operation.
  16661. */
  16662. pan: function (e, panning) {
  16663. var chart = this,
  16664. hoverPoints = chart.hoverPoints,
  16665. doRedraw;
  16666. // remove active points for shared tooltip
  16667. if (hoverPoints) {
  16668. each(hoverPoints, function (point) {
  16669. point.setState();
  16670. });
  16671. }
  16672. each(panning === 'xy' ? [1, 0] : [1], function (isX) { // xy is used in maps
  16673. var axis = chart[isX ? 'xAxis' : 'yAxis'][0],
  16674. horiz = axis.horiz,
  16675. mousePos = e[horiz ? 'chartX' : 'chartY'],
  16676. mouseDown = horiz ? 'mouseDownX' : 'mouseDownY',
  16677. startPos = chart[mouseDown],
  16678. halfPointRange = (axis.pointRange || 0) / 2,
  16679. extremes = axis.getExtremes(),
  16680. newMin = axis.toValue(startPos - mousePos, true) + halfPointRange,
  16681. newMax = axis.toValue(startPos + axis.len - mousePos, true) - halfPointRange,
  16682. goingLeft = startPos > mousePos; // #3613
  16683. if (axis.series.length &&
  16684. (goingLeft || newMin > mathMin(extremes.dataMin, extremes.min)) &&
  16685. (!goingLeft || newMax < mathMax(extremes.dataMax, extremes.max))) {
  16686. axis.setExtremes(newMin, newMax, false, false, { trigger: 'pan' });
  16687. doRedraw = true;
  16688. }
  16689. chart[mouseDown] = mousePos; // set new reference for next run
  16690. });
  16691. if (doRedraw) {
  16692. chart.redraw(false);
  16693. }
  16694. css(chart.container, { cursor: 'move' });
  16695. }
  16696. });
  16697. /*
  16698. * Extend the Point object with interaction
  16699. */
  16700. extend(Point.prototype, {
  16701. /**
  16702. * Toggle the selection status of a point
  16703. * @param {Boolean} selected Whether to select or unselect the point.
  16704. * @param {Boolean} accumulate Whether to add to the previous selection. By default,
  16705. * this happens if the control key (Cmd on Mac) was pressed during clicking.
  16706. */
  16707. select: function (selected, accumulate) {
  16708. var point = this,
  16709. series = point.series,
  16710. chart = series.chart;
  16711. selected = pick(selected, !point.selected);
  16712. // fire the event with the default handler
  16713. point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () {
  16714. point.selected = point.options.selected = selected;
  16715. series.options.data[inArray(point, series.data)] = point.options;
  16716. point.setState(selected && SELECT_STATE);
  16717. // unselect all other points unless Ctrl or Cmd + click
  16718. if (!accumulate) {
  16719. each(chart.getSelectedPoints(), function (loopPoint) {
  16720. if (loopPoint.selected && loopPoint !== point) {
  16721. loopPoint.selected = loopPoint.options.selected = false;
  16722. series.options.data[inArray(loopPoint, series.data)] = loopPoint.options;
  16723. loopPoint.setState(NORMAL_STATE);
  16724. loopPoint.firePointEvent('unselect');
  16725. }
  16726. });
  16727. }
  16728. });
  16729. },
  16730. /**
  16731. * Runs on mouse over the point
  16732. *
  16733. * @param {Object} e The event arguments
  16734. * @param {Boolean} byProximity Falsy for kd points that are closest to the mouse, or to
  16735. * actually hovered points. True for other points in shared tooltip.
  16736. */
  16737. onMouseOver: function (e, byProximity) {
  16738. var point = this,
  16739. series = point.series,
  16740. chart = series.chart,
  16741. tooltip = chart.tooltip,
  16742. hoverPoint = chart.hoverPoint;
  16743. if (chart.hoverSeries !== series) {
  16744. series.onMouseOver();
  16745. }
  16746. // set normal state to previous series
  16747. if (hoverPoint && hoverPoint !== point) {
  16748. hoverPoint.onMouseOut();
  16749. }
  16750. if (point.series) { // It may have been destroyed, #4130
  16751. // trigger the event
  16752. point.firePointEvent('mouseOver');
  16753. // update the tooltip
  16754. if (tooltip && (!tooltip.shared || series.noSharedTooltip)) {
  16755. tooltip.refresh(point, e);
  16756. }
  16757. // hover this
  16758. point.setState(HOVER_STATE);
  16759. if (!byProximity) {
  16760. chart.hoverPoint = point;
  16761. }
  16762. }
  16763. },
  16764. /**
  16765. * Runs on mouse out from the point
  16766. */
  16767. onMouseOut: function () {
  16768. var chart = this.series.chart,
  16769. hoverPoints = chart.hoverPoints;
  16770. this.firePointEvent('mouseOut');
  16771. if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887, #2240
  16772. this.setState();
  16773. chart.hoverPoint = null;
  16774. }
  16775. },
  16776. /**
  16777. * Import events from the series' and point's options. Only do it on
  16778. * demand, to save processing time on hovering.
  16779. */
  16780. importEvents: function () {
  16781. if (!this.hasImportedEvents) {
  16782. var point = this,
  16783. options = merge(point.series.options.point, point.options),
  16784. events = options.events,
  16785. eventType;
  16786. point.events = events;
  16787. for (eventType in events) {
  16788. addEvent(point, eventType, events[eventType]);
  16789. }
  16790. this.hasImportedEvents = true;
  16791. }
  16792. },
  16793. /**
  16794. * Set the point's state
  16795. * @param {String} state
  16796. */
  16797. setState: function (state, move) {
  16798. var point = this,
  16799. plotX = mathFloor(point.plotX), // #4586
  16800. plotY = point.plotY,
  16801. series = point.series,
  16802. stateOptions = series.options.states,
  16803. markerOptions = defaultPlotOptions[series.type].marker && series.options.marker,
  16804. normalDisabled = markerOptions && !markerOptions.enabled,
  16805. markerStateOptions = markerOptions && markerOptions.states[state],
  16806. stateDisabled = markerStateOptions && markerStateOptions.enabled === false,
  16807. stateMarkerGraphic = series.stateMarkerGraphic,
  16808. pointMarker = point.marker || {},
  16809. chart = series.chart,
  16810. radius,
  16811. halo = series.halo,
  16812. haloOptions,
  16813. newSymbol,
  16814. pointAttr;
  16815. state = state || NORMAL_STATE; // empty string
  16816. pointAttr = point.pointAttr[state] || series.pointAttr[state];
  16817. if (
  16818. // already has this state
  16819. (state === point.state && !move) ||
  16820. // selected points don't respond to hover
  16821. (point.selected && state !== SELECT_STATE) ||
  16822. // series' state options is disabled
  16823. (stateOptions[state] && stateOptions[state].enabled === false) ||
  16824. // general point marker's state options is disabled
  16825. (state && (stateDisabled || (normalDisabled && markerStateOptions.enabled === false))) ||
  16826. // individual point marker's state options is disabled
  16827. (state && pointMarker.states && pointMarker.states[state] && pointMarker.states[state].enabled === false) // #1610
  16828. ) {
  16829. return;
  16830. }
  16831. // apply hover styles to the existing point
  16832. if (point.graphic) {
  16833. radius = markerOptions && point.graphic.symbolName && pointAttr.r;
  16834. point.graphic.attr(merge(
  16835. pointAttr,
  16836. radius ? { // new symbol attributes (#507, #612)
  16837. x: plotX - radius,
  16838. y: plotY - radius,
  16839. width: 2 * radius,
  16840. height: 2 * radius
  16841. } : {}
  16842. ));
  16843. // Zooming in from a range with no markers to a range with markers
  16844. if (stateMarkerGraphic) {
  16845. stateMarkerGraphic.hide();
  16846. }
  16847. } else {
  16848. // if a graphic is not applied to each point in the normal state, create a shared
  16849. // graphic for the hover state
  16850. if (state && markerStateOptions) {
  16851. radius = markerStateOptions.radius;
  16852. newSymbol = pointMarker.symbol || series.symbol;
  16853. // If the point has another symbol than the previous one, throw away the
  16854. // state marker graphic and force a new one (#1459)
  16855. if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) {
  16856. stateMarkerGraphic = stateMarkerGraphic.destroy();
  16857. }
  16858. // Add a new state marker graphic
  16859. if (!stateMarkerGraphic) {
  16860. if (newSymbol) {
  16861. series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol(
  16862. newSymbol,
  16863. plotX - radius,
  16864. plotY - radius,
  16865. 2 * radius,
  16866. 2 * radius
  16867. )
  16868. .attr(pointAttr)
  16869. .add(series.markerGroup);
  16870. stateMarkerGraphic.currentSymbol = newSymbol;
  16871. }
  16872. // Move the existing graphic
  16873. } else {
  16874. stateMarkerGraphic[move ? 'animate' : 'attr']({ // #1054
  16875. x: plotX - radius,
  16876. y: plotY - radius
  16877. });
  16878. }
  16879. }
  16880. if (stateMarkerGraphic) {
  16881. stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY, chart.inverted) ? 'show' : 'hide'](); // #2450
  16882. stateMarkerGraphic.element.point = point; // #4310
  16883. }
  16884. }
  16885. // Show me your halo
  16886. haloOptions = stateOptions[state] && stateOptions[state].halo;
  16887. if (haloOptions && haloOptions.size) {
  16888. if (!halo) {
  16889. series.halo = halo = chart.renderer.path()
  16890. .add(chart.seriesGroup);
  16891. }
  16892. halo.attr(extend({
  16893. 'fill': point.color || series.color,
  16894. 'fill-opacity': haloOptions.opacity,
  16895. 'zIndex': -1 // #4929, IE8 added halo above everything
  16896. },
  16897. haloOptions.attributes))[move ? 'animate' : 'attr']({
  16898. d: point.haloPath(haloOptions.size)
  16899. });
  16900. } else if (halo) {
  16901. halo.attr({ d: [] });
  16902. }
  16903. point.state = state;
  16904. },
  16905. /**
  16906. * Get the circular path definition for the halo
  16907. * @param {Number} size The radius of the circular halo
  16908. * @returns {Array} The path definition
  16909. */
  16910. haloPath: function (size) {
  16911. var series = this.series,
  16912. chart = series.chart,
  16913. plotBox = series.getPlotBox(),
  16914. inverted = chart.inverted,
  16915. plotX = Math.floor(this.plotX);
  16916. return chart.renderer.symbols.circle(
  16917. plotBox.translateX + (inverted ? series.yAxis.len - this.plotY : plotX) - size,
  16918. plotBox.translateY + (inverted ? series.xAxis.len - plotX : this.plotY) - size,
  16919. size * 2,
  16920. size * 2
  16921. );
  16922. }
  16923. });
  16924. /*
  16925. * Extend the Series object with interaction
  16926. */
  16927. extend(Series.prototype, {
  16928. /**
  16929. * Series mouse over handler
  16930. */
  16931. onMouseOver: function () {
  16932. var series = this,
  16933. chart = series.chart,
  16934. hoverSeries = chart.hoverSeries;
  16935. // set normal state to previous series
  16936. if (hoverSeries && hoverSeries !== series) {
  16937. hoverSeries.onMouseOut();
  16938. }
  16939. // trigger the event, but to save processing time,
  16940. // only if defined
  16941. if (series.options.events.mouseOver) {
  16942. fireEvent(series, 'mouseOver');
  16943. }
  16944. // hover this
  16945. series.setState(HOVER_STATE);
  16946. chart.hoverSeries = series;
  16947. },
  16948. /**
  16949. * Series mouse out handler
  16950. */
  16951. onMouseOut: function () {
  16952. // trigger the event only if listeners exist
  16953. var series = this,
  16954. options = series.options,
  16955. chart = series.chart,
  16956. tooltip = chart.tooltip,
  16957. hoverPoint = chart.hoverPoint;
  16958. chart.hoverSeries = null; // #182, set to null before the mouseOut event fires
  16959. // trigger mouse out on the point, which must be in this series
  16960. if (hoverPoint) {
  16961. hoverPoint.onMouseOut();
  16962. }
  16963. // fire the mouse out event
  16964. if (series && options.events.mouseOut) {
  16965. fireEvent(series, 'mouseOut');
  16966. }
  16967. // hide the tooltip
  16968. if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) {
  16969. tooltip.hide();
  16970. }
  16971. // set normal state
  16972. series.setState();
  16973. },
  16974. /**
  16975. * Set the state of the graph
  16976. */
  16977. setState: function (state) {
  16978. var series = this,
  16979. options = series.options,
  16980. graph = series.graph,
  16981. stateOptions = options.states,
  16982. lineWidth = options.lineWidth,
  16983. attribs,
  16984. i = 0;
  16985. state = state || NORMAL_STATE;
  16986. if (series.state !== state) {
  16987. series.state = state;
  16988. if (stateOptions[state] && stateOptions[state].enabled === false) {
  16989. return;
  16990. }
  16991. if (state) {
  16992. lineWidth = stateOptions[state].lineWidth || lineWidth + (stateOptions[state].lineWidthPlus || 0); // #4035
  16993. }
  16994. if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML
  16995. attribs = {
  16996. 'stroke-width': lineWidth
  16997. };
  16998. // use attr because animate will cause any other animation on the graph to stop
  16999. graph.attr(attribs);
  17000. while (series['zoneGraph' + i]) {
  17001. series['zoneGraph' + i].attr(attribs);
  17002. i = i + 1;
  17003. }
  17004. }
  17005. }
  17006. },
  17007. /**
  17008. * Set the visibility of the graph
  17009. *
  17010. * @param vis {Boolean} True to show the series, false to hide. If UNDEFINED,
  17011. * the visibility is toggled.
  17012. */
  17013. setVisible: function (vis, redraw) {
  17014. var series = this,
  17015. chart = series.chart,
  17016. legendItem = series.legendItem,
  17017. showOrHide,
  17018. ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries,
  17019. oldVisibility = series.visible;
  17020. // if called without an argument, toggle visibility
  17021. series.visible = vis = series.options.visible = series.userOptions.visible = vis === undefined ? !oldVisibility : vis; // #5618
  17022. showOrHide = vis ? 'show' : 'hide';
  17023. // show or hide elements
  17024. each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) {
  17025. if (series[key]) {
  17026. series[key][showOrHide]();
  17027. }
  17028. });
  17029. // hide tooltip (#1361)
  17030. if (chart.hoverSeries === series || (chart.hoverPoint && chart.hoverPoint.series) === series) {
  17031. series.onMouseOut();
  17032. }
  17033. if (legendItem) {
  17034. chart.legend.colorizeItem(series, vis);
  17035. }
  17036. // rescale or adapt to resized chart
  17037. series.isDirty = true;
  17038. // in a stack, all other series are affected
  17039. if (series.options.stacking) {
  17040. each(chart.series, function (otherSeries) {
  17041. if (otherSeries.options.stacking && otherSeries.visible) {
  17042. otherSeries.isDirty = true;
  17043. }
  17044. });
  17045. }
  17046. // show or hide linked series
  17047. each(series.linkedSeries, function (otherSeries) {
  17048. otherSeries.setVisible(vis, false);
  17049. });
  17050. if (ignoreHiddenSeries) {
  17051. chart.isDirtyBox = true;
  17052. }
  17053. if (redraw !== false) {
  17054. chart.redraw();
  17055. }
  17056. fireEvent(series, showOrHide);
  17057. },
  17058. /**
  17059. * Show the graph
  17060. */
  17061. show: function () {
  17062. this.setVisible(true);
  17063. },
  17064. /**
  17065. * Hide the graph
  17066. */
  17067. hide: function () {
  17068. this.setVisible(false);
  17069. },
  17070. /**
  17071. * Set the selected state of the graph
  17072. *
  17073. * @param selected {Boolean} True to select the series, false to unselect. If
  17074. * UNDEFINED, the selection state is toggled.
  17075. */
  17076. select: function (selected) {
  17077. var series = this;
  17078. // if called without an argument, toggle
  17079. series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected;
  17080. if (series.checkbox) {
  17081. series.checkbox.checked = selected;
  17082. }
  17083. fireEvent(series, selected ? 'select' : 'unselect');
  17084. },
  17085. drawTracker: TrackerMixin.drawTrackerGraph
  17086. });
  17087. // global variables
  17088. extend(Highcharts, {
  17089. // Constructors
  17090. Color: Color,
  17091. Point: Point,
  17092. Tick: Tick,
  17093. Renderer: Renderer,
  17094. SVGElement: SVGElement,
  17095. SVGRenderer: SVGRenderer,
  17096. // Various
  17097. arrayMin: arrayMin,
  17098. arrayMax: arrayMax,
  17099. charts: charts,
  17100. correctFloat: correctFloat,
  17101. dateFormat: dateFormat,
  17102. error: error,
  17103. format: format,
  17104. pathAnim: pathAnim,
  17105. getOptions: getOptions,
  17106. hasBidiBug: hasBidiBug,
  17107. isTouchDevice: isTouchDevice,
  17108. setOptions: setOptions,
  17109. addEvent: addEvent,
  17110. removeEvent: removeEvent,
  17111. createElement: createElement,
  17112. discardElement: discardElement,
  17113. css: css,
  17114. each: each,
  17115. map: map,
  17116. merge: merge,
  17117. splat: splat,
  17118. stableSort: stableSort,
  17119. extendClass: extendClass,
  17120. pInt: pInt,
  17121. svg: hasSVG,
  17122. canvas: useCanVG,
  17123. vml: !hasSVG && !useCanVG,
  17124. product: PRODUCT,
  17125. version: VERSION
  17126. });
  17127. return Highcharts;
  17128. }));