highcharts.src.js 434 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974
  1. // ==ClosureCompiler==
  2. // @compilation_level SIMPLE_OPTIMIZATIONS
  3. /**
  4. * @license Highcharts JS v3.0.6 (2013-10-04)
  5. *
  6. * (c) 2009-2013 Torstein Hønsi
  7. *
  8. * License: www.highcharts.com/license
  9. */
  10. // JSLint options:
  11. /*global Highcharts, document, window, navigator, setInterval, clearInterval, clearTimeout, setTimeout, location, jQuery, $, console, each, grep */
  12. (function () {
  13. // encapsulated variables
  14. var UNDEFINED,
  15. doc = document,
  16. win = window,
  17. math = Math,
  18. mathRound = math.round,
  19. mathFloor = math.floor,
  20. mathCeil = math.ceil,
  21. mathMax = math.max,
  22. mathMin = math.min,
  23. mathAbs = math.abs,
  24. mathCos = math.cos,
  25. mathSin = math.sin,
  26. mathPI = math.PI,
  27. deg2rad = mathPI * 2 / 360,
  28. // some variables
  29. userAgent = navigator.userAgent,
  30. isOpera = win.opera,
  31. isIE = /msie/i.test(userAgent) && !isOpera,
  32. docMode8 = doc.documentMode === 8,
  33. isWebKit = /AppleWebKit/.test(userAgent),
  34. isFirefox = /Firefox/.test(userAgent),
  35. isTouchDevice = /(Mobile|Android|Windows Phone)/.test(userAgent),
  36. SVG_NS = 'http://www.w3.org/2000/svg',
  37. hasSVG = !!doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect,
  38. hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4, // issue #38
  39. useCanVG = !hasSVG && !isIE && !!doc.createElement('canvas').getContext,
  40. Renderer,
  41. hasTouch = doc.documentElement.ontouchstart !== UNDEFINED,
  42. symbolSizes = {},
  43. idCounter = 0,
  44. garbageBin,
  45. defaultOptions,
  46. dateFormat, // function
  47. globalAnimation,
  48. pathAnim,
  49. timeUnits,
  50. noop = function () {},
  51. charts = [],
  52. PRODUCT = 'Highcharts',
  53. VERSION = '3.0.6',
  54. // some constants for frequently used strings
  55. DIV = 'div',
  56. ABSOLUTE = 'absolute',
  57. RELATIVE = 'relative',
  58. HIDDEN = 'hidden',
  59. PREFIX = 'highcharts-',
  60. VISIBLE = 'visible',
  61. PX = 'px',
  62. NONE = 'none',
  63. M = 'M',
  64. L = 'L',
  65. /*
  66. * Empirical lowest possible opacities for TRACKER_FILL
  67. * IE6: 0.002
  68. * IE7: 0.002
  69. * IE8: 0.002
  70. * IE9: 0.00000000001 (unlimited)
  71. * IE10: 0.0001 (exporting only)
  72. * FF: 0.00000000001 (unlimited)
  73. * Chrome: 0.000001
  74. * Safari: 0.000001
  75. * Opera: 0.00000000001 (unlimited)
  76. */
  77. TRACKER_FILL = 'rgba(192,192,192,' + (hasSVG ? 0.0001 : 0.002) + ')', // invisible but clickable
  78. //TRACKER_FILL = 'rgba(192,192,192,0.5)',
  79. NORMAL_STATE = '',
  80. HOVER_STATE = 'hover',
  81. SELECT_STATE = 'select',
  82. MILLISECOND = 'millisecond',
  83. SECOND = 'second',
  84. MINUTE = 'minute',
  85. HOUR = 'hour',
  86. DAY = 'day',
  87. WEEK = 'week',
  88. MONTH = 'month',
  89. YEAR = 'year',
  90. // constants for attributes
  91. LINEAR_GRADIENT = 'linearGradient',
  92. STOPS = 'stops',
  93. STROKE_WIDTH = 'stroke-width',
  94. // time methods, changed based on whether or not UTC is used
  95. makeTime,
  96. getMinutes,
  97. getHours,
  98. getDay,
  99. getDate,
  100. getMonth,
  101. getFullYear,
  102. setMinutes,
  103. setHours,
  104. setDate,
  105. setMonth,
  106. setFullYear,
  107. // lookup over the types and the associated classes
  108. seriesTypes = {};
  109. // The Highcharts namespace
  110. win.Highcharts = win.Highcharts ? error(16, true) : {};
  111. /**
  112. * Extend an object with the members of another
  113. * @param {Object} a The object to be extended
  114. * @param {Object} b The object to add to the first one
  115. */
  116. function extend(a, b) {
  117. var n;
  118. if (!a) {
  119. a = {};
  120. }
  121. for (n in b) {
  122. a[n] = b[n];
  123. }
  124. return a;
  125. }
  126. /**
  127. * Deep merge two or more objects and return a third object.
  128. * Previously this function redirected to jQuery.extend(true), but this had two limitations.
  129. * First, it deep merged arrays, which lead to workarounds in Highcharts. Second,
  130. * it copied properties from extended prototypes.
  131. */
  132. function merge() {
  133. var i,
  134. len = arguments.length,
  135. ret = {},
  136. doCopy = function (copy, original) {
  137. var value, key;
  138. // An object is replacing a primitive
  139. if (typeof copy !== 'object') {
  140. copy = {};
  141. }
  142. for (key in original) {
  143. if (original.hasOwnProperty(key)) {
  144. value = original[key];
  145. // Copy the contents of objects, but not arrays or DOM nodes
  146. if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]'
  147. && typeof value.nodeType !== 'number') {
  148. copy[key] = doCopy(copy[key] || {}, value);
  149. // Primitives and arrays are copied over directly
  150. } else {
  151. copy[key] = original[key];
  152. }
  153. }
  154. }
  155. return copy;
  156. };
  157. // For each argument, extend the return
  158. for (i = 0; i < len; i++) {
  159. ret = doCopy(ret, arguments[i]);
  160. }
  161. return ret;
  162. }
  163. /**
  164. * Take an array and turn into a hash with even number arguments as keys and odd numbers as
  165. * values. Allows creating constants for commonly used style properties, attributes etc.
  166. * Avoid it in performance critical situations like looping
  167. */
  168. function hash() {
  169. var i = 0,
  170. args = arguments,
  171. length = args.length,
  172. obj = {};
  173. for (; i < length; i++) {
  174. obj[args[i++]] = args[i];
  175. }
  176. return obj;
  177. }
  178. /**
  179. * Shortcut for parseInt
  180. * @param {Object} s
  181. * @param {Number} mag Magnitude
  182. */
  183. function pInt(s, mag) {
  184. return parseInt(s, mag || 10);
  185. }
  186. /**
  187. * Check for string
  188. * @param {Object} s
  189. */
  190. function isString(s) {
  191. return typeof s === 'string';
  192. }
  193. /**
  194. * Check for object
  195. * @param {Object} obj
  196. */
  197. function isObject(obj) {
  198. return typeof obj === 'object';
  199. }
  200. /**
  201. * Check for array
  202. * @param {Object} obj
  203. */
  204. function isArray(obj) {
  205. return Object.prototype.toString.call(obj) === '[object Array]';
  206. }
  207. /**
  208. * Check for number
  209. * @param {Object} n
  210. */
  211. function isNumber(n) {
  212. return typeof n === 'number';
  213. }
  214. function log2lin(num) {
  215. return math.log(num) / math.LN10;
  216. }
  217. function lin2log(num) {
  218. return math.pow(10, num);
  219. }
  220. /**
  221. * Remove last occurence of an item from an array
  222. * @param {Array} arr
  223. * @param {Mixed} item
  224. */
  225. function erase(arr, item) {
  226. var i = arr.length;
  227. while (i--) {
  228. if (arr[i] === item) {
  229. arr.splice(i, 1);
  230. break;
  231. }
  232. }
  233. //return arr;
  234. }
  235. /**
  236. * Returns true if the object is not null or undefined. Like MooTools' $.defined.
  237. * @param {Object} obj
  238. */
  239. function defined(obj) {
  240. return obj !== UNDEFINED && obj !== null;
  241. }
  242. /**
  243. * Set or get an attribute or an object of attributes. Can't use jQuery attr because
  244. * it attempts to set expando properties on the SVG element, which is not allowed.
  245. *
  246. * @param {Object} elem The DOM element to receive the attribute(s)
  247. * @param {String|Object} prop The property or an abject of key-value pairs
  248. * @param {String} value The value if a single property is set
  249. */
  250. function attr(elem, prop, value) {
  251. var key,
  252. setAttribute = 'setAttribute',
  253. ret;
  254. // if the prop is a string
  255. if (isString(prop)) {
  256. // set the value
  257. if (defined(value)) {
  258. elem[setAttribute](prop, value);
  259. // get the value
  260. } else if (elem && elem.getAttribute) { // elem not defined when printing pie demo...
  261. ret = elem.getAttribute(prop);
  262. }
  263. // else if prop is defined, it is a hash of key/value pairs
  264. } else if (defined(prop) && isObject(prop)) {
  265. for (key in prop) {
  266. elem[setAttribute](key, prop[key]);
  267. }
  268. }
  269. return ret;
  270. }
  271. /**
  272. * Check if an element is an array, and if not, make it into an array. Like
  273. * MooTools' $.splat.
  274. */
  275. function splat(obj) {
  276. return isArray(obj) ? obj : [obj];
  277. }
  278. /**
  279. * Return the first value that is defined. Like MooTools' $.pick.
  280. */
  281. function pick() {
  282. var args = arguments,
  283. i,
  284. arg,
  285. length = args.length;
  286. for (i = 0; i < length; i++) {
  287. arg = args[i];
  288. if (typeof arg !== 'undefined' && arg !== null) {
  289. return arg;
  290. }
  291. }
  292. }
  293. /**
  294. * Set CSS on a given element
  295. * @param {Object} el
  296. * @param {Object} styles Style object with camel case property names
  297. */
  298. function css(el, styles) {
  299. if (isIE) {
  300. if (styles && styles.opacity !== UNDEFINED) {
  301. styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')';
  302. }
  303. }
  304. extend(el.style, styles);
  305. }
  306. /**
  307. * Utility function to create element with attributes and styles
  308. * @param {Object} tag
  309. * @param {Object} attribs
  310. * @param {Object} styles
  311. * @param {Object} parent
  312. * @param {Object} nopad
  313. */
  314. function createElement(tag, attribs, styles, parent, nopad) {
  315. var el = doc.createElement(tag);
  316. if (attribs) {
  317. extend(el, attribs);
  318. }
  319. if (nopad) {
  320. css(el, {padding: 0, border: NONE, margin: 0});
  321. }
  322. if (styles) {
  323. css(el, styles);
  324. }
  325. if (parent) {
  326. parent.appendChild(el);
  327. }
  328. return el;
  329. }
  330. /**
  331. * Extend a prototyped class by new members
  332. * @param {Object} parent
  333. * @param {Object} members
  334. */
  335. function extendClass(parent, members) {
  336. var object = function () {};
  337. object.prototype = new parent();
  338. extend(object.prototype, members);
  339. return object;
  340. }
  341. /**
  342. * Format a number and return a string based on input settings
  343. * @param {Number} number The input number to format
  344. * @param {Number} decimals The amount of decimals
  345. * @param {String} decPoint The decimal point, defaults to the one given in the lang options
  346. * @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options
  347. */
  348. function numberFormat(number, decimals, decPoint, thousandsSep) {
  349. var lang = defaultOptions.lang,
  350. // http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/
  351. n = +number || 0,
  352. c = decimals === -1 ?
  353. (n.toString().split('.')[1] || '').length : // preserve decimals
  354. (isNaN(decimals = mathAbs(decimals)) ? 2 : decimals),
  355. d = decPoint === undefined ? lang.decimalPoint : decPoint,
  356. t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep,
  357. s = n < 0 ? "-" : "",
  358. i = String(pInt(n = mathAbs(n).toFixed(c))),
  359. j = i.length > 3 ? i.length % 3 : 0;
  360. return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) +
  361. (c ? d + mathAbs(n - i).toFixed(c).slice(2) : "");
  362. }
  363. /**
  364. * Pad a string to a given length by adding 0 to the beginning
  365. * @param {Number} number
  366. * @param {Number} length
  367. */
  368. function pad(number, length) {
  369. // Create an array of the remaining length +1 and join it with 0's
  370. return new Array((length || 2) + 1 - String(number).length).join(0) + number;
  371. }
  372. /**
  373. * Wrap a method with extended functionality, preserving the original function
  374. * @param {Object} obj The context object that the method belongs to
  375. * @param {String} method The name of the method to extend
  376. * @param {Function} func A wrapper function callback. This function is called with the same arguments
  377. * as the original function, except that the original function is unshifted and passed as the first
  378. * argument.
  379. */
  380. function wrap(obj, method, func) {
  381. var proceed = obj[method];
  382. obj[method] = function () {
  383. var args = Array.prototype.slice.call(arguments);
  384. args.unshift(proceed);
  385. return func.apply(this, args);
  386. };
  387. }
  388. /**
  389. * Based on http://www.php.net/manual/en/function.strftime.php
  390. * @param {String} format
  391. * @param {Number} timestamp
  392. * @param {Boolean} capitalize
  393. */
  394. dateFormat = function (format, timestamp, capitalize) {
  395. if (!defined(timestamp) || isNaN(timestamp)) {
  396. return 'Invalid date';
  397. }
  398. format = pick(format, '%Y-%m-%d %H:%M:%S');
  399. var date = new Date(timestamp),
  400. key, // used in for constuct below
  401. // get the basic time values
  402. hours = date[getHours](),
  403. day = date[getDay](),
  404. dayOfMonth = date[getDate](),
  405. month = date[getMonth](),
  406. fullYear = date[getFullYear](),
  407. lang = defaultOptions.lang,
  408. langWeekdays = lang.weekdays,
  409. // List all format keys. Custom formats can be added from the outside.
  410. replacements = extend({
  411. // Day
  412. 'a': langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon'
  413. 'A': langWeekdays[day], // Long weekday, like 'Monday'
  414. 'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31
  415. 'e': dayOfMonth, // Day of the month, 1 through 31
  416. // Week (none implemented)
  417. //'W': weekNumber(),
  418. // Month
  419. 'b': lang.shortMonths[month], // Short month, like 'Jan'
  420. 'B': lang.months[month], // Long month, like 'January'
  421. 'm': pad(month + 1), // Two digit month number, 01 through 12
  422. // Year
  423. 'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009
  424. 'Y': fullYear, // Four digits year, like 2009
  425. // Time
  426. 'H': pad(hours), // Two digits hours in 24h format, 00 through 23
  427. 'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11
  428. 'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12
  429. 'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59
  430. 'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM
  431. 'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM
  432. 'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59
  433. 'L': pad(mathRound(timestamp % 1000), 3) // Milliseconds (naming from Ruby)
  434. }, Highcharts.dateFormats);
  435. // do the replaces
  436. for (key in replacements) {
  437. while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster
  438. format = format.replace('%' + key, typeof replacements[key] === 'function' ? replacements[key](timestamp) : replacements[key]);
  439. }
  440. }
  441. // Optionally capitalize the string and return
  442. return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format;
  443. };
  444. /**
  445. * Format a single variable. Similar to sprintf, without the % prefix.
  446. */
  447. function formatSingle(format, val) {
  448. var floatRegex = /f$/,
  449. decRegex = /\.([0-9])/,
  450. lang = defaultOptions.lang,
  451. decimals;
  452. if (floatRegex.test(format)) { // float
  453. decimals = format.match(decRegex);
  454. decimals = decimals ? decimals[1] : -1;
  455. val = numberFormat(
  456. val,
  457. decimals,
  458. lang.decimalPoint,
  459. format.indexOf(',') > -1 ? lang.thousandsSep : ''
  460. );
  461. } else {
  462. val = dateFormat(format, val);
  463. }
  464. return val;
  465. }
  466. /**
  467. * Format a string according to a subset of the rules of Python's String.format method.
  468. */
  469. function format(str, ctx) {
  470. var splitter = '{',
  471. isInside = false,
  472. segment,
  473. valueAndFormat,
  474. path,
  475. i,
  476. len,
  477. ret = [],
  478. val,
  479. index;
  480. while ((index = str.indexOf(splitter)) !== -1) {
  481. segment = str.slice(0, index);
  482. if (isInside) { // we're on the closing bracket looking back
  483. valueAndFormat = segment.split(':');
  484. path = valueAndFormat.shift().split('.'); // get first and leave format
  485. len = path.length;
  486. val = ctx;
  487. // Assign deeper paths
  488. for (i = 0; i < len; i++) {
  489. val = val[path[i]];
  490. }
  491. // Format the replacement
  492. if (valueAndFormat.length) {
  493. val = formatSingle(valueAndFormat.join(':'), val);
  494. }
  495. // Push the result and advance the cursor
  496. ret.push(val);
  497. } else {
  498. ret.push(segment);
  499. }
  500. str = str.slice(index + 1); // the rest
  501. isInside = !isInside; // toggle
  502. splitter = isInside ? '}' : '{'; // now look for next matching bracket
  503. }
  504. ret.push(str);
  505. return ret.join('');
  506. }
  507. /**
  508. * Get the magnitude of a number
  509. */
  510. function getMagnitude(num) {
  511. return math.pow(10, mathFloor(math.log(num) / math.LN10));
  512. }
  513. /**
  514. * Take an interval and normalize it to multiples of 1, 2, 2.5 and 5
  515. * @param {Number} interval
  516. * @param {Array} multiples
  517. * @param {Number} magnitude
  518. * @param {Object} options
  519. */
  520. function normalizeTickInterval(interval, multiples, magnitude, options) {
  521. var normalized, i;
  522. // round to a tenfold of 1, 2, 2.5 or 5
  523. magnitude = pick(magnitude, 1);
  524. normalized = interval / magnitude;
  525. // multiples for a linear scale
  526. if (!multiples) {
  527. multiples = [1, 2, 2.5, 5, 10];
  528. // the allowDecimals option
  529. if (options && options.allowDecimals === false) {
  530. if (magnitude === 1) {
  531. multiples = [1, 2, 5, 10];
  532. } else if (magnitude <= 0.1) {
  533. multiples = [1 / magnitude];
  534. }
  535. }
  536. }
  537. // normalize the interval to the nearest multiple
  538. for (i = 0; i < multiples.length; i++) {
  539. interval = multiples[i];
  540. if (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2) {
  541. break;
  542. }
  543. }
  544. // multiply back to the correct magnitude
  545. interval *= magnitude;
  546. return interval;
  547. }
  548. /**
  549. * Get a normalized tick interval for dates. Returns a configuration object with
  550. * unit range (interval), count and name. Used to prepare data for getTimeTicks.
  551. * Previously this logic was part of getTimeTicks, but as getTimeTicks now runs
  552. * of segments in stock charts, the normalizing logic was extracted in order to
  553. * prevent it for running over again for each segment having the same interval.
  554. * #662, #697.
  555. */
  556. function normalizeTimeTickInterval(tickInterval, unitsOption) {
  557. var units = unitsOption || [[
  558. MILLISECOND, // unit name
  559. [1, 2, 5, 10, 20, 25, 50, 100, 200, 500] // allowed multiples
  560. ], [
  561. SECOND,
  562. [1, 2, 5, 10, 15, 30]
  563. ], [
  564. MINUTE,
  565. [1, 2, 5, 10, 15, 30]
  566. ], [
  567. HOUR,
  568. [1, 2, 3, 4, 6, 8, 12]
  569. ], [
  570. DAY,
  571. [1, 2]
  572. ], [
  573. WEEK,
  574. [1, 2]
  575. ], [
  576. MONTH,
  577. [1, 2, 3, 4, 6]
  578. ], [
  579. YEAR,
  580. null
  581. ]],
  582. unit = units[units.length - 1], // default unit is years
  583. interval = timeUnits[unit[0]],
  584. multiples = unit[1],
  585. count,
  586. i;
  587. // loop through the units to find the one that best fits the tickInterval
  588. for (i = 0; i < units.length; i++) {
  589. unit = units[i];
  590. interval = timeUnits[unit[0]];
  591. multiples = unit[1];
  592. if (units[i + 1]) {
  593. // lessThan is in the middle between the highest multiple and the next unit.
  594. var lessThan = (interval * multiples[multiples.length - 1] +
  595. timeUnits[units[i + 1][0]]) / 2;
  596. // break and keep the current unit
  597. if (tickInterval <= lessThan) {
  598. break;
  599. }
  600. }
  601. }
  602. // prevent 2.5 years intervals, though 25, 250 etc. are allowed
  603. if (interval === timeUnits[YEAR] && tickInterval < 5 * interval) {
  604. multiples = [1, 2, 5];
  605. }
  606. // get the count
  607. count = normalizeTickInterval(
  608. tickInterval / interval,
  609. multiples,
  610. unit[0] === YEAR ? getMagnitude(tickInterval / interval) : 1 // #1913
  611. );
  612. return {
  613. unitRange: interval,
  614. count: count,
  615. unitName: unit[0]
  616. };
  617. }
  618. /**
  619. * Set the tick positions to a time unit that makes sense, for example
  620. * on the first of each month or on every Monday. Return an array
  621. * with the time positions. Used in datetime axes as well as for grouping
  622. * data on a datetime axis.
  623. *
  624. * @param {Object} normalizedInterval The interval in axis values (ms) and the count
  625. * @param {Number} min The minimum in axis values
  626. * @param {Number} max The maximum in axis values
  627. * @param {Number} startOfWeek
  628. */
  629. function getTimeTicks(normalizedInterval, min, max, startOfWeek) {
  630. var tickPositions = [],
  631. i,
  632. higherRanks = {},
  633. useUTC = defaultOptions.global.useUTC,
  634. minYear, // used in months and years as a basis for Date.UTC()
  635. minDate = new Date(min),
  636. interval = normalizedInterval.unitRange,
  637. count = normalizedInterval.count;
  638. if (defined(min)) { // #1300
  639. if (interval >= timeUnits[SECOND]) { // second
  640. minDate.setMilliseconds(0);
  641. minDate.setSeconds(interval >= timeUnits[MINUTE] ? 0 :
  642. count * mathFloor(minDate.getSeconds() / count));
  643. }
  644. if (interval >= timeUnits[MINUTE]) { // minute
  645. minDate[setMinutes](interval >= timeUnits[HOUR] ? 0 :
  646. count * mathFloor(minDate[getMinutes]() / count));
  647. }
  648. if (interval >= timeUnits[HOUR]) { // hour
  649. minDate[setHours](interval >= timeUnits[DAY] ? 0 :
  650. count * mathFloor(minDate[getHours]() / count));
  651. }
  652. if (interval >= timeUnits[DAY]) { // day
  653. minDate[setDate](interval >= timeUnits[MONTH] ? 1 :
  654. count * mathFloor(minDate[getDate]() / count));
  655. }
  656. if (interval >= timeUnits[MONTH]) { // month
  657. minDate[setMonth](interval >= timeUnits[YEAR] ? 0 :
  658. count * mathFloor(minDate[getMonth]() / count));
  659. minYear = minDate[getFullYear]();
  660. }
  661. if (interval >= timeUnits[YEAR]) { // year
  662. minYear -= minYear % count;
  663. minDate[setFullYear](minYear);
  664. }
  665. // week is a special case that runs outside the hierarchy
  666. if (interval === timeUnits[WEEK]) {
  667. // get start of current week, independent of count
  668. minDate[setDate](minDate[getDate]() - minDate[getDay]() +
  669. pick(startOfWeek, 1));
  670. }
  671. // get tick positions
  672. i = 1;
  673. minYear = minDate[getFullYear]();
  674. var time = minDate.getTime(),
  675. minMonth = minDate[getMonth](),
  676. minDateDate = minDate[getDate](),
  677. timezoneOffset = useUTC ?
  678. 0 :
  679. (24 * 3600 * 1000 + minDate.getTimezoneOffset() * 60 * 1000) % (24 * 3600 * 1000); // #950
  680. // iterate and add tick positions at appropriate values
  681. while (time < max) {
  682. tickPositions.push(time);
  683. // if the interval is years, use Date.UTC to increase years
  684. if (interval === timeUnits[YEAR]) {
  685. time = makeTime(minYear + i * count, 0);
  686. // if the interval is months, use Date.UTC to increase months
  687. } else if (interval === timeUnits[MONTH]) {
  688. time = makeTime(minYear, minMonth + i * count);
  689. // if we're using global time, the interval is not fixed as it jumps
  690. // one hour at the DST crossover
  691. } else if (!useUTC && (interval === timeUnits[DAY] || interval === timeUnits[WEEK])) {
  692. time = makeTime(minYear, minMonth, minDateDate +
  693. i * count * (interval === timeUnits[DAY] ? 1 : 7));
  694. // else, the interval is fixed and we use simple addition
  695. } else {
  696. time += interval * count;
  697. }
  698. i++;
  699. }
  700. // push the last time
  701. tickPositions.push(time);
  702. // mark new days if the time is dividible by day (#1649, #1760)
  703. each(grep(tickPositions, function (time) {
  704. return interval <= timeUnits[HOUR] && time % timeUnits[DAY] === timezoneOffset;
  705. }), function (time) {
  706. higherRanks[time] = DAY;
  707. });
  708. }
  709. // reconciliation information on the chosen unit - for dynamic label formatter
  710. tickPositions.info = extend(normalizedInterval, {
  711. higherRanks: higherRanks,
  712. totalRange: interval * count
  713. });
  714. return tickPositions;
  715. }
  716. /**
  717. * Helper class that contains variuos counters that are local to the chart.
  718. */
  719. function ChartCounters() {
  720. this.color = 0;
  721. this.symbol = 0;
  722. }
  723. ChartCounters.prototype = {
  724. /**
  725. * Wraps the color counter if it reaches the specified length.
  726. */
  727. wrapColor: function (length) {
  728. if (this.color >= length) {
  729. this.color = 0;
  730. }
  731. },
  732. /**
  733. * Wraps the symbol counter if it reaches the specified length.
  734. */
  735. wrapSymbol: function (length) {
  736. if (this.symbol >= length) {
  737. this.symbol = 0;
  738. }
  739. }
  740. };
  741. /**
  742. * Utility method that sorts an object array and keeping the order of equal items.
  743. * ECMA script standard does not specify the behaviour when items are equal.
  744. */
  745. function stableSort(arr, sortFunction) {
  746. var length = arr.length,
  747. sortValue,
  748. i;
  749. // Add index to each item
  750. for (i = 0; i < length; i++) {
  751. arr[i].ss_i = i; // stable sort index
  752. }
  753. arr.sort(function (a, b) {
  754. sortValue = sortFunction(a, b);
  755. return sortValue === 0 ? a.ss_i - b.ss_i : sortValue;
  756. });
  757. // Remove index from items
  758. for (i = 0; i < length; i++) {
  759. delete arr[i].ss_i; // stable sort index
  760. }
  761. }
  762. /**
  763. * Non-recursive method to find the lowest member of an array. Math.min raises a maximum
  764. * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
  765. * method is slightly slower, but safe.
  766. */
  767. function arrayMin(data) {
  768. var i = data.length,
  769. min = data[0];
  770. while (i--) {
  771. if (data[i] < min) {
  772. min = data[i];
  773. }
  774. }
  775. return min;
  776. }
  777. /**
  778. * Non-recursive method to find the lowest member of an array. Math.min raises a maximum
  779. * call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
  780. * method is slightly slower, but safe.
  781. */
  782. function arrayMax(data) {
  783. var i = data.length,
  784. max = data[0];
  785. while (i--) {
  786. if (data[i] > max) {
  787. max = data[i];
  788. }
  789. }
  790. return max;
  791. }
  792. /**
  793. * Utility method that destroys any SVGElement or VMLElement that are properties on the given object.
  794. * It loops all properties and invokes destroy if there is a destroy method. The property is
  795. * then delete'ed.
  796. * @param {Object} The object to destroy properties on
  797. * @param {Object} Exception, do not destroy this property, only delete it.
  798. */
  799. function destroyObjectProperties(obj, except) {
  800. var n;
  801. for (n in obj) {
  802. // If the object is non-null and destroy is defined
  803. if (obj[n] && obj[n] !== except && obj[n].destroy) {
  804. // Invoke the destroy
  805. obj[n].destroy();
  806. }
  807. // Delete the property from the object.
  808. delete obj[n];
  809. }
  810. }
  811. /**
  812. * Discard an element by moving it to the bin and delete
  813. * @param {Object} The HTML node to discard
  814. */
  815. function discardElement(element) {
  816. // create a garbage bin element, not part of the DOM
  817. if (!garbageBin) {
  818. garbageBin = createElement(DIV);
  819. }
  820. // move the node and empty bin
  821. if (element) {
  822. garbageBin.appendChild(element);
  823. }
  824. garbageBin.innerHTML = '';
  825. }
  826. /**
  827. * Provide error messages for debugging, with links to online explanation
  828. */
  829. function error(code, stop) {
  830. var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code;
  831. if (stop) {
  832. throw msg;
  833. } else if (win.console) {
  834. console.log(msg);
  835. }
  836. }
  837. /**
  838. * Fix JS round off float errors
  839. * @param {Number} num
  840. */
  841. function correctFloat(num) {
  842. return parseFloat(
  843. num.toPrecision(14)
  844. );
  845. }
  846. /**
  847. * Set the global animation to either a given value, or fall back to the
  848. * given chart's animation option
  849. * @param {Object} animation
  850. * @param {Object} chart
  851. */
  852. function setAnimation(animation, chart) {
  853. globalAnimation = pick(animation, chart.animation);
  854. }
  855. /**
  856. * The time unit lookup
  857. */
  858. /*jslint white: true*/
  859. timeUnits = hash(
  860. MILLISECOND, 1,
  861. SECOND, 1000,
  862. MINUTE, 60000,
  863. HOUR, 3600000,
  864. DAY, 24 * 3600000,
  865. WEEK, 7 * 24 * 3600000,
  866. MONTH, 31 * 24 * 3600000,
  867. YEAR, 31556952000
  868. );
  869. /*jslint white: false*/
  870. /**
  871. * Path interpolation algorithm used across adapters
  872. */
  873. pathAnim = {
  874. /**
  875. * Prepare start and end values so that the path can be animated one to one
  876. */
  877. init: function (elem, fromD, toD) {
  878. fromD = fromD || '';
  879. var shift = elem.shift,
  880. bezier = fromD.indexOf('C') > -1,
  881. numParams = bezier ? 7 : 3,
  882. endLength,
  883. slice,
  884. i,
  885. start = fromD.split(' '),
  886. end = [].concat(toD), // copy
  887. startBaseLine,
  888. endBaseLine,
  889. sixify = function (arr) { // in splines make move points have six parameters like bezier curves
  890. i = arr.length;
  891. while (i--) {
  892. if (arr[i] === M) {
  893. arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]);
  894. }
  895. }
  896. };
  897. if (bezier) {
  898. sixify(start);
  899. sixify(end);
  900. }
  901. // pull out the base lines before padding
  902. if (elem.isArea) {
  903. startBaseLine = start.splice(start.length - 6, 6);
  904. endBaseLine = end.splice(end.length - 6, 6);
  905. }
  906. // if shifting points, prepend a dummy point to the end path
  907. if (shift <= end.length / numParams && start.length === end.length) {
  908. while (shift--) {
  909. end = [].concat(end).splice(0, numParams).concat(end);
  910. }
  911. }
  912. elem.shift = 0; // reset for following animations
  913. // copy and append last point until the length matches the end length
  914. if (start.length) {
  915. endLength = end.length;
  916. while (start.length < endLength) {
  917. //bezier && sixify(start);
  918. slice = [].concat(start).splice(start.length - numParams, numParams);
  919. if (bezier) { // disable first control point
  920. slice[numParams - 6] = slice[numParams - 2];
  921. slice[numParams - 5] = slice[numParams - 1];
  922. }
  923. start = start.concat(slice);
  924. }
  925. }
  926. if (startBaseLine) { // append the base lines for areas
  927. start = start.concat(startBaseLine);
  928. end = end.concat(endBaseLine);
  929. }
  930. return [start, end];
  931. },
  932. /**
  933. * Interpolate each value of the path and return the array
  934. */
  935. step: function (start, end, pos, complete) {
  936. var ret = [],
  937. i = start.length,
  938. startVal;
  939. if (pos === 1) { // land on the final path without adjustment points appended in the ends
  940. ret = complete;
  941. } else if (i === end.length && pos < 1) {
  942. while (i--) {
  943. startVal = parseFloat(start[i]);
  944. ret[i] =
  945. isNaN(startVal) ? // a letter instruction like M or L
  946. start[i] :
  947. pos * (parseFloat(end[i] - startVal)) + startVal;
  948. }
  949. } else { // if animation is finished or length not matching, land on right value
  950. ret = end;
  951. }
  952. return ret;
  953. }
  954. };
  955. (function ($) {
  956. /**
  957. * The default HighchartsAdapter for jQuery
  958. */
  959. win.HighchartsAdapter = win.HighchartsAdapter || ($ && {
  960. /**
  961. * Initialize the adapter by applying some extensions to jQuery
  962. */
  963. init: function (pathAnim) {
  964. // extend the animate function to allow SVG animations
  965. var Fx = $.fx,
  966. Step = Fx.step,
  967. dSetter,
  968. Tween = $.Tween,
  969. propHooks = Tween && Tween.propHooks,
  970. opacityHook = $.cssHooks.opacity;
  971. /*jslint unparam: true*//* allow unused param x in this function */
  972. $.extend($.easing, {
  973. easeOutQuad: function (x, t, b, c, d) {
  974. return -c * (t /= d) * (t - 2) + b;
  975. }
  976. });
  977. /*jslint unparam: false*/
  978. // extend some methods to check for elem.attr, which means it is a Highcharts SVG object
  979. $.each(['cur', '_default', 'width', 'height', 'opacity'], function (i, fn) {
  980. var obj = Step,
  981. base,
  982. elem;
  983. // Handle different parent objects
  984. if (fn === 'cur') {
  985. obj = Fx.prototype; // 'cur', the getter, relates to Fx.prototype
  986. } else if (fn === '_default' && Tween) { // jQuery 1.8 model
  987. obj = propHooks[fn];
  988. fn = 'set';
  989. }
  990. // Overwrite the method
  991. base = obj[fn];
  992. if (base) { // step.width and step.height don't exist in jQuery < 1.7
  993. // create the extended function replacement
  994. obj[fn] = function (fx) {
  995. // Fx.prototype.cur does not use fx argument
  996. fx = i ? fx : this;
  997. // Don't run animations on textual properties like align (#1821)
  998. if (fx.prop === 'align') {
  999. return;
  1000. }
  1001. // shortcut
  1002. elem = fx.elem;
  1003. // Fx.prototype.cur returns the current value. The other ones are setters
  1004. // and returning a value has no effect.
  1005. return elem.attr ? // is SVG element wrapper
  1006. elem.attr(fx.prop, fn === 'cur' ? UNDEFINED : fx.now) : // apply the SVG wrapper's method
  1007. base.apply(this, arguments); // use jQuery's built-in method
  1008. };
  1009. }
  1010. });
  1011. // Extend the opacity getter, needed for fading opacity with IE9 and jQuery 1.10+
  1012. wrap(opacityHook, 'get', function (proceed, elem, computed) {
  1013. return elem.attr ? (elem.opacity || 0) : proceed.call(this, elem, computed);
  1014. });
  1015. // Define the setter function for d (path definitions)
  1016. dSetter = function (fx) {
  1017. var elem = fx.elem,
  1018. ends;
  1019. // Normally start and end should be set in state == 0, but sometimes,
  1020. // for reasons unknown, this doesn't happen. Perhaps state == 0 is skipped
  1021. // in these cases
  1022. if (!fx.started) {
  1023. ends = pathAnim.init(elem, elem.d, elem.toD);
  1024. fx.start = ends[0];
  1025. fx.end = ends[1];
  1026. fx.started = true;
  1027. }
  1028. // interpolate each value of the path
  1029. elem.attr('d', pathAnim.step(fx.start, fx.end, fx.pos, elem.toD));
  1030. };
  1031. // jQuery 1.8 style
  1032. if (Tween) {
  1033. propHooks.d = {
  1034. set: dSetter
  1035. };
  1036. // pre 1.8
  1037. } else {
  1038. // animate paths
  1039. Step.d = dSetter;
  1040. }
  1041. /**
  1042. * Utility for iterating over an array. Parameters are reversed compared to jQuery.
  1043. * @param {Array} arr
  1044. * @param {Function} fn
  1045. */
  1046. this.each = Array.prototype.forEach ?
  1047. function (arr, fn) { // modern browsers
  1048. return Array.prototype.forEach.call(arr, fn);
  1049. } :
  1050. function (arr, fn) { // legacy
  1051. var i = 0,
  1052. len = arr.length;
  1053. for (; i < len; i++) {
  1054. if (fn.call(arr[i], arr[i], i, arr) === false) {
  1055. return i;
  1056. }
  1057. }
  1058. };
  1059. /**
  1060. * Register Highcharts as a plugin in the respective framework
  1061. */
  1062. $.fn.highcharts = function () {
  1063. var constr = 'Chart', // default constructor
  1064. args = arguments,
  1065. options,
  1066. ret,
  1067. chart;
  1068. if (isString(args[0])) {
  1069. constr = args[0];
  1070. args = Array.prototype.slice.call(args, 1);
  1071. }
  1072. options = args[0];
  1073. // Create the chart
  1074. if (options !== UNDEFINED) {
  1075. /*jslint unused:false*/
  1076. options.chart = options.chart || {};
  1077. options.chart.renderTo = this[0];
  1078. chart = new Highcharts[constr](options, args[1]);
  1079. ret = this;
  1080. /*jslint unused:true*/
  1081. }
  1082. // When called without parameters or with the return argument, get a predefined chart
  1083. if (options === UNDEFINED) {
  1084. ret = charts[attr(this[0], 'data-highcharts-chart')];
  1085. }
  1086. return ret;
  1087. };
  1088. },
  1089. /**
  1090. * Downloads a script and executes a callback when done.
  1091. * @param {String} scriptLocation
  1092. * @param {Function} callback
  1093. */
  1094. getScript: $.getScript,
  1095. /**
  1096. * Return the index of an item in an array, or -1 if not found
  1097. */
  1098. inArray: $.inArray,
  1099. /**
  1100. * A direct link to jQuery methods. MooTools and Prototype adapters must be implemented for each case of method.
  1101. * @param {Object} elem The HTML element
  1102. * @param {String} method Which method to run on the wrapped element
  1103. */
  1104. adapterRun: function (elem, method) {
  1105. return $(elem)[method]();
  1106. },
  1107. /**
  1108. * Filter an array
  1109. */
  1110. grep: $.grep,
  1111. /**
  1112. * Map an array
  1113. * @param {Array} arr
  1114. * @param {Function} fn
  1115. */
  1116. map: function (arr, fn) {
  1117. //return jQuery.map(arr, fn);
  1118. var results = [],
  1119. i = 0,
  1120. len = arr.length;
  1121. for (; i < len; i++) {
  1122. results[i] = fn.call(arr[i], arr[i], i, arr);
  1123. }
  1124. return results;
  1125. },
  1126. /**
  1127. * Get the position of an element relative to the top left of the page
  1128. */
  1129. offset: function (el) {
  1130. return $(el).offset();
  1131. },
  1132. /**
  1133. * Add an event listener
  1134. * @param {Object} el A HTML element or custom object
  1135. * @param {String} event The event type
  1136. * @param {Function} fn The event handler
  1137. */
  1138. addEvent: function (el, event, fn) {
  1139. $(el).bind(event, fn);
  1140. },
  1141. /**
  1142. * Remove event added with addEvent
  1143. * @param {Object} el The object
  1144. * @param {String} eventType The event type. Leave blank to remove all events.
  1145. * @param {Function} handler The function to remove
  1146. */
  1147. removeEvent: function (el, eventType, handler) {
  1148. // workaround for jQuery issue with unbinding custom events:
  1149. // http://forum.jQuery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jQuery-1-4-2
  1150. var func = doc.removeEventListener ? 'removeEventListener' : 'detachEvent';
  1151. if (doc[func] && el && !el[func]) {
  1152. el[func] = function () {};
  1153. }
  1154. $(el).unbind(eventType, handler);
  1155. },
  1156. /**
  1157. * Fire an event on a custom object
  1158. * @param {Object} el
  1159. * @param {String} type
  1160. * @param {Object} eventArguments
  1161. * @param {Function} defaultFunction
  1162. */
  1163. fireEvent: function (el, type, eventArguments, defaultFunction) {
  1164. var event = $.Event(type),
  1165. detachedType = 'detached' + type,
  1166. defaultPrevented;
  1167. // Remove warnings in Chrome when accessing layerX and layerY. Although Highcharts
  1168. // never uses these properties, Chrome includes them in the default click event and
  1169. // raises the warning when they are copied over in the extend statement below.
  1170. //
  1171. // To avoid problems in IE (see #1010) where we cannot delete the properties and avoid
  1172. // testing if they are there (warning in chrome) the only option is to test if running IE.
  1173. if (!isIE && eventArguments) {
  1174. delete eventArguments.layerX;
  1175. delete eventArguments.layerY;
  1176. }
  1177. extend(event, eventArguments);
  1178. // Prevent jQuery from triggering the object method that is named the
  1179. // same as the event. For example, if the event is 'select', jQuery
  1180. // attempts calling el.select and it goes into a loop.
  1181. if (el[type]) {
  1182. el[detachedType] = el[type];
  1183. el[type] = null;
  1184. }
  1185. // Wrap preventDefault and stopPropagation in try/catch blocks in
  1186. // order to prevent JS errors when cancelling events on non-DOM
  1187. // objects. #615.
  1188. /*jslint unparam: true*/
  1189. $.each(['preventDefault', 'stopPropagation'], function (i, fn) {
  1190. var base = event[fn];
  1191. event[fn] = function () {
  1192. try {
  1193. base.call(event);
  1194. } catch (e) {
  1195. if (fn === 'preventDefault') {
  1196. defaultPrevented = true;
  1197. }
  1198. }
  1199. };
  1200. });
  1201. /*jslint unparam: false*/
  1202. // trigger it
  1203. $(el).trigger(event);
  1204. // attach the method
  1205. if (el[detachedType]) {
  1206. el[type] = el[detachedType];
  1207. el[detachedType] = null;
  1208. }
  1209. if (defaultFunction && !event.isDefaultPrevented() && !defaultPrevented) {
  1210. defaultFunction(event);
  1211. }
  1212. },
  1213. /**
  1214. * Extension method needed for MooTools
  1215. */
  1216. washMouseEvent: function (e) {
  1217. var ret = e.originalEvent || e;
  1218. // computed by jQuery, needed by IE8
  1219. if (ret.pageX === UNDEFINED) { // #1236
  1220. ret.pageX = e.pageX;
  1221. ret.pageY = e.pageY;
  1222. }
  1223. return ret;
  1224. },
  1225. /**
  1226. * Animate a HTML element or SVG element wrapper
  1227. * @param {Object} el
  1228. * @param {Object} params
  1229. * @param {Object} options jQuery-like animation options: duration, easing, callback
  1230. */
  1231. animate: function (el, params, options) {
  1232. var $el = $(el);
  1233. if (!el.style) {
  1234. el.style = {}; // #1881
  1235. }
  1236. if (params.d) {
  1237. el.toD = params.d; // keep the array form for paths, used in $.fx.step.d
  1238. params.d = 1; // because in jQuery, animating to an array has a different meaning
  1239. }
  1240. $el.stop();
  1241. if (params.opacity !== UNDEFINED && el.attr) {
  1242. params.opacity += 'px'; // force jQuery to use same logic as width and height (#2161)
  1243. }
  1244. $el.animate(params, options);
  1245. },
  1246. /**
  1247. * Stop running animation
  1248. */
  1249. stop: function (el) {
  1250. $(el).stop();
  1251. }
  1252. });
  1253. }(win.jQuery));
  1254. // check for a custom HighchartsAdapter defined prior to this file
  1255. var globalAdapter = win.HighchartsAdapter,
  1256. adapter = globalAdapter || {};
  1257. // Initialize the adapter
  1258. if (globalAdapter) {
  1259. globalAdapter.init.call(globalAdapter, pathAnim);
  1260. }
  1261. // Utility functions. If the HighchartsAdapter is not defined, adapter is an empty object
  1262. // and all the utility functions will be null. In that case they are populated by the
  1263. // default adapters below.
  1264. var adapterRun = adapter.adapterRun,
  1265. getScript = adapter.getScript,
  1266. inArray = adapter.inArray,
  1267. each = adapter.each,
  1268. grep = adapter.grep,
  1269. offset = adapter.offset,
  1270. map = adapter.map,
  1271. addEvent = adapter.addEvent,
  1272. removeEvent = adapter.removeEvent,
  1273. fireEvent = adapter.fireEvent,
  1274. washMouseEvent = adapter.washMouseEvent,
  1275. animate = adapter.animate,
  1276. stop = adapter.stop;
  1277. /* ****************************************************************************
  1278. * Handle the options *
  1279. *****************************************************************************/
  1280. var
  1281. defaultLabelOptions = {
  1282. enabled: true,
  1283. // rotation: 0,
  1284. // align: 'center',
  1285. x: 0,
  1286. y: 15,
  1287. /*formatter: function () {
  1288. return this.value;
  1289. },*/
  1290. style: {
  1291. color: '#666',
  1292. cursor: 'default',
  1293. fontSize: '11px',
  1294. lineHeight: '14px'
  1295. }
  1296. };
  1297. defaultOptions = {
  1298. colors: ['#2f7ed8', '#0d233a', '#8bbc21', '#910000', '#1aadce', '#492970',
  1299. '#f28f43', '#77a1e5', '#c42525', '#a6c96a'],
  1300. symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'],
  1301. lang: {
  1302. loading: 'Loading...',
  1303. months: ['January', 'February', 'March', 'April', 'May', 'June', 'July',
  1304. 'August', 'September', 'October', 'November', 'December'],
  1305. shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  1306. weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  1307. decimalPoint: '.',
  1308. numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels
  1309. resetZoom: 'Reset zoom',
  1310. resetZoomTitle: 'Reset zoom level 1:1',
  1311. thousandsSep: ','
  1312. },
  1313. global: {
  1314. useUTC: true,
  1315. canvasToolsURL: 'http://code.highcharts.com/3.0.6/modules/canvas-tools.js',
  1316. VMLRadialGradientURL: 'http://code.highcharts.com/3.0.6/gfx/vml-radial-gradient.png'
  1317. },
  1318. chart: {
  1319. //animation: true,
  1320. //alignTicks: false,
  1321. //reflow: true,
  1322. //className: null,
  1323. //events: { load, selection },
  1324. //margin: [null],
  1325. //marginTop: null,
  1326. //marginRight: null,
  1327. //marginBottom: null,
  1328. //marginLeft: null,
  1329. borderColor: '#4572A7',
  1330. //borderWidth: 0,
  1331. borderRadius: 5,
  1332. defaultSeriesType: 'line',
  1333. ignoreHiddenSeries: true,
  1334. //inverted: false,
  1335. //shadow: false,
  1336. spacing: [10, 10, 15, 10],
  1337. //spacingTop: 10,
  1338. //spacingRight: 10,
  1339. //spacingBottom: 15,
  1340. //spacingLeft: 10,
  1341. style: {
  1342. fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font
  1343. fontSize: '12px'
  1344. },
  1345. backgroundColor: '#FFFFFF',
  1346. //plotBackgroundColor: null,
  1347. plotBorderColor: '#C0C0C0',
  1348. //plotBorderWidth: 0,
  1349. //plotShadow: false,
  1350. //zoomType: ''
  1351. resetZoomButton: {
  1352. theme: {
  1353. zIndex: 20
  1354. },
  1355. position: {
  1356. align: 'right',
  1357. x: -10,
  1358. //verticalAlign: 'top',
  1359. y: 10
  1360. }
  1361. // relativeTo: 'plot'
  1362. }
  1363. },
  1364. title: {
  1365. text: 'Chart title',
  1366. align: 'center',
  1367. // floating: false,
  1368. margin: 15,
  1369. // x: 0,
  1370. // verticalAlign: 'top',
  1371. // y: null,
  1372. style: {
  1373. color: '#274b6d',//#3E576F',
  1374. fontSize: '16px'
  1375. }
  1376. },
  1377. subtitle: {
  1378. text: '',
  1379. align: 'center',
  1380. // floating: false
  1381. // x: 0,
  1382. // verticalAlign: 'top',
  1383. // y: null,
  1384. style: {
  1385. color: '#4d759e'
  1386. }
  1387. },
  1388. plotOptions: {
  1389. line: { // base series options
  1390. allowPointSelect: false,
  1391. showCheckbox: false,
  1392. animation: {
  1393. duration: 1000
  1394. },
  1395. //connectNulls: false,
  1396. //cursor: 'default',
  1397. //clip: true,
  1398. //dashStyle: null,
  1399. //enableMouseTracking: true,
  1400. events: {},
  1401. //legendIndex: 0,
  1402. lineWidth: 2,
  1403. //shadow: false,
  1404. // stacking: null,
  1405. marker: {
  1406. enabled: true,
  1407. //symbol: null,
  1408. lineWidth: 0,
  1409. radius: 4,
  1410. lineColor: '#FFFFFF',
  1411. //fillColor: null,
  1412. states: { // states for a single point
  1413. hover: {
  1414. enabled: true
  1415. //radius: base + 2
  1416. },
  1417. select: {
  1418. fillColor: '#FFFFFF',
  1419. lineColor: '#000000',
  1420. lineWidth: 2
  1421. }
  1422. }
  1423. },
  1424. point: {
  1425. events: {}
  1426. },
  1427. dataLabels: merge(defaultLabelOptions, {
  1428. align: 'center',
  1429. enabled: false,
  1430. formatter: function () {
  1431. return this.y === null ? '' : numberFormat(this.y, -1);
  1432. },
  1433. verticalAlign: 'bottom', // above singular point
  1434. y: 0
  1435. // backgroundColor: undefined,
  1436. // borderColor: undefined,
  1437. // borderRadius: undefined,
  1438. // borderWidth: undefined,
  1439. // padding: 3,
  1440. // shadow: false
  1441. }),
  1442. cropThreshold: 300, // draw points outside the plot area when the number of points is less than this
  1443. pointRange: 0,
  1444. //pointStart: 0,
  1445. //pointInterval: 1,
  1446. showInLegend: true,
  1447. states: { // states for the entire series
  1448. hover: {
  1449. //enabled: false,
  1450. //lineWidth: base + 1,
  1451. marker: {
  1452. // lineWidth: base + 1,
  1453. // radius: base + 1
  1454. }
  1455. },
  1456. select: {
  1457. marker: {}
  1458. }
  1459. },
  1460. stickyTracking: true
  1461. //tooltip: {
  1462. //pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b>'
  1463. //valueDecimals: null,
  1464. //xDateFormat: '%A, %b %e, %Y',
  1465. //valuePrefix: '',
  1466. //ySuffix: ''
  1467. //}
  1468. // turboThreshold: 1000
  1469. // zIndex: null
  1470. }
  1471. },
  1472. labels: {
  1473. //items: [],
  1474. style: {
  1475. //font: defaultFont,
  1476. position: ABSOLUTE,
  1477. color: '#3E576F'
  1478. }
  1479. },
  1480. legend: {
  1481. enabled: true,
  1482. align: 'center',
  1483. //floating: false,
  1484. layout: 'horizontal',
  1485. labelFormatter: function () {
  1486. return this.name;
  1487. },
  1488. borderWidth: 1,
  1489. borderColor: '#909090',
  1490. borderRadius: 5,
  1491. navigation: {
  1492. // animation: true,
  1493. activeColor: '#274b6d',
  1494. // arrowSize: 12
  1495. inactiveColor: '#CCC'
  1496. // style: {} // text styles
  1497. },
  1498. // margin: 10,
  1499. // reversed: false,
  1500. shadow: false,
  1501. // backgroundColor: null,
  1502. /*style: {
  1503. padding: '5px'
  1504. },*/
  1505. itemStyle: {
  1506. cursor: 'pointer',
  1507. color: '#274b6d',
  1508. fontSize: '12px'
  1509. },
  1510. itemHoverStyle: {
  1511. //cursor: 'pointer', removed as of #601
  1512. color: '#000'
  1513. },
  1514. itemHiddenStyle: {
  1515. color: '#CCC'
  1516. },
  1517. itemCheckboxStyle: {
  1518. position: ABSOLUTE,
  1519. width: '13px', // for IE precision
  1520. height: '13px'
  1521. },
  1522. // itemWidth: undefined,
  1523. symbolWidth: 16,
  1524. symbolPadding: 5,
  1525. verticalAlign: 'bottom',
  1526. // width: undefined,
  1527. x: 0,
  1528. y: 0,
  1529. title: {
  1530. //text: null,
  1531. style: {
  1532. fontWeight: 'bold'
  1533. }
  1534. }
  1535. },
  1536. loading: {
  1537. // hideDuration: 100,
  1538. labelStyle: {
  1539. fontWeight: 'bold',
  1540. position: RELATIVE,
  1541. top: '1em'
  1542. },
  1543. // showDuration: 0,
  1544. style: {
  1545. position: ABSOLUTE,
  1546. backgroundColor: 'white',
  1547. opacity: 0.5,
  1548. textAlign: 'center'
  1549. }
  1550. },
  1551. tooltip: {
  1552. enabled: true,
  1553. animation: hasSVG,
  1554. //crosshairs: null,
  1555. backgroundColor: 'rgba(255, 255, 255, .85)',
  1556. borderWidth: 1,
  1557. borderRadius: 3,
  1558. dateTimeLabelFormats: {
  1559. millisecond: '%A, %b %e, %H:%M:%S.%L',
  1560. second: '%A, %b %e, %H:%M:%S',
  1561. minute: '%A, %b %e, %H:%M',
  1562. hour: '%A, %b %e, %H:%M',
  1563. day: '%A, %b %e, %Y',
  1564. week: 'Week from %A, %b %e, %Y',
  1565. month: '%B %Y',
  1566. year: '%Y'
  1567. },
  1568. //formatter: defaultFormatter,
  1569. headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>',
  1570. pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b><br/>',
  1571. shadow: true,
  1572. //shared: false,
  1573. snap: isTouchDevice ? 25 : 10,
  1574. style: {
  1575. color: '#333333',
  1576. cursor: 'default',
  1577. fontSize: '12px',
  1578. padding: '8px',
  1579. whiteSpace: 'nowrap'
  1580. }
  1581. //xDateFormat: '%A, %b %e, %Y',
  1582. //valueDecimals: null,
  1583. //valuePrefix: '',
  1584. //valueSuffix: ''
  1585. },
  1586. credits: {
  1587. enabled: true,
  1588. text: 'Highcharts.com',
  1589. href: 'http://www.highcharts.com',
  1590. position: {
  1591. align: 'right',
  1592. x: -10,
  1593. verticalAlign: 'bottom',
  1594. y: -5
  1595. },
  1596. style: {
  1597. cursor: 'pointer',
  1598. color: '#909090',
  1599. fontSize: '9px'
  1600. }
  1601. }
  1602. };
  1603. // Series defaults
  1604. var defaultPlotOptions = defaultOptions.plotOptions,
  1605. defaultSeriesOptions = defaultPlotOptions.line;
  1606. // set the default time methods
  1607. setTimeMethods();
  1608. /**
  1609. * Set the time methods globally based on the useUTC option. Time method can be either
  1610. * local time or UTC (default).
  1611. */
  1612. function setTimeMethods() {
  1613. var useUTC = defaultOptions.global.useUTC,
  1614. GET = useUTC ? 'getUTC' : 'get',
  1615. SET = useUTC ? 'setUTC' : 'set';
  1616. makeTime = useUTC ? Date.UTC : function (year, month, date, hours, minutes, seconds) {
  1617. return new Date(
  1618. year,
  1619. month,
  1620. pick(date, 1),
  1621. pick(hours, 0),
  1622. pick(minutes, 0),
  1623. pick(seconds, 0)
  1624. ).getTime();
  1625. };
  1626. getMinutes = GET + 'Minutes';
  1627. getHours = GET + 'Hours';
  1628. getDay = GET + 'Day';
  1629. getDate = GET + 'Date';
  1630. getMonth = GET + 'Month';
  1631. getFullYear = GET + 'FullYear';
  1632. setMinutes = SET + 'Minutes';
  1633. setHours = SET + 'Hours';
  1634. setDate = SET + 'Date';
  1635. setMonth = SET + 'Month';
  1636. setFullYear = SET + 'FullYear';
  1637. }
  1638. /**
  1639. * Merge the default options with custom options and return the new options structure
  1640. * @param {Object} options The new custom options
  1641. */
  1642. function setOptions(options) {
  1643. // Pull out axis options and apply them to the respective default axis options
  1644. /*defaultXAxisOptions = merge(defaultXAxisOptions, options.xAxis);
  1645. defaultYAxisOptions = merge(defaultYAxisOptions, options.yAxis);
  1646. options.xAxis = options.yAxis = UNDEFINED;*/
  1647. // Merge in the default options
  1648. defaultOptions = merge(defaultOptions, options);
  1649. // Apply UTC
  1650. setTimeMethods();
  1651. return defaultOptions;
  1652. }
  1653. /**
  1654. * Get the updated default options. Merely exposing defaultOptions for outside modules
  1655. * isn't enough because the setOptions method creates a new object.
  1656. */
  1657. function getOptions() {
  1658. return defaultOptions;
  1659. }
  1660. /**
  1661. * Handle color operations. The object methods are chainable.
  1662. * @param {String} input The input color in either rbga or hex format
  1663. */
  1664. var Color = function (input) {
  1665. // declare variables
  1666. var rgba = [], result, stops;
  1667. /**
  1668. * Parse the input color to rgba array
  1669. * @param {String} input
  1670. */
  1671. function init(input) {
  1672. // Gradients
  1673. if (input && input.stops) {
  1674. stops = map(input.stops, function (stop) {
  1675. return Color(stop[1]);
  1676. });
  1677. // Solid colors
  1678. } else {
  1679. // rgba
  1680. result = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/.exec(input);
  1681. if (result) {
  1682. rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)];
  1683. } else {
  1684. // hex
  1685. result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(input);
  1686. if (result) {
  1687. rgba = [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1];
  1688. } else {
  1689. // rgb
  1690. result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(input);
  1691. if (result) {
  1692. rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1];
  1693. }
  1694. }
  1695. }
  1696. }
  1697. }
  1698. /**
  1699. * Return the color a specified format
  1700. * @param {String} format
  1701. */
  1702. function get(format) {
  1703. var ret;
  1704. if (stops) {
  1705. ret = merge(input);
  1706. ret.stops = [].concat(ret.stops);
  1707. each(stops, function (stop, i) {
  1708. ret.stops[i] = [ret.stops[i][0], stop.get(format)];
  1709. });
  1710. // it's NaN if gradient colors on a column chart
  1711. } else if (rgba && !isNaN(rgba[0])) {
  1712. if (format === 'rgb') {
  1713. ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')';
  1714. } else if (format === 'a') {
  1715. ret = rgba[3];
  1716. } else {
  1717. ret = 'rgba(' + rgba.join(',') + ')';
  1718. }
  1719. } else {
  1720. ret = input;
  1721. }
  1722. return ret;
  1723. }
  1724. /**
  1725. * Brighten the color
  1726. * @param {Number} alpha
  1727. */
  1728. function brighten(alpha) {
  1729. if (stops) {
  1730. each(stops, function (stop) {
  1731. stop.brighten(alpha);
  1732. });
  1733. } else if (isNumber(alpha) && alpha !== 0) {
  1734. var i;
  1735. for (i = 0; i < 3; i++) {
  1736. rgba[i] += pInt(alpha * 255);
  1737. if (rgba[i] < 0) {
  1738. rgba[i] = 0;
  1739. }
  1740. if (rgba[i] > 255) {
  1741. rgba[i] = 255;
  1742. }
  1743. }
  1744. }
  1745. return this;
  1746. }
  1747. /**
  1748. * Set the color's opacity to a given alpha value
  1749. * @param {Number} alpha
  1750. */
  1751. function setOpacity(alpha) {
  1752. rgba[3] = alpha;
  1753. return this;
  1754. }
  1755. // initialize: parse the input
  1756. init(input);
  1757. // public methods
  1758. return {
  1759. get: get,
  1760. brighten: brighten,
  1761. rgba: rgba,
  1762. setOpacity: setOpacity
  1763. };
  1764. };
  1765. /**
  1766. * A wrapper object for SVG elements
  1767. */
  1768. function SVGElement() {}
  1769. SVGElement.prototype = {
  1770. /**
  1771. * Initialize the SVG renderer
  1772. * @param {Object} renderer
  1773. * @param {String} nodeName
  1774. */
  1775. init: function (renderer, nodeName) {
  1776. var wrapper = this;
  1777. wrapper.element = nodeName === 'span' ?
  1778. createElement(nodeName) :
  1779. doc.createElementNS(SVG_NS, nodeName);
  1780. wrapper.renderer = renderer;
  1781. /**
  1782. * A collection of attribute setters. These methods, if defined, are called right before a certain
  1783. * attribute is set on an element wrapper. Returning false prevents the default attribute
  1784. * setter to run. Returning a value causes the default setter to set that value. Used in
  1785. * Renderer.label.
  1786. */
  1787. wrapper.attrSetters = {};
  1788. },
  1789. /**
  1790. * Default base for animation
  1791. */
  1792. opacity: 1,
  1793. /**
  1794. * Animate a given attribute
  1795. * @param {Object} params
  1796. * @param {Number} options The same options as in jQuery animation
  1797. * @param {Function} complete Function to perform at the end of animation
  1798. */
  1799. animate: function (params, options, complete) {
  1800. var animOptions = pick(options, globalAnimation, true);
  1801. stop(this); // stop regardless of animation actually running, or reverting to .attr (#607)
  1802. if (animOptions) {
  1803. animOptions = merge(animOptions);
  1804. if (complete) { // allows using a callback with the global animation without overwriting it
  1805. animOptions.complete = complete;
  1806. }
  1807. animate(this, params, animOptions);
  1808. } else {
  1809. this.attr(params);
  1810. if (complete) {
  1811. complete();
  1812. }
  1813. }
  1814. },
  1815. /**
  1816. * Set or get a given attribute
  1817. * @param {Object|String} hash
  1818. * @param {Mixed|Undefined} val
  1819. */
  1820. attr: function (hash, val) {
  1821. var wrapper = this,
  1822. key,
  1823. value,
  1824. result,
  1825. i,
  1826. child,
  1827. element = wrapper.element,
  1828. nodeName = element.nodeName.toLowerCase(), // Android2 requires lower for "text"
  1829. renderer = wrapper.renderer,
  1830. skipAttr,
  1831. titleNode,
  1832. attrSetters = wrapper.attrSetters,
  1833. shadows = wrapper.shadows,
  1834. hasSetSymbolSize,
  1835. doTransform,
  1836. ret = wrapper;
  1837. // single key-value pair
  1838. if (isString(hash) && defined(val)) {
  1839. key = hash;
  1840. hash = {};
  1841. hash[key] = val;
  1842. }
  1843. // used as a getter: first argument is a string, second is undefined
  1844. if (isString(hash)) {
  1845. key = hash;
  1846. if (nodeName === 'circle') {
  1847. key = { x: 'cx', y: 'cy' }[key] || key;
  1848. } else if (key === 'strokeWidth') {
  1849. key = 'stroke-width';
  1850. }
  1851. ret = attr(element, key) || wrapper[key] || 0;
  1852. if (key !== 'd' && key !== 'visibility' && key !== 'fill') { // 'd' is string in animation step
  1853. ret = parseFloat(ret);
  1854. }
  1855. // setter
  1856. } else {
  1857. for (key in hash) {
  1858. skipAttr = false; // reset
  1859. value = hash[key];
  1860. // check for a specific attribute setter
  1861. result = attrSetters[key] && attrSetters[key].call(wrapper, value, key);
  1862. if (result !== false) {
  1863. if (result !== UNDEFINED) {
  1864. value = result; // the attribute setter has returned a new value to set
  1865. }
  1866. // paths
  1867. if (key === 'd') {
  1868. if (value && value.join) { // join path
  1869. value = value.join(' ');
  1870. }
  1871. if (/(NaN| {2}|^$)/.test(value)) {
  1872. value = 'M 0 0';
  1873. }
  1874. //wrapper.d = value; // shortcut for animations
  1875. // update child tspans x values
  1876. } else if (key === 'x' && nodeName === 'text') {
  1877. for (i = 0; i < element.childNodes.length; i++) {
  1878. child = element.childNodes[i];
  1879. // if the x values are equal, the tspan represents a linebreak
  1880. if (attr(child, 'x') === attr(element, 'x')) {
  1881. //child.setAttribute('x', value);
  1882. attr(child, 'x', value);
  1883. }
  1884. }
  1885. } else if (wrapper.rotation && (key === 'x' || key === 'y')) {
  1886. doTransform = true;
  1887. // apply gradients
  1888. } else if (key === 'fill') {
  1889. value = renderer.color(value, element, key);
  1890. // circle x and y
  1891. } else if (nodeName === 'circle' && (key === 'x' || key === 'y')) {
  1892. key = { x: 'cx', y: 'cy' }[key] || key;
  1893. // rectangle border radius
  1894. } else if (nodeName === 'rect' && key === 'r') {
  1895. attr(element, {
  1896. rx: value,
  1897. ry: value
  1898. });
  1899. skipAttr = true;
  1900. // translation and text rotation
  1901. } else if (key === 'translateX' || key === 'translateY' || key === 'rotation' ||
  1902. key === 'verticalAlign' || key === 'scaleX' || key === 'scaleY') {
  1903. doTransform = true;
  1904. skipAttr = true;
  1905. // apply opacity as subnode (required by legacy WebKit and Batik)
  1906. } else if (key === 'stroke') {
  1907. value = renderer.color(value, element, key);
  1908. // emulate VML's dashstyle implementation
  1909. } else if (key === 'dashstyle') {
  1910. key = 'stroke-dasharray';
  1911. value = value && value.toLowerCase();
  1912. if (value === 'solid') {
  1913. value = NONE;
  1914. } else if (value) {
  1915. value = value
  1916. .replace('shortdashdotdot', '3,1,1,1,1,1,')
  1917. .replace('shortdashdot', '3,1,1,1')
  1918. .replace('shortdot', '1,1,')
  1919. .replace('shortdash', '3,1,')
  1920. .replace('longdash', '8,3,')
  1921. .replace(/dot/g, '1,3,')
  1922. .replace('dash', '4,3,')
  1923. .replace(/,$/, '')
  1924. .split(','); // ending comma
  1925. i = value.length;
  1926. while (i--) {
  1927. value[i] = pInt(value[i]) * pick(hash['stroke-width'], wrapper['stroke-width']);
  1928. }
  1929. value = value.join(',');
  1930. }
  1931. // IE9/MooTools combo: MooTools returns objects instead of numbers and IE9 Beta 2
  1932. // is unable to cast them. Test again with final IE9.
  1933. } else if (key === 'width') {
  1934. value = pInt(value);
  1935. // Text alignment
  1936. } else if (key === 'align') {
  1937. key = 'text-anchor';
  1938. value = { left: 'start', center: 'middle', right: 'end' }[value];
  1939. // Title requires a subnode, #431
  1940. } else if (key === 'title') {
  1941. titleNode = element.getElementsByTagName('title')[0];
  1942. if (!titleNode) {
  1943. titleNode = doc.createElementNS(SVG_NS, 'title');
  1944. element.appendChild(titleNode);
  1945. }
  1946. titleNode.textContent = value;
  1947. }
  1948. // jQuery animate changes case
  1949. if (key === 'strokeWidth') {
  1950. key = 'stroke-width';
  1951. }
  1952. // In Chrome/Win < 6 as well as Batik, the stroke attribute can't be set when the stroke-
  1953. // width is 0. #1369
  1954. if (key === 'stroke-width' || key === 'stroke') {
  1955. wrapper[key] = value;
  1956. // Only apply the stroke attribute if the stroke width is defined and larger than 0
  1957. if (wrapper.stroke && wrapper['stroke-width']) {
  1958. attr(element, 'stroke', wrapper.stroke);
  1959. attr(element, 'stroke-width', wrapper['stroke-width']);
  1960. wrapper.hasStroke = true;
  1961. } else if (key === 'stroke-width' && value === 0 && wrapper.hasStroke) {
  1962. element.removeAttribute('stroke');
  1963. wrapper.hasStroke = false;
  1964. }
  1965. skipAttr = true;
  1966. }
  1967. // symbols
  1968. if (wrapper.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) {
  1969. if (!hasSetSymbolSize) {
  1970. wrapper.symbolAttr(hash);
  1971. hasSetSymbolSize = true;
  1972. }
  1973. skipAttr = true;
  1974. }
  1975. // let the shadow follow the main element
  1976. if (shadows && /^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(key)) {
  1977. i = shadows.length;
  1978. while (i--) {
  1979. attr(
  1980. shadows[i],
  1981. key,
  1982. key === 'height' ?
  1983. mathMax(value - (shadows[i].cutHeight || 0), 0) :
  1984. value
  1985. );
  1986. }
  1987. }
  1988. // validate heights
  1989. if ((key === 'width' || key === 'height') && nodeName === 'rect' && value < 0) {
  1990. value = 0;
  1991. }
  1992. // Record for animation and quick access without polling the DOM
  1993. wrapper[key] = value;
  1994. if (key === 'text') {
  1995. // Delete bBox memo when the text changes
  1996. if (value !== wrapper.textStr) {
  1997. delete wrapper.bBox;
  1998. }
  1999. wrapper.textStr = value;
  2000. if (wrapper.added) {
  2001. renderer.buildText(wrapper);
  2002. }
  2003. } else if (!skipAttr) {
  2004. attr(element, key, value);
  2005. }
  2006. }
  2007. }
  2008. // Update transform. Do this outside the loop to prevent redundant updating for batch setting
  2009. // of attributes.
  2010. if (doTransform) {
  2011. wrapper.updateTransform();
  2012. }
  2013. }
  2014. return ret;
  2015. },
  2016. /**
  2017. * Add a class name to an element
  2018. */
  2019. addClass: function (className) {
  2020. var element = this.element,
  2021. currentClassName = attr(element, 'class') || '';
  2022. if (currentClassName.indexOf(className) === -1) {
  2023. attr(element, 'class', currentClassName + ' ' + className);
  2024. }
  2025. return this;
  2026. },
  2027. /* hasClass and removeClass are not (yet) needed
  2028. hasClass: function (className) {
  2029. return attr(this.element, 'class').indexOf(className) !== -1;
  2030. },
  2031. removeClass: function (className) {
  2032. attr(this.element, 'class', attr(this.element, 'class').replace(className, ''));
  2033. return this;
  2034. },
  2035. */
  2036. /**
  2037. * If one of the symbol size affecting parameters are changed,
  2038. * check all the others only once for each call to an element's
  2039. * .attr() method
  2040. * @param {Object} hash
  2041. */
  2042. symbolAttr: function (hash) {
  2043. var wrapper = this;
  2044. each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function (key) {
  2045. wrapper[key] = pick(hash[key], wrapper[key]);
  2046. });
  2047. wrapper.attr({
  2048. d: wrapper.renderer.symbols[wrapper.symbolName](
  2049. wrapper.x,
  2050. wrapper.y,
  2051. wrapper.width,
  2052. wrapper.height,
  2053. wrapper
  2054. )
  2055. });
  2056. },
  2057. /**
  2058. * Apply a clipping path to this object
  2059. * @param {String} id
  2060. */
  2061. clip: function (clipRect) {
  2062. return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : NONE);
  2063. },
  2064. /**
  2065. * Calculate the coordinates needed for drawing a rectangle crisply and return the
  2066. * calculated attributes
  2067. * @param {Number} strokeWidth
  2068. * @param {Number} x
  2069. * @param {Number} y
  2070. * @param {Number} width
  2071. * @param {Number} height
  2072. */
  2073. crisp: function (strokeWidth, x, y, width, height) {
  2074. var wrapper = this,
  2075. key,
  2076. attribs = {},
  2077. values = {},
  2078. normalizer;
  2079. strokeWidth = strokeWidth || wrapper.strokeWidth || (wrapper.attr && wrapper.attr('stroke-width')) || 0;
  2080. normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors
  2081. // normalize for crisp edges
  2082. values.x = mathFloor(x || wrapper.x || 0) + normalizer;
  2083. values.y = mathFloor(y || wrapper.y || 0) + normalizer;
  2084. values.width = mathFloor((width || wrapper.width || 0) - 2 * normalizer);
  2085. values.height = mathFloor((height || wrapper.height || 0) - 2 * normalizer);
  2086. values.strokeWidth = strokeWidth;
  2087. for (key in values) {
  2088. if (wrapper[key] !== values[key]) { // only set attribute if changed
  2089. wrapper[key] = attribs[key] = values[key];
  2090. }
  2091. }
  2092. return attribs;
  2093. },
  2094. /**
  2095. * Set styles for the element
  2096. * @param {Object} styles
  2097. */
  2098. css: function (styles) {
  2099. /*jslint unparam: true*//* allow unused param a in the regexp function below */
  2100. var elemWrapper = this,
  2101. elem = elemWrapper.element,
  2102. textWidth = styles && styles.width && elem.nodeName.toLowerCase() === 'text',
  2103. n,
  2104. serializedCss = '',
  2105. hyphenate = function (a, b) { return '-' + b.toLowerCase(); };
  2106. /*jslint unparam: false*/
  2107. // convert legacy
  2108. if (styles && styles.color) {
  2109. styles.fill = styles.color;
  2110. }
  2111. // Merge the new styles with the old ones
  2112. styles = extend(
  2113. elemWrapper.styles,
  2114. styles
  2115. );
  2116. // store object
  2117. elemWrapper.styles = styles;
  2118. // Don't handle line wrap on canvas
  2119. if (useCanVG && textWidth) {
  2120. delete styles.width;
  2121. }
  2122. // serialize and set style attribute
  2123. if (isIE && !hasSVG) { // legacy IE doesn't support setting style attribute
  2124. if (textWidth) {
  2125. delete styles.width;
  2126. }
  2127. css(elemWrapper.element, styles);
  2128. } else {
  2129. for (n in styles) {
  2130. serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';';
  2131. }
  2132. attr(elem, 'style', serializedCss); // #1881
  2133. }
  2134. // re-build text
  2135. if (textWidth && elemWrapper.added) {
  2136. elemWrapper.renderer.buildText(elemWrapper);
  2137. }
  2138. return elemWrapper;
  2139. },
  2140. /**
  2141. * Add an event listener
  2142. * @param {String} eventType
  2143. * @param {Function} handler
  2144. */
  2145. on: function (eventType, handler) {
  2146. var svgElement = this,
  2147. element = svgElement.element;
  2148. // touch
  2149. if (hasTouch && eventType === 'click') {
  2150. element.ontouchstart = function (e) {
  2151. svgElement.touchEventFired = Date.now();
  2152. e.preventDefault();
  2153. handler.call(element, e);
  2154. };
  2155. element.onclick = function (e) {
  2156. if (userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { // #2269
  2157. handler.call(element, e);
  2158. }
  2159. };
  2160. } else {
  2161. // simplest possible event model for internal use
  2162. element['on' + eventType] = handler;
  2163. }
  2164. return this;
  2165. },
  2166. /**
  2167. * Set the coordinates needed to draw a consistent radial gradient across
  2168. * pie slices regardless of positioning inside the chart. The format is
  2169. * [centerX, centerY, diameter] in pixels.
  2170. */
  2171. setRadialReference: function (coordinates) {
  2172. this.element.radialReference = coordinates;
  2173. return this;
  2174. },
  2175. /**
  2176. * Move an object and its children by x and y values
  2177. * @param {Number} x
  2178. * @param {Number} y
  2179. */
  2180. translate: function (x, y) {
  2181. return this.attr({
  2182. translateX: x,
  2183. translateY: y
  2184. });
  2185. },
  2186. /**
  2187. * Invert a group, rotate and flip
  2188. */
  2189. invert: function () {
  2190. var wrapper = this;
  2191. wrapper.inverted = true;
  2192. wrapper.updateTransform();
  2193. return wrapper;
  2194. },
  2195. /**
  2196. * Apply CSS to HTML elements. This is used in text within SVG rendering and
  2197. * by the VML renderer
  2198. */
  2199. htmlCss: function (styles) {
  2200. var wrapper = this,
  2201. element = wrapper.element,
  2202. textWidth = styles && element.tagName === 'SPAN' && styles.width;
  2203. if (textWidth) {
  2204. delete styles.width;
  2205. wrapper.textWidth = textWidth;
  2206. wrapper.updateTransform();
  2207. }
  2208. wrapper.styles = extend(wrapper.styles, styles);
  2209. css(wrapper.element, styles);
  2210. return wrapper;
  2211. },
  2212. /**
  2213. * VML and useHTML method for calculating the bounding box based on offsets
  2214. * @param {Boolean} refresh Whether to force a fresh value from the DOM or to
  2215. * use the cached value
  2216. *
  2217. * @return {Object} A hash containing values for x, y, width and height
  2218. */
  2219. htmlGetBBox: function () {
  2220. var wrapper = this,
  2221. element = wrapper.element,
  2222. bBox = wrapper.bBox;
  2223. // faking getBBox in exported SVG in legacy IE
  2224. if (!bBox) {
  2225. // faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?)
  2226. if (element.nodeName === 'text') {
  2227. element.style.position = ABSOLUTE;
  2228. }
  2229. bBox = wrapper.bBox = {
  2230. x: element.offsetLeft,
  2231. y: element.offsetTop,
  2232. width: element.offsetWidth,
  2233. height: element.offsetHeight
  2234. };
  2235. }
  2236. return bBox;
  2237. },
  2238. /**
  2239. * VML override private method to update elements based on internal
  2240. * properties based on SVG transform
  2241. */
  2242. htmlUpdateTransform: function () {
  2243. // aligning non added elements is expensive
  2244. if (!this.added) {
  2245. this.alignOnAdd = true;
  2246. return;
  2247. }
  2248. var wrapper = this,
  2249. renderer = wrapper.renderer,
  2250. elem = wrapper.element,
  2251. translateX = wrapper.translateX || 0,
  2252. translateY = wrapper.translateY || 0,
  2253. x = wrapper.x || 0,
  2254. y = wrapper.y || 0,
  2255. align = wrapper.textAlign || 'left',
  2256. alignCorrection = { left: 0, center: 0.5, right: 1 }[align],
  2257. nonLeft = align && align !== 'left',
  2258. shadows = wrapper.shadows;
  2259. // apply translate
  2260. css(elem, {
  2261. marginLeft: translateX,
  2262. marginTop: translateY
  2263. });
  2264. if (shadows) { // used in labels/tooltip
  2265. each(shadows, function (shadow) {
  2266. css(shadow, {
  2267. marginLeft: translateX + 1,
  2268. marginTop: translateY + 1
  2269. });
  2270. });
  2271. }
  2272. // apply inversion
  2273. if (wrapper.inverted) { // wrapper is a group
  2274. each(elem.childNodes, function (child) {
  2275. renderer.invertChild(child, elem);
  2276. });
  2277. }
  2278. if (elem.tagName === 'SPAN') {
  2279. var width, height,
  2280. rotation = wrapper.rotation,
  2281. baseline,
  2282. radians = 0,
  2283. costheta = 1,
  2284. sintheta = 0,
  2285. quad,
  2286. textWidth = pInt(wrapper.textWidth),
  2287. xCorr = wrapper.xCorr || 0,
  2288. yCorr = wrapper.yCorr || 0,
  2289. currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth].join(',');
  2290. if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed
  2291. if (defined(rotation)) {
  2292. radians = rotation * deg2rad; // deg to rad
  2293. costheta = mathCos(radians);
  2294. sintheta = mathSin(radians);
  2295. wrapper.setSpanRotation(rotation, sintheta, costheta);
  2296. }
  2297. width = pick(wrapper.elemWidth, elem.offsetWidth);
  2298. height = pick(wrapper.elemHeight, elem.offsetHeight);
  2299. // update textWidth
  2300. if (width > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254
  2301. css(elem, {
  2302. width: textWidth + PX,
  2303. display: 'block',
  2304. whiteSpace: 'normal'
  2305. });
  2306. width = textWidth;
  2307. }
  2308. // correct x and y
  2309. baseline = renderer.fontMetrics(elem.style.fontSize).b;
  2310. xCorr = costheta < 0 && -width;
  2311. yCorr = sintheta < 0 && -height;
  2312. // correct for baseline and corners spilling out after rotation
  2313. quad = costheta * sintheta < 0;
  2314. xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection);
  2315. yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1);
  2316. // correct for the length/height of the text
  2317. if (nonLeft) {
  2318. xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1);
  2319. if (rotation) {
  2320. yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1);
  2321. }
  2322. css(elem, {
  2323. textAlign: align
  2324. });
  2325. }
  2326. // reconciliation correction
  2327. wrapper.xCorr = xCorr;
  2328. wrapper.yCorr = yCorr;
  2329. }
  2330. // apply position with correction
  2331. css(elem, {
  2332. left: (x + xCorr) + PX,
  2333. top: (y + yCorr) + PX
  2334. });
  2335. // force reflow in webkit to apply the left and top on useHTML element (#1249)
  2336. if (isWebKit) {
  2337. height = elem.offsetHeight; // assigned to height for JSLint purpose
  2338. }
  2339. // reconciliation current text transform
  2340. wrapper.cTT = currentTextTransform;
  2341. }
  2342. },
  2343. /**
  2344. * Set the rotation of an individual HTML span
  2345. */
  2346. setSpanRotation: function (rotation) {
  2347. var rotationStyle = {},
  2348. cssTransformKey = isIE ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : '';
  2349. rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)';
  2350. css(this.element, rotationStyle);
  2351. },
  2352. /**
  2353. * Private method to update the transform attribute based on internal
  2354. * properties
  2355. */
  2356. updateTransform: function () {
  2357. var wrapper = this,
  2358. translateX = wrapper.translateX || 0,
  2359. translateY = wrapper.translateY || 0,
  2360. scaleX = wrapper.scaleX,
  2361. scaleY = wrapper.scaleY,
  2362. inverted = wrapper.inverted,
  2363. rotation = wrapper.rotation,
  2364. transform;
  2365. // flipping affects translate as adjustment for flipping around the group's axis
  2366. if (inverted) {
  2367. translateX += wrapper.attr('width');
  2368. translateY += wrapper.attr('height');
  2369. }
  2370. // Apply translate. Nearly all transformed elements have translation, so instead
  2371. // of checking for translate = 0, do it always (#1767, #1846).
  2372. transform = ['translate(' + translateX + ',' + translateY + ')'];
  2373. // apply rotation
  2374. if (inverted) {
  2375. transform.push('rotate(90) scale(-1,1)');
  2376. } else if (rotation) { // text rotation
  2377. transform.push('rotate(' + rotation + ' ' + (wrapper.x || 0) + ' ' + (wrapper.y || 0) + ')');
  2378. }
  2379. // apply scale
  2380. if (defined(scaleX) || defined(scaleY)) {
  2381. transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')');
  2382. }
  2383. if (transform.length) {
  2384. attr(wrapper.element, 'transform', transform.join(' '));
  2385. }
  2386. },
  2387. /**
  2388. * Bring the element to the front
  2389. */
  2390. toFront: function () {
  2391. var element = this.element;
  2392. element.parentNode.appendChild(element);
  2393. return this;
  2394. },
  2395. /**
  2396. * Break down alignment options like align, verticalAlign, x and y
  2397. * to x and y relative to the chart.
  2398. *
  2399. * @param {Object} alignOptions
  2400. * @param {Boolean} alignByTranslate
  2401. * @param {String[Object} box The box to align to, needs a width and height. When the
  2402. * box is a string, it refers to an object in the Renderer. For example, when
  2403. * box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height
  2404. * x and y properties.
  2405. *
  2406. */
  2407. align: function (alignOptions, alignByTranslate, box) {
  2408. var align,
  2409. vAlign,
  2410. x,
  2411. y,
  2412. attribs = {},
  2413. alignTo,
  2414. renderer = this.renderer,
  2415. alignedObjects = renderer.alignedObjects;
  2416. // First call on instanciate
  2417. if (alignOptions) {
  2418. this.alignOptions = alignOptions;
  2419. this.alignByTranslate = alignByTranslate;
  2420. if (!box || isString(box)) { // boxes other than renderer handle this internally
  2421. this.alignTo = alignTo = box || 'renderer';
  2422. erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize
  2423. alignedObjects.push(this);
  2424. box = null; // reassign it below
  2425. }
  2426. // When called on resize, no arguments are supplied
  2427. } else {
  2428. alignOptions = this.alignOptions;
  2429. alignByTranslate = this.alignByTranslate;
  2430. alignTo = this.alignTo;
  2431. }
  2432. box = pick(box, renderer[alignTo], renderer);
  2433. // Assign variables
  2434. align = alignOptions.align;
  2435. vAlign = alignOptions.verticalAlign;
  2436. x = (box.x || 0) + (alignOptions.x || 0); // default: left align
  2437. y = (box.y || 0) + (alignOptions.y || 0); // default: top align
  2438. // Align
  2439. if (align === 'right' || align === 'center') {
  2440. x += (box.width - (alignOptions.width || 0)) /
  2441. { right: 1, center: 2 }[align];
  2442. }
  2443. attribs[alignByTranslate ? 'translateX' : 'x'] = mathRound(x);
  2444. // Vertical align
  2445. if (vAlign === 'bottom' || vAlign === 'middle') {
  2446. y += (box.height - (alignOptions.height || 0)) /
  2447. ({ bottom: 1, middle: 2 }[vAlign] || 1);
  2448. }
  2449. attribs[alignByTranslate ? 'translateY' : 'y'] = mathRound(y);
  2450. // Animate only if already placed
  2451. this[this.placed ? 'animate' : 'attr'](attribs);
  2452. this.placed = true;
  2453. this.alignAttr = attribs;
  2454. return this;
  2455. },
  2456. /**
  2457. * Get the bounding box (width, height, x and y) for the element
  2458. */
  2459. getBBox: function () {
  2460. var wrapper = this,
  2461. bBox = wrapper.bBox,
  2462. renderer = wrapper.renderer,
  2463. width,
  2464. height,
  2465. rotation = wrapper.rotation,
  2466. element = wrapper.element,
  2467. styles = wrapper.styles,
  2468. rad = rotation * deg2rad;
  2469. if (!bBox) {
  2470. // SVG elements
  2471. if (element.namespaceURI === SVG_NS || renderer.forExport) {
  2472. try { // Fails in Firefox if the container has display: none.
  2473. bBox = element.getBBox ?
  2474. // SVG: use extend because IE9 is not allowed to change width and height in case
  2475. // of rotation (below)
  2476. extend({}, element.getBBox()) :
  2477. // Canvas renderer and legacy IE in export mode
  2478. {
  2479. width: element.offsetWidth,
  2480. height: element.offsetHeight
  2481. };
  2482. } catch (e) {}
  2483. // If the bBox is not set, the try-catch block above failed. The other condition
  2484. // is for Opera that returns a width of -Infinity on hidden elements.
  2485. if (!bBox || bBox.width < 0) {
  2486. bBox = { width: 0, height: 0 };
  2487. }
  2488. // VML Renderer or useHTML within SVG
  2489. } else {
  2490. bBox = wrapper.htmlGetBBox();
  2491. }
  2492. // True SVG elements as well as HTML elements in modern browsers using the .useHTML option
  2493. // need to compensated for rotation
  2494. if (renderer.isSVG) {
  2495. width = bBox.width;
  2496. height = bBox.height;
  2497. // Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669)
  2498. if (isIE && styles && styles.fontSize === '11px' && height.toPrecision(3) === '22.7') {
  2499. bBox.height = height = 14;
  2500. }
  2501. // Adjust for rotated text
  2502. if (rotation) {
  2503. bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad));
  2504. bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad));
  2505. }
  2506. }
  2507. wrapper.bBox = bBox;
  2508. }
  2509. return bBox;
  2510. },
  2511. /**
  2512. * Show the element
  2513. */
  2514. show: function () {
  2515. return this.attr({ visibility: VISIBLE });
  2516. },
  2517. /**
  2518. * Hide the element
  2519. */
  2520. hide: function () {
  2521. return this.attr({ visibility: HIDDEN });
  2522. },
  2523. fadeOut: function (duration) {
  2524. var elemWrapper = this;
  2525. elemWrapper.animate({
  2526. opacity: 0
  2527. }, {
  2528. duration: duration || 150,
  2529. complete: function () {
  2530. elemWrapper.hide();
  2531. }
  2532. });
  2533. },
  2534. /**
  2535. * Add the element
  2536. * @param {Object|Undefined} parent Can be an element, an element wrapper or undefined
  2537. * to append the element to the renderer.box.
  2538. */
  2539. add: function (parent) {
  2540. var renderer = this.renderer,
  2541. parentWrapper = parent || renderer,
  2542. parentNode = parentWrapper.element || renderer.box,
  2543. childNodes = parentNode.childNodes,
  2544. element = this.element,
  2545. zIndex = attr(element, 'zIndex'),
  2546. otherElement,
  2547. otherZIndex,
  2548. i,
  2549. inserted;
  2550. if (parent) {
  2551. this.parentGroup = parent;
  2552. }
  2553. // mark as inverted
  2554. this.parentInverted = parent && parent.inverted;
  2555. // build formatted text
  2556. if (this.textStr !== undefined) {
  2557. renderer.buildText(this);
  2558. }
  2559. // mark the container as having z indexed children
  2560. if (zIndex) {
  2561. parentWrapper.handleZ = true;
  2562. zIndex = pInt(zIndex);
  2563. }
  2564. // insert according to this and other elements' zIndex
  2565. if (parentWrapper.handleZ) { // this element or any of its siblings has a z index
  2566. for (i = 0; i < childNodes.length; i++) {
  2567. otherElement = childNodes[i];
  2568. otherZIndex = attr(otherElement, 'zIndex');
  2569. if (otherElement !== element && (
  2570. // insert before the first element with a higher zIndex
  2571. pInt(otherZIndex) > zIndex ||
  2572. // if no zIndex given, insert before the first element with a zIndex
  2573. (!defined(zIndex) && defined(otherZIndex))
  2574. )) {
  2575. parentNode.insertBefore(element, otherElement);
  2576. inserted = true;
  2577. break;
  2578. }
  2579. }
  2580. }
  2581. // default: append at the end
  2582. if (!inserted) {
  2583. parentNode.appendChild(element);
  2584. }
  2585. // mark as added
  2586. this.added = true;
  2587. // fire an event for internal hooks
  2588. fireEvent(this, 'add');
  2589. return this;
  2590. },
  2591. /**
  2592. * Removes a child either by removeChild or move to garbageBin.
  2593. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not.
  2594. */
  2595. safeRemoveChild: function (element) {
  2596. var parentNode = element.parentNode;
  2597. if (parentNode) {
  2598. parentNode.removeChild(element);
  2599. }
  2600. },
  2601. /**
  2602. * Destroy the element and element wrapper
  2603. */
  2604. destroy: function () {
  2605. var wrapper = this,
  2606. element = wrapper.element || {},
  2607. shadows = wrapper.shadows,
  2608. parentToClean = wrapper.renderer.isSVG && element.nodeName === 'SPAN' && element.parentNode,
  2609. grandParent,
  2610. key,
  2611. i;
  2612. // remove events
  2613. element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null;
  2614. stop(wrapper); // stop running animations
  2615. if (wrapper.clipPath) {
  2616. wrapper.clipPath = wrapper.clipPath.destroy();
  2617. }
  2618. // Destroy stops in case this is a gradient object
  2619. if (wrapper.stops) {
  2620. for (i = 0; i < wrapper.stops.length; i++) {
  2621. wrapper.stops[i] = wrapper.stops[i].destroy();
  2622. }
  2623. wrapper.stops = null;
  2624. }
  2625. // remove element
  2626. wrapper.safeRemoveChild(element);
  2627. // destroy shadows
  2628. if (shadows) {
  2629. each(shadows, function (shadow) {
  2630. wrapper.safeRemoveChild(shadow);
  2631. });
  2632. }
  2633. // In case of useHTML, clean up empty containers emulating SVG groups (#1960).
  2634. while (parentToClean && parentToClean.childNodes.length === 0) {
  2635. grandParent = parentToClean.parentNode;
  2636. wrapper.safeRemoveChild(parentToClean);
  2637. parentToClean = grandParent;
  2638. }
  2639. // remove from alignObjects
  2640. if (wrapper.alignTo) {
  2641. erase(wrapper.renderer.alignedObjects, wrapper);
  2642. }
  2643. for (key in wrapper) {
  2644. delete wrapper[key];
  2645. }
  2646. return null;
  2647. },
  2648. /**
  2649. * Add a shadow to the element. Must be done after the element is added to the DOM
  2650. * @param {Boolean|Object} shadowOptions
  2651. */
  2652. shadow: function (shadowOptions, group, cutOff) {
  2653. var shadows = [],
  2654. i,
  2655. shadow,
  2656. element = this.element,
  2657. strokeWidth,
  2658. shadowWidth,
  2659. shadowElementOpacity,
  2660. // compensate for inverted plot area
  2661. transform;
  2662. if (shadowOptions) {
  2663. shadowWidth = pick(shadowOptions.width, 3);
  2664. shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth;
  2665. transform = this.parentInverted ?
  2666. '(-1,-1)' :
  2667. '(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')';
  2668. for (i = 1; i <= shadowWidth; i++) {
  2669. shadow = element.cloneNode(0);
  2670. strokeWidth = (shadowWidth * 2) + 1 - (2 * i);
  2671. attr(shadow, {
  2672. 'isShadow': 'true',
  2673. 'stroke': shadowOptions.color || 'black',
  2674. 'stroke-opacity': shadowElementOpacity * i,
  2675. 'stroke-width': strokeWidth,
  2676. 'transform': 'translate' + transform,
  2677. 'fill': NONE
  2678. });
  2679. if (cutOff) {
  2680. attr(shadow, 'height', mathMax(attr(shadow, 'height') - strokeWidth, 0));
  2681. shadow.cutHeight = strokeWidth;
  2682. }
  2683. if (group) {
  2684. group.element.appendChild(shadow);
  2685. } else {
  2686. element.parentNode.insertBefore(shadow, element);
  2687. }
  2688. shadows.push(shadow);
  2689. }
  2690. this.shadows = shadows;
  2691. }
  2692. return this;
  2693. }
  2694. };
  2695. /**
  2696. * The default SVG renderer
  2697. */
  2698. var SVGRenderer = function () {
  2699. this.init.apply(this, arguments);
  2700. };
  2701. SVGRenderer.prototype = {
  2702. Element: SVGElement,
  2703. /**
  2704. * Initialize the SVGRenderer
  2705. * @param {Object} container
  2706. * @param {Number} width
  2707. * @param {Number} height
  2708. * @param {Boolean} forExport
  2709. */
  2710. init: function (container, width, height, forExport) {
  2711. var renderer = this,
  2712. loc = location,
  2713. boxWrapper,
  2714. element,
  2715. desc;
  2716. boxWrapper = renderer.createElement('svg')
  2717. .attr({
  2718. version: '1.1'
  2719. });
  2720. element = boxWrapper.element;
  2721. container.appendChild(element);
  2722. // For browsers other than IE, add the namespace attribute (#1978)
  2723. if (container.innerHTML.indexOf('xmlns') === -1) {
  2724. attr(element, 'xmlns', SVG_NS);
  2725. }
  2726. // object properties
  2727. renderer.isSVG = true;
  2728. renderer.box = element;
  2729. renderer.boxWrapper = boxWrapper;
  2730. renderer.alignedObjects = [];
  2731. // Page url used for internal references. #24, #672, #1070
  2732. renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ?
  2733. loc.href
  2734. .replace(/#.*?$/, '') // remove the hash
  2735. .replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes
  2736. .replace(/ /g, '%20') : // replace spaces (needed for Safari only)
  2737. '';
  2738. // Add description
  2739. desc = this.createElement('desc').add();
  2740. desc.element.appendChild(doc.createTextNode('Created with ' + PRODUCT + ' ' + VERSION));
  2741. renderer.defs = this.createElement('defs').add();
  2742. renderer.forExport = forExport;
  2743. renderer.gradients = {}; // Object where gradient SvgElements are stored
  2744. renderer.setSize(width, height, false);
  2745. // Issue 110 workaround:
  2746. // In Firefox, if a div is positioned by percentage, its pixel position may land
  2747. // between pixels. The container itself doesn't display this, but an SVG element
  2748. // inside this container will be drawn at subpixel precision. In order to draw
  2749. // sharp lines, this must be compensated for. This doesn't seem to work inside
  2750. // iframes though (like in jsFiddle).
  2751. var subPixelFix, rect;
  2752. if (isFirefox && container.getBoundingClientRect) {
  2753. renderer.subPixelFix = subPixelFix = function () {
  2754. css(container, { left: 0, top: 0 });
  2755. rect = container.getBoundingClientRect();
  2756. css(container, {
  2757. left: (mathCeil(rect.left) - rect.left) + PX,
  2758. top: (mathCeil(rect.top) - rect.top) + PX
  2759. });
  2760. };
  2761. // run the fix now
  2762. subPixelFix();
  2763. // run it on resize
  2764. addEvent(win, 'resize', subPixelFix);
  2765. }
  2766. },
  2767. /**
  2768. * Detect whether the renderer is hidden. This happens when one of the parent elements
  2769. * has display: none. #608.
  2770. */
  2771. isHidden: function () {
  2772. return !this.boxWrapper.getBBox().width;
  2773. },
  2774. /**
  2775. * Destroys the renderer and its allocated members.
  2776. */
  2777. destroy: function () {
  2778. var renderer = this,
  2779. rendererDefs = renderer.defs;
  2780. renderer.box = null;
  2781. renderer.boxWrapper = renderer.boxWrapper.destroy();
  2782. // Call destroy on all gradient elements
  2783. destroyObjectProperties(renderer.gradients || {});
  2784. renderer.gradients = null;
  2785. // Defs are null in VMLRenderer
  2786. // Otherwise, destroy them here.
  2787. if (rendererDefs) {
  2788. renderer.defs = rendererDefs.destroy();
  2789. }
  2790. // Remove sub pixel fix handler
  2791. // We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed
  2792. // See issue #982
  2793. if (renderer.subPixelFix) {
  2794. removeEvent(win, 'resize', renderer.subPixelFix);
  2795. }
  2796. renderer.alignedObjects = null;
  2797. return null;
  2798. },
  2799. /**
  2800. * Create a wrapper for an SVG element
  2801. * @param {Object} nodeName
  2802. */
  2803. createElement: function (nodeName) {
  2804. var wrapper = new this.Element();
  2805. wrapper.init(this, nodeName);
  2806. return wrapper;
  2807. },
  2808. /**
  2809. * Dummy function for use in canvas renderer
  2810. */
  2811. draw: function () {},
  2812. /**
  2813. * Parse a simple HTML string into SVG tspans
  2814. *
  2815. * @param {Object} textNode The parent text SVG node
  2816. */
  2817. buildText: function (wrapper) {
  2818. var textNode = wrapper.element,
  2819. renderer = this,
  2820. forExport = renderer.forExport,
  2821. lines = pick(wrapper.textStr, '').toString()
  2822. .replace(/<(b|strong)>/g, '<span style="font-weight:bold">')
  2823. .replace(/<(i|em)>/g, '<span style="font-style:italic">')
  2824. .replace(/<a/g, '<span')
  2825. .replace(/<\/(b|strong|i|em|a)>/g, '</span>')
  2826. .split(/<br.*?>/g),
  2827. childNodes = textNode.childNodes,
  2828. styleRegex = /style="([^"]+)"/,
  2829. hrefRegex = /href="(http[^"]+)"/,
  2830. parentX = attr(textNode, 'x'),
  2831. textStyles = wrapper.styles,
  2832. width = textStyles && textStyles.width && pInt(textStyles.width),
  2833. textLineHeight = textStyles && textStyles.lineHeight,
  2834. i = childNodes.length;
  2835. /// remove old text
  2836. while (i--) {
  2837. textNode.removeChild(childNodes[i]);
  2838. }
  2839. if (width && !wrapper.added) {
  2840. this.box.appendChild(textNode); // attach it to the DOM to read offset width
  2841. }
  2842. // remove empty line at end
  2843. if (lines[lines.length - 1] === '') {
  2844. lines.pop();
  2845. }
  2846. // build the lines
  2847. each(lines, function (line, lineNo) {
  2848. var spans, spanNo = 0;
  2849. line = line.replace(/<span/g, '|||<span').replace(/<\/span>/g, '</span>|||');
  2850. spans = line.split('|||');
  2851. each(spans, function (span) {
  2852. if (span !== '' || spans.length === 1) {
  2853. var attributes = {},
  2854. tspan = doc.createElementNS(SVG_NS, 'tspan'),
  2855. spanStyle; // #390
  2856. if (styleRegex.test(span)) {
  2857. spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2');
  2858. attr(tspan, 'style', spanStyle);
  2859. }
  2860. if (hrefRegex.test(span) && !forExport) { // Not for export - #1529
  2861. attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"');
  2862. css(tspan, { cursor: 'pointer' });
  2863. }
  2864. span = (span.replace(/<(.|\n)*?>/g, '') || ' ')
  2865. .replace(/&lt;/g, '<')
  2866. .replace(/&gt;/g, '>');
  2867. // Nested tags aren't supported, and cause crash in Safari (#1596)
  2868. if (span !== ' ') {
  2869. // add the text node
  2870. tspan.appendChild(doc.createTextNode(span));
  2871. if (!spanNo) { // first span in a line, align it to the left
  2872. attributes.x = parentX;
  2873. } else {
  2874. attributes.dx = 0; // #16
  2875. }
  2876. // add attributes
  2877. attr(tspan, attributes);
  2878. // first span on subsequent line, add the line height
  2879. if (!spanNo && lineNo) {
  2880. // allow getting the right offset height in exporting in IE
  2881. if (!hasSVG && forExport) {
  2882. css(tspan, { display: 'block' });
  2883. }
  2884. // Set the line height based on the font size of either
  2885. // the text element or the tspan element
  2886. attr(
  2887. tspan,
  2888. 'dy',
  2889. textLineHeight || renderer.fontMetrics(
  2890. /px$/.test(tspan.style.fontSize) ?
  2891. tspan.style.fontSize :
  2892. textStyles.fontSize
  2893. ).h,
  2894. // Safari 6.0.2 - too optimized for its own good (#1539)
  2895. // TODO: revisit this with future versions of Safari
  2896. isWebKit && tspan.offsetHeight
  2897. );
  2898. }
  2899. // Append it
  2900. textNode.appendChild(tspan);
  2901. spanNo++;
  2902. // check width and apply soft breaks
  2903. if (width) {
  2904. var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273
  2905. tooLong,
  2906. actualWidth,
  2907. clipHeight = wrapper._clipHeight,
  2908. rest = [],
  2909. dy = pInt(textLineHeight || 16),
  2910. softLineNo = 1,
  2911. bBox;
  2912. while (words.length || rest.length) {
  2913. delete wrapper.bBox; // delete cache
  2914. bBox = wrapper.getBBox();
  2915. actualWidth = bBox.width;
  2916. tooLong = actualWidth > width;
  2917. if (!tooLong || words.length === 1) { // new line needed
  2918. words = rest;
  2919. rest = [];
  2920. if (words.length) {
  2921. softLineNo++;
  2922. if (clipHeight && softLineNo * dy > clipHeight) {
  2923. words = ['...'];
  2924. wrapper.attr('title', wrapper.textStr);
  2925. } else {
  2926. tspan = doc.createElementNS(SVG_NS, 'tspan');
  2927. attr(tspan, {
  2928. dy: dy,
  2929. x: parentX
  2930. });
  2931. if (spanStyle) { // #390
  2932. attr(tspan, 'style', spanStyle);
  2933. }
  2934. textNode.appendChild(tspan);
  2935. if (actualWidth > width) { // a single word is pressing it out
  2936. width = actualWidth;
  2937. }
  2938. }
  2939. }
  2940. } else { // append to existing line tspan
  2941. tspan.removeChild(tspan.firstChild);
  2942. rest.unshift(words.pop());
  2943. }
  2944. if (words.length) {
  2945. tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-')));
  2946. }
  2947. }
  2948. }
  2949. }
  2950. }
  2951. });
  2952. });
  2953. },
  2954. /**
  2955. * Create a button with preset states
  2956. * @param {String} text
  2957. * @param {Number} x
  2958. * @param {Number} y
  2959. * @param {Function} callback
  2960. * @param {Object} normalState
  2961. * @param {Object} hoverState
  2962. * @param {Object} pressedState
  2963. */
  2964. button: function (text, x, y, callback, normalState, hoverState, pressedState, disabledState) {
  2965. var label = this.label(text, x, y, null, null, null, null, null, 'button'),
  2966. curState = 0,
  2967. stateOptions,
  2968. stateStyle,
  2969. normalStyle,
  2970. hoverStyle,
  2971. pressedStyle,
  2972. disabledStyle,
  2973. STYLE = 'style',
  2974. verticalGradient = { x1: 0, y1: 0, x2: 0, y2: 1 };
  2975. // Normal state - prepare the attributes
  2976. normalState = merge({
  2977. 'stroke-width': 1,
  2978. stroke: '#CCCCCC',
  2979. fill: {
  2980. linearGradient: verticalGradient,
  2981. stops: [
  2982. [0, '#FEFEFE'],
  2983. [1, '#F6F6F6']
  2984. ]
  2985. },
  2986. r: 2,
  2987. padding: 5,
  2988. style: {
  2989. color: 'black'
  2990. }
  2991. }, normalState);
  2992. normalStyle = normalState[STYLE];
  2993. delete normalState[STYLE];
  2994. // Hover state
  2995. hoverState = merge(normalState, {
  2996. stroke: '#68A',
  2997. fill: {
  2998. linearGradient: verticalGradient,
  2999. stops: [
  3000. [0, '#FFF'],
  3001. [1, '#ACF']
  3002. ]
  3003. }
  3004. }, hoverState);
  3005. hoverStyle = hoverState[STYLE];
  3006. delete hoverState[STYLE];
  3007. // Pressed state
  3008. pressedState = merge(normalState, {
  3009. stroke: '#68A',
  3010. fill: {
  3011. linearGradient: verticalGradient,
  3012. stops: [
  3013. [0, '#9BD'],
  3014. [1, '#CDF']
  3015. ]
  3016. }
  3017. }, pressedState);
  3018. pressedStyle = pressedState[STYLE];
  3019. delete pressedState[STYLE];
  3020. // Disabled state
  3021. disabledState = merge(normalState, {
  3022. style: {
  3023. color: '#CCC'
  3024. }
  3025. }, disabledState);
  3026. disabledStyle = disabledState[STYLE];
  3027. delete disabledState[STYLE];
  3028. // Add the events. IE9 and IE10 need mouseover and mouseout to funciton (#667).
  3029. addEvent(label.element, isIE ? 'mouseover' : 'mouseenter', function () {
  3030. if (curState !== 3) {
  3031. label.attr(hoverState)
  3032. .css(hoverStyle);
  3033. }
  3034. });
  3035. addEvent(label.element, isIE ? 'mouseout' : 'mouseleave', function () {
  3036. if (curState !== 3) {
  3037. stateOptions = [normalState, hoverState, pressedState][curState];
  3038. stateStyle = [normalStyle, hoverStyle, pressedStyle][curState];
  3039. label.attr(stateOptions)
  3040. .css(stateStyle);
  3041. }
  3042. });
  3043. label.setState = function (state) {
  3044. label.state = curState = state;
  3045. if (!state) {
  3046. label.attr(normalState)
  3047. .css(normalStyle);
  3048. } else if (state === 2) {
  3049. label.attr(pressedState)
  3050. .css(pressedStyle);
  3051. } else if (state === 3) {
  3052. label.attr(disabledState)
  3053. .css(disabledStyle);
  3054. }
  3055. };
  3056. return label
  3057. .on('click', function () {
  3058. if (curState !== 3) {
  3059. callback.call(label);
  3060. }
  3061. })
  3062. .attr(normalState)
  3063. .css(extend({ cursor: 'default' }, normalStyle));
  3064. },
  3065. /**
  3066. * Make a straight line crisper by not spilling out to neighbour pixels
  3067. * @param {Array} points
  3068. * @param {Number} width
  3069. */
  3070. crispLine: function (points, width) {
  3071. // points format: [M, 0, 0, L, 100, 0]
  3072. // normalize to a crisp line
  3073. if (points[1] === points[4]) {
  3074. // Substract due to #1129. Now bottom and left axis gridlines behave the same.
  3075. points[1] = points[4] = mathRound(points[1]) - (width % 2 / 2);
  3076. }
  3077. if (points[2] === points[5]) {
  3078. points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2);
  3079. }
  3080. return points;
  3081. },
  3082. /**
  3083. * Draw a path
  3084. * @param {Array} path An SVG path in array form
  3085. */
  3086. path: function (path) {
  3087. var attr = {
  3088. fill: NONE
  3089. };
  3090. if (isArray(path)) {
  3091. attr.d = path;
  3092. } else if (isObject(path)) { // attributes
  3093. extend(attr, path);
  3094. }
  3095. return this.createElement('path').attr(attr);
  3096. },
  3097. /**
  3098. * Draw and return an SVG circle
  3099. * @param {Number} x The x position
  3100. * @param {Number} y The y position
  3101. * @param {Number} r The radius
  3102. */
  3103. circle: function (x, y, r) {
  3104. var attr = isObject(x) ?
  3105. x :
  3106. {
  3107. x: x,
  3108. y: y,
  3109. r: r
  3110. };
  3111. return this.createElement('circle').attr(attr);
  3112. },
  3113. /**
  3114. * Draw and return an arc
  3115. * @param {Number} x X position
  3116. * @param {Number} y Y position
  3117. * @param {Number} r Radius
  3118. * @param {Number} innerR Inner radius like used in donut charts
  3119. * @param {Number} start Starting angle
  3120. * @param {Number} end Ending angle
  3121. */
  3122. arc: function (x, y, r, innerR, start, end) {
  3123. var arc;
  3124. if (isObject(x)) {
  3125. y = x.y;
  3126. r = x.r;
  3127. innerR = x.innerR;
  3128. start = x.start;
  3129. end = x.end;
  3130. x = x.x;
  3131. }
  3132. // Arcs are defined as symbols for the ability to set
  3133. // attributes in attr and animate
  3134. arc = this.symbol('arc', x || 0, y || 0, r || 0, r || 0, {
  3135. innerR: innerR || 0,
  3136. start: start || 0,
  3137. end: end || 0
  3138. });
  3139. arc.r = r; // #959
  3140. return arc;
  3141. },
  3142. /**
  3143. * Draw and return a rectangle
  3144. * @param {Number} x Left position
  3145. * @param {Number} y Top position
  3146. * @param {Number} width
  3147. * @param {Number} height
  3148. * @param {Number} r Border corner radius
  3149. * @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing
  3150. */
  3151. rect: function (x, y, width, height, r, strokeWidth) {
  3152. r = isObject(x) ? x.r : r;
  3153. var wrapper = this.createElement('rect').attr({
  3154. rx: r,
  3155. ry: r,
  3156. fill: NONE
  3157. });
  3158. return wrapper.attr(
  3159. isObject(x) ?
  3160. x :
  3161. // do not crispify when an object is passed in (as in column charts)
  3162. wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0))
  3163. );
  3164. },
  3165. /**
  3166. * Resize the box and re-align all aligned elements
  3167. * @param {Object} width
  3168. * @param {Object} height
  3169. * @param {Boolean} animate
  3170. *
  3171. */
  3172. setSize: function (width, height, animate) {
  3173. var renderer = this,
  3174. alignedObjects = renderer.alignedObjects,
  3175. i = alignedObjects.length;
  3176. renderer.width = width;
  3177. renderer.height = height;
  3178. renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({
  3179. width: width,
  3180. height: height
  3181. });
  3182. while (i--) {
  3183. alignedObjects[i].align();
  3184. }
  3185. },
  3186. /**
  3187. * Create a group
  3188. * @param {String} name The group will be given a class name of 'highcharts-{name}'.
  3189. * This can be used for styling and scripting.
  3190. */
  3191. g: function (name) {
  3192. var elem = this.createElement('g');
  3193. return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem;
  3194. },
  3195. /**
  3196. * Display an image
  3197. * @param {String} src
  3198. * @param {Number} x
  3199. * @param {Number} y
  3200. * @param {Number} width
  3201. * @param {Number} height
  3202. */
  3203. image: function (src, x, y, width, height) {
  3204. var attribs = {
  3205. preserveAspectRatio: NONE
  3206. },
  3207. elemWrapper;
  3208. // optional properties
  3209. if (arguments.length > 1) {
  3210. extend(attribs, {
  3211. x: x,
  3212. y: y,
  3213. width: width,
  3214. height: height
  3215. });
  3216. }
  3217. elemWrapper = this.createElement('image').attr(attribs);
  3218. // set the href in the xlink namespace
  3219. if (elemWrapper.element.setAttributeNS) {
  3220. elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink',
  3221. 'href', src);
  3222. } else {
  3223. // could be exporting in IE
  3224. // using href throws "not supported" in ie7 and under, requries regex shim to fix later
  3225. elemWrapper.element.setAttribute('hc-svg-href', src);
  3226. }
  3227. return elemWrapper;
  3228. },
  3229. /**
  3230. * Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object.
  3231. *
  3232. * @param {Object} symbol
  3233. * @param {Object} x
  3234. * @param {Object} y
  3235. * @param {Object} radius
  3236. * @param {Object} options
  3237. */
  3238. symbol: function (symbol, x, y, width, height, options) {
  3239. var obj,
  3240. // get the symbol definition function
  3241. symbolFn = this.symbols[symbol],
  3242. // check if there's a path defined for this symbol
  3243. path = symbolFn && symbolFn(
  3244. mathRound(x),
  3245. mathRound(y),
  3246. width,
  3247. height,
  3248. options
  3249. ),
  3250. imageElement,
  3251. imageRegex = /^url\((.*?)\)$/,
  3252. imageSrc,
  3253. imageSize,
  3254. centerImage;
  3255. if (path) {
  3256. obj = this.path(path);
  3257. // expando properties for use in animate and attr
  3258. extend(obj, {
  3259. symbolName: symbol,
  3260. x: x,
  3261. y: y,
  3262. width: width,
  3263. height: height
  3264. });
  3265. if (options) {
  3266. extend(obj, options);
  3267. }
  3268. // image symbols
  3269. } else if (imageRegex.test(symbol)) {
  3270. // On image load, set the size and position
  3271. centerImage = function (img, size) {
  3272. if (img.element) { // it may be destroyed in the meantime (#1390)
  3273. img.attr({
  3274. width: size[0],
  3275. height: size[1]
  3276. });
  3277. if (!img.alignByTranslate) { // #185
  3278. img.translate(
  3279. mathRound((width - size[0]) / 2), // #1378
  3280. mathRound((height - size[1]) / 2)
  3281. );
  3282. }
  3283. }
  3284. };
  3285. imageSrc = symbol.match(imageRegex)[1];
  3286. imageSize = symbolSizes[imageSrc];
  3287. // Ireate the image synchronously, add attribs async
  3288. obj = this.image(imageSrc)
  3289. .attr({
  3290. x: x,
  3291. y: y
  3292. });
  3293. obj.isImg = true;
  3294. if (imageSize) {
  3295. centerImage(obj, imageSize);
  3296. } else {
  3297. // Initialize image to be 0 size so export will still function if there's no cached sizes.
  3298. //
  3299. obj.attr({ width: 0, height: 0 });
  3300. // Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8,
  3301. // the created element must be assigned to a variable in order to load (#292).
  3302. imageElement = createElement('img', {
  3303. onload: function () {
  3304. centerImage(obj, symbolSizes[imageSrc] = [this.width, this.height]);
  3305. },
  3306. src: imageSrc
  3307. });
  3308. }
  3309. }
  3310. return obj;
  3311. },
  3312. /**
  3313. * An extendable collection of functions for defining symbol paths.
  3314. */
  3315. symbols: {
  3316. 'circle': function (x, y, w, h) {
  3317. var cpw = 0.166 * w;
  3318. return [
  3319. M, x + w / 2, y,
  3320. 'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h,
  3321. 'C', x - cpw, y + h, x - cpw, y, x + w / 2, y,
  3322. 'Z'
  3323. ];
  3324. },
  3325. 'square': function (x, y, w, h) {
  3326. return [
  3327. M, x, y,
  3328. L, x + w, y,
  3329. x + w, y + h,
  3330. x, y + h,
  3331. 'Z'
  3332. ];
  3333. },
  3334. 'triangle': function (x, y, w, h) {
  3335. return [
  3336. M, x + w / 2, y,
  3337. L, x + w, y + h,
  3338. x, y + h,
  3339. 'Z'
  3340. ];
  3341. },
  3342. 'triangle-down': function (x, y, w, h) {
  3343. return [
  3344. M, x, y,
  3345. L, x + w, y,
  3346. x + w / 2, y + h,
  3347. 'Z'
  3348. ];
  3349. },
  3350. 'diamond': function (x, y, w, h) {
  3351. return [
  3352. M, x + w / 2, y,
  3353. L, x + w, y + h / 2,
  3354. x + w / 2, y + h,
  3355. x, y + h / 2,
  3356. 'Z'
  3357. ];
  3358. },
  3359. 'arc': function (x, y, w, h, options) {
  3360. var start = options.start,
  3361. radius = options.r || w || h,
  3362. end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561)
  3363. innerRadius = options.innerR,
  3364. open = options.open,
  3365. cosStart = mathCos(start),
  3366. sinStart = mathSin(start),
  3367. cosEnd = mathCos(end),
  3368. sinEnd = mathSin(end),
  3369. longArc = options.end - start < mathPI ? 0 : 1;
  3370. return [
  3371. M,
  3372. x + radius * cosStart,
  3373. y + radius * sinStart,
  3374. 'A', // arcTo
  3375. radius, // x radius
  3376. radius, // y radius
  3377. 0, // slanting
  3378. longArc, // long or short arc
  3379. 1, // clockwise
  3380. x + radius * cosEnd,
  3381. y + radius * sinEnd,
  3382. open ? M : L,
  3383. x + innerRadius * cosEnd,
  3384. y + innerRadius * sinEnd,
  3385. 'A', // arcTo
  3386. innerRadius, // x radius
  3387. innerRadius, // y radius
  3388. 0, // slanting
  3389. longArc, // long or short arc
  3390. 0, // clockwise
  3391. x + innerRadius * cosStart,
  3392. y + innerRadius * sinStart,
  3393. open ? '' : 'Z' // close
  3394. ];
  3395. }
  3396. },
  3397. /**
  3398. * Define a clipping rectangle
  3399. * @param {String} id
  3400. * @param {Number} x
  3401. * @param {Number} y
  3402. * @param {Number} width
  3403. * @param {Number} height
  3404. */
  3405. clipRect: function (x, y, width, height) {
  3406. var wrapper,
  3407. id = PREFIX + idCounter++,
  3408. clipPath = this.createElement('clipPath').attr({
  3409. id: id
  3410. }).add(this.defs);
  3411. wrapper = this.rect(x, y, width, height, 0).add(clipPath);
  3412. wrapper.id = id;
  3413. wrapper.clipPath = clipPath;
  3414. return wrapper;
  3415. },
  3416. /**
  3417. * Take a color and return it if it's a string, make it a gradient if it's a
  3418. * gradient configuration object. Prior to Highstock, an array was used to define
  3419. * a linear gradient with pixel positions relative to the SVG. In newer versions
  3420. * we change the coordinates to apply relative to the shape, using coordinates
  3421. * 0-1 within the shape. To preserve backwards compatibility, linearGradient
  3422. * in this definition is an object of x1, y1, x2 and y2.
  3423. *
  3424. * @param {Object} color The color or config object
  3425. */
  3426. color: function (color, elem, prop) {
  3427. var renderer = this,
  3428. colorObject,
  3429. regexRgba = /^rgba/,
  3430. gradName,
  3431. gradAttr,
  3432. gradients,
  3433. gradientObject,
  3434. stops,
  3435. stopColor,
  3436. stopOpacity,
  3437. radialReference,
  3438. n,
  3439. id,
  3440. key = [];
  3441. // Apply linear or radial gradients
  3442. if (color && color.linearGradient) {
  3443. gradName = 'linearGradient';
  3444. } else if (color && color.radialGradient) {
  3445. gradName = 'radialGradient';
  3446. }
  3447. if (gradName) {
  3448. gradAttr = color[gradName];
  3449. gradients = renderer.gradients;
  3450. stops = color.stops;
  3451. radialReference = elem.radialReference;
  3452. // Keep < 2.2 kompatibility
  3453. if (isArray(gradAttr)) {
  3454. color[gradName] = gradAttr = {
  3455. x1: gradAttr[0],
  3456. y1: gradAttr[1],
  3457. x2: gradAttr[2],
  3458. y2: gradAttr[3],
  3459. gradientUnits: 'userSpaceOnUse'
  3460. };
  3461. }
  3462. // Correct the radial gradient for the radial reference system
  3463. if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) {
  3464. gradAttr = merge(gradAttr, {
  3465. cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2],
  3466. cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2],
  3467. r: gradAttr.r * radialReference[2],
  3468. gradientUnits: 'userSpaceOnUse'
  3469. });
  3470. }
  3471. // Build the unique key to detect whether we need to create a new element (#1282)
  3472. for (n in gradAttr) {
  3473. if (n !== 'id') {
  3474. key.push(n, gradAttr[n]);
  3475. }
  3476. }
  3477. for (n in stops) {
  3478. key.push(stops[n]);
  3479. }
  3480. key = key.join(',');
  3481. // Check if a gradient object with the same config object is created within this renderer
  3482. if (gradients[key]) {
  3483. id = gradients[key].id;
  3484. } else {
  3485. // Set the id and create the element
  3486. gradAttr.id = id = PREFIX + idCounter++;
  3487. gradients[key] = gradientObject = renderer.createElement(gradName)
  3488. .attr(gradAttr)
  3489. .add(renderer.defs);
  3490. // The gradient needs to keep a list of stops to be able to destroy them
  3491. gradientObject.stops = [];
  3492. each(stops, function (stop) {
  3493. var stopObject;
  3494. if (regexRgba.test(stop[1])) {
  3495. colorObject = Color(stop[1]);
  3496. stopColor = colorObject.get('rgb');
  3497. stopOpacity = colorObject.get('a');
  3498. } else {
  3499. stopColor = stop[1];
  3500. stopOpacity = 1;
  3501. }
  3502. stopObject = renderer.createElement('stop').attr({
  3503. offset: stop[0],
  3504. 'stop-color': stopColor,
  3505. 'stop-opacity': stopOpacity
  3506. }).add(gradientObject);
  3507. // Add the stop element to the gradient
  3508. gradientObject.stops.push(stopObject);
  3509. });
  3510. }
  3511. // Return the reference to the gradient object
  3512. return 'url(' + renderer.url + '#' + id + ')';
  3513. // Webkit and Batik can't show rgba.
  3514. } else if (regexRgba.test(color)) {
  3515. colorObject = Color(color);
  3516. attr(elem, prop + '-opacity', colorObject.get('a'));
  3517. return colorObject.get('rgb');
  3518. } else {
  3519. // Remove the opacity attribute added above. Does not throw if the attribute is not there.
  3520. elem.removeAttribute(prop + '-opacity');
  3521. return color;
  3522. }
  3523. },
  3524. /**
  3525. * Add text to the SVG object
  3526. * @param {String} str
  3527. * @param {Number} x Left position
  3528. * @param {Number} y Top position
  3529. * @param {Boolean} useHTML Use HTML to render the text
  3530. */
  3531. text: function (str, x, y, useHTML) {
  3532. // declare variables
  3533. var renderer = this,
  3534. defaultChartStyle = defaultOptions.chart.style,
  3535. fakeSVG = useCanVG || (!hasSVG && renderer.forExport),
  3536. wrapper;
  3537. if (useHTML && !renderer.forExport) {
  3538. return renderer.html(str, x, y);
  3539. }
  3540. x = mathRound(pick(x, 0));
  3541. y = mathRound(pick(y, 0));
  3542. wrapper = renderer.createElement('text')
  3543. .attr({
  3544. x: x,
  3545. y: y,
  3546. text: str
  3547. })
  3548. .css({
  3549. fontFamily: defaultChartStyle.fontFamily,
  3550. fontSize: defaultChartStyle.fontSize
  3551. });
  3552. // Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063)
  3553. if (fakeSVG) {
  3554. wrapper.css({
  3555. position: ABSOLUTE
  3556. });
  3557. }
  3558. wrapper.x = x;
  3559. wrapper.y = y;
  3560. return wrapper;
  3561. },
  3562. /**
  3563. * Create HTML text node. This is used by the VML renderer as well as the SVG
  3564. * renderer through the useHTML option.
  3565. *
  3566. * @param {String} str
  3567. * @param {Number} x
  3568. * @param {Number} y
  3569. */
  3570. html: function (str, x, y) {
  3571. var defaultChartStyle = defaultOptions.chart.style,
  3572. wrapper = this.createElement('span'),
  3573. attrSetters = wrapper.attrSetters,
  3574. element = wrapper.element,
  3575. renderer = wrapper.renderer;
  3576. // Text setter
  3577. attrSetters.text = function (value) {
  3578. if (value !== element.innerHTML) {
  3579. delete this.bBox;
  3580. }
  3581. element.innerHTML = value;
  3582. return false;
  3583. };
  3584. // Various setters which rely on update transform
  3585. attrSetters.x = attrSetters.y = attrSetters.align = function (value, key) {
  3586. if (key === 'align') {
  3587. key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML.
  3588. }
  3589. wrapper[key] = value;
  3590. wrapper.htmlUpdateTransform();
  3591. return false;
  3592. };
  3593. // Set the default attributes
  3594. wrapper.attr({
  3595. text: str,
  3596. x: mathRound(x),
  3597. y: mathRound(y)
  3598. })
  3599. .css({
  3600. position: ABSOLUTE,
  3601. whiteSpace: 'nowrap',
  3602. fontFamily: defaultChartStyle.fontFamily,
  3603. fontSize: defaultChartStyle.fontSize
  3604. });
  3605. // Use the HTML specific .css method
  3606. wrapper.css = wrapper.htmlCss;
  3607. // This is specific for HTML within SVG
  3608. if (renderer.isSVG) {
  3609. wrapper.add = function (svgGroupWrapper) {
  3610. var htmlGroup,
  3611. container = renderer.box.parentNode,
  3612. parentGroup,
  3613. parents = [];
  3614. // Create a mock group to hold the HTML elements
  3615. if (svgGroupWrapper) {
  3616. htmlGroup = svgGroupWrapper.div;
  3617. if (!htmlGroup) {
  3618. // Read the parent chain into an array and read from top down
  3619. parentGroup = svgGroupWrapper;
  3620. while (parentGroup) {
  3621. parents.push(parentGroup);
  3622. // Move up to the next parent group
  3623. parentGroup = parentGroup.parentGroup;
  3624. }
  3625. // Ensure dynamically updating position when any parent is translated
  3626. each(parents.reverse(), function (parentGroup) {
  3627. var htmlGroupStyle;
  3628. // Create a HTML div and append it to the parent div to emulate
  3629. // the SVG group structure
  3630. htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, {
  3631. className: attr(parentGroup.element, 'class')
  3632. }, {
  3633. position: ABSOLUTE,
  3634. left: (parentGroup.translateX || 0) + PX,
  3635. top: (parentGroup.translateY || 0) + PX
  3636. }, htmlGroup || container); // the top group is appended to container
  3637. // Shortcut
  3638. htmlGroupStyle = htmlGroup.style;
  3639. // Set listeners to update the HTML div's position whenever the SVG group
  3640. // position is changed
  3641. extend(parentGroup.attrSetters, {
  3642. translateX: function (value) {
  3643. htmlGroupStyle.left = value + PX;
  3644. },
  3645. translateY: function (value) {
  3646. htmlGroupStyle.top = value + PX;
  3647. },
  3648. visibility: function (value, key) {
  3649. htmlGroupStyle[key] = value;
  3650. }
  3651. });
  3652. });
  3653. }
  3654. } else {
  3655. htmlGroup = container;
  3656. }
  3657. htmlGroup.appendChild(element);
  3658. // Shared with VML:
  3659. wrapper.added = true;
  3660. if (wrapper.alignOnAdd) {
  3661. wrapper.htmlUpdateTransform();
  3662. }
  3663. return wrapper;
  3664. };
  3665. }
  3666. return wrapper;
  3667. },
  3668. /**
  3669. * Utility to return the baseline offset and total line height from the font size
  3670. */
  3671. fontMetrics: function (fontSize) {
  3672. fontSize = pInt(fontSize || 11);
  3673. // Empirical values found by comparing font size and bounding box height.
  3674. // Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/
  3675. var lineHeight = fontSize < 24 ? fontSize + 4 : mathRound(fontSize * 1.2),
  3676. baseline = mathRound(lineHeight * 0.8);
  3677. return {
  3678. h: lineHeight,
  3679. b: baseline
  3680. };
  3681. },
  3682. /**
  3683. * Add a label, a text item that can hold a colored or gradient background
  3684. * as well as a border and shadow.
  3685. * @param {string} str
  3686. * @param {Number} x
  3687. * @param {Number} y
  3688. * @param {String} shape
  3689. * @param {Number} anchorX In case the shape has a pointer, like a flag, this is the
  3690. * coordinates it should be pinned to
  3691. * @param {Number} anchorY
  3692. * @param {Boolean} baseline Whether to position the label relative to the text baseline,
  3693. * like renderer.text, or to the upper border of the rectangle.
  3694. * @param {String} className Class name for the group
  3695. */
  3696. label: function (str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) {
  3697. var renderer = this,
  3698. wrapper = renderer.g(className),
  3699. text = renderer.text('', 0, 0, useHTML)
  3700. .attr({
  3701. zIndex: 1
  3702. }),
  3703. //.add(wrapper),
  3704. box,
  3705. bBox,
  3706. alignFactor = 0,
  3707. padding = 3,
  3708. paddingLeft = 0,
  3709. width,
  3710. height,
  3711. wrapperX,
  3712. wrapperY,
  3713. crispAdjust = 0,
  3714. deferredAttr = {},
  3715. baselineOffset,
  3716. attrSetters = wrapper.attrSetters,
  3717. needsBox;
  3718. /**
  3719. * This function runs after the label is added to the DOM (when the bounding box is
  3720. * available), and after the text of the label is updated to detect the new bounding
  3721. * box and reflect it in the border box.
  3722. */
  3723. function updateBoxSize() {
  3724. var boxX,
  3725. boxY,
  3726. style = text.element.style;
  3727. bBox = (width === undefined || height === undefined || wrapper.styles.textAlign) &&
  3728. text.getBBox();
  3729. wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft;
  3730. wrapper.height = (height || bBox.height || 0) + 2 * padding;
  3731. // update the label-scoped y offset
  3732. baselineOffset = padding + renderer.fontMetrics(style && style.fontSize).b;
  3733. if (needsBox) {
  3734. // create the border box if it is not already present
  3735. if (!box) {
  3736. boxX = mathRound(-alignFactor * padding);
  3737. boxY = baseline ? -baselineOffset : 0;
  3738. wrapper.box = box = shape ?
  3739. renderer.symbol(shape, boxX, boxY, wrapper.width, wrapper.height) :
  3740. renderer.rect(boxX, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]);
  3741. box.add(wrapper);
  3742. }
  3743. // apply the box attributes
  3744. if (!box.isImg) { // #1630
  3745. box.attr(merge({
  3746. width: wrapper.width,
  3747. height: wrapper.height
  3748. }, deferredAttr));
  3749. }
  3750. deferredAttr = null;
  3751. }
  3752. }
  3753. /**
  3754. * This function runs after setting text or padding, but only if padding is changed
  3755. */
  3756. function updateTextPadding() {
  3757. var styles = wrapper.styles,
  3758. textAlign = styles && styles.textAlign,
  3759. x = paddingLeft + padding * (1 - alignFactor),
  3760. y;
  3761. // determin y based on the baseline
  3762. y = baseline ? 0 : baselineOffset;
  3763. // compensate for alignment
  3764. if (defined(width) && (textAlign === 'center' || textAlign === 'right')) {
  3765. x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width);
  3766. }
  3767. // update if anything changed
  3768. if (x !== text.x || y !== text.y) {
  3769. text.attr({
  3770. x: x,
  3771. y: y
  3772. });
  3773. }
  3774. // reconciliation current values
  3775. text.x = x;
  3776. text.y = y;
  3777. }
  3778. /**
  3779. * Set a box attribute, or defer it if the box is not yet created
  3780. * @param {Object} key
  3781. * @param {Object} value
  3782. */
  3783. function boxAttr(key, value) {
  3784. if (box) {
  3785. box.attr(key, value);
  3786. } else {
  3787. deferredAttr[key] = value;
  3788. }
  3789. }
  3790. function getSizeAfterAdd() {
  3791. text.add(wrapper);
  3792. wrapper.attr({
  3793. text: str, // alignment is available now
  3794. x: x,
  3795. y: y
  3796. });
  3797. if (box && defined(anchorX)) {
  3798. wrapper.attr({
  3799. anchorX: anchorX,
  3800. anchorY: anchorY
  3801. });
  3802. }
  3803. }
  3804. /**
  3805. * After the text element is added, get the desired size of the border box
  3806. * and add it before the text in the DOM.
  3807. */
  3808. addEvent(wrapper, 'add', getSizeAfterAdd);
  3809. /*
  3810. * Add specific attribute setters.
  3811. */
  3812. // only change local variables
  3813. attrSetters.width = function (value) {
  3814. width = value;
  3815. return false;
  3816. };
  3817. attrSetters.height = function (value) {
  3818. height = value;
  3819. return false;
  3820. };
  3821. attrSetters.padding = function (value) {
  3822. if (defined(value) && value !== padding) {
  3823. padding = value;
  3824. updateTextPadding();
  3825. }
  3826. return false;
  3827. };
  3828. attrSetters.paddingLeft = function (value) {
  3829. if (defined(value) && value !== paddingLeft) {
  3830. paddingLeft = value;
  3831. updateTextPadding();
  3832. }
  3833. return false;
  3834. };
  3835. // change local variable and set attribue as well
  3836. attrSetters.align = function (value) {
  3837. alignFactor = { left: 0, center: 0.5, right: 1 }[value];
  3838. return false; // prevent setting text-anchor on the group
  3839. };
  3840. // apply these to the box and the text alike
  3841. attrSetters.text = function (value, key) {
  3842. text.attr(key, value);
  3843. updateBoxSize();
  3844. updateTextPadding();
  3845. return false;
  3846. };
  3847. // apply these to the box but not to the text
  3848. attrSetters[STROKE_WIDTH] = function (value, key) {
  3849. needsBox = true;
  3850. crispAdjust = value % 2 / 2;
  3851. boxAttr(key, value);
  3852. return false;
  3853. };
  3854. attrSetters.stroke = attrSetters.fill = attrSetters.r = function (value, key) {
  3855. if (key === 'fill') {
  3856. needsBox = true;
  3857. }
  3858. boxAttr(key, value);
  3859. return false;
  3860. };
  3861. attrSetters.anchorX = function (value, key) {
  3862. anchorX = value;
  3863. boxAttr(key, value + crispAdjust - wrapperX);
  3864. return false;
  3865. };
  3866. attrSetters.anchorY = function (value, key) {
  3867. anchorY = value;
  3868. boxAttr(key, value - wrapperY);
  3869. return false;
  3870. };
  3871. // rename attributes
  3872. attrSetters.x = function (value) {
  3873. wrapper.x = value; // for animation getter
  3874. value -= alignFactor * ((width || bBox.width) + padding);
  3875. wrapperX = mathRound(value);
  3876. wrapper.attr('translateX', wrapperX);
  3877. return false;
  3878. };
  3879. attrSetters.y = function (value) {
  3880. wrapperY = wrapper.y = mathRound(value);
  3881. wrapper.attr('translateY', wrapperY);
  3882. return false;
  3883. };
  3884. // Redirect certain methods to either the box or the text
  3885. var baseCss = wrapper.css;
  3886. return extend(wrapper, {
  3887. /**
  3888. * Pick up some properties and apply them to the text instead of the wrapper
  3889. */
  3890. css: function (styles) {
  3891. if (styles) {
  3892. var textStyles = {};
  3893. styles = merge(styles); // create a copy to avoid altering the original object (#537)
  3894. each(['fontSize', 'fontWeight', 'fontFamily', 'color', 'lineHeight', 'width', 'textDecoration', 'textShadow'], function (prop) {
  3895. if (styles[prop] !== UNDEFINED) {
  3896. textStyles[prop] = styles[prop];
  3897. delete styles[prop];
  3898. }
  3899. });
  3900. text.css(textStyles);
  3901. }
  3902. return baseCss.call(wrapper, styles);
  3903. },
  3904. /**
  3905. * Return the bounding box of the box, not the group
  3906. */
  3907. getBBox: function () {
  3908. return {
  3909. width: bBox.width + 2 * padding,
  3910. height: bBox.height + 2 * padding,
  3911. x: bBox.x - padding,
  3912. y: bBox.y - padding
  3913. };
  3914. },
  3915. /**
  3916. * Apply the shadow to the box
  3917. */
  3918. shadow: function (b) {
  3919. if (box) {
  3920. box.shadow(b);
  3921. }
  3922. return wrapper;
  3923. },
  3924. /**
  3925. * Destroy and release memory.
  3926. */
  3927. destroy: function () {
  3928. removeEvent(wrapper, 'add', getSizeAfterAdd);
  3929. // Added by button implementation
  3930. removeEvent(wrapper.element, 'mouseenter');
  3931. removeEvent(wrapper.element, 'mouseleave');
  3932. if (text) {
  3933. text = text.destroy();
  3934. }
  3935. if (box) {
  3936. box = box.destroy();
  3937. }
  3938. // Call base implementation to destroy the rest
  3939. SVGElement.prototype.destroy.call(wrapper);
  3940. // Release local pointers (#1298)
  3941. wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = getSizeAfterAdd = null;
  3942. }
  3943. });
  3944. }
  3945. }; // end SVGRenderer
  3946. // general renderer
  3947. Renderer = SVGRenderer;
  3948. /* ****************************************************************************
  3949. * *
  3950. * START OF INTERNET EXPLORER <= 8 SPECIFIC CODE *
  3951. * *
  3952. * For applications and websites that don't need IE support, like platform *
  3953. * targeted mobile apps and web apps, this code can be removed. *
  3954. * *
  3955. *****************************************************************************/
  3956. /**
  3957. * @constructor
  3958. */
  3959. var VMLRenderer, VMLElement;
  3960. if (!hasSVG && !useCanVG) {
  3961. /**
  3962. * The VML element wrapper.
  3963. */
  3964. Highcharts.VMLElement = VMLElement = {
  3965. /**
  3966. * Initialize a new VML element wrapper. It builds the markup as a string
  3967. * to minimize DOM traffic.
  3968. * @param {Object} renderer
  3969. * @param {Object} nodeName
  3970. */
  3971. init: function (renderer, nodeName) {
  3972. var wrapper = this,
  3973. markup = ['<', nodeName, ' filled="f" stroked="f"'],
  3974. style = ['position: ', ABSOLUTE, ';'],
  3975. isDiv = nodeName === DIV;
  3976. // divs and shapes need size
  3977. if (nodeName === 'shape' || isDiv) {
  3978. style.push('left:0;top:0;width:1px;height:1px;');
  3979. }
  3980. style.push('visibility: ', isDiv ? HIDDEN : VISIBLE);
  3981. markup.push(' style="', style.join(''), '"/>');
  3982. // create element with default attributes and style
  3983. if (nodeName) {
  3984. markup = isDiv || nodeName === 'span' || nodeName === 'img' ?
  3985. markup.join('')
  3986. : renderer.prepVML(markup);
  3987. wrapper.element = createElement(markup);
  3988. }
  3989. wrapper.renderer = renderer;
  3990. wrapper.attrSetters = {};
  3991. },
  3992. /**
  3993. * Add the node to the given parent
  3994. * @param {Object} parent
  3995. */
  3996. add: function (parent) {
  3997. var wrapper = this,
  3998. renderer = wrapper.renderer,
  3999. element = wrapper.element,
  4000. box = renderer.box,
  4001. inverted = parent && parent.inverted,
  4002. // get the parent node
  4003. parentNode = parent ?
  4004. parent.element || parent :
  4005. box;
  4006. // if the parent group is inverted, apply inversion on all children
  4007. if (inverted) { // only on groups
  4008. renderer.invertChild(element, parentNode);
  4009. }
  4010. // append it
  4011. parentNode.appendChild(element);
  4012. // align text after adding to be able to read offset
  4013. wrapper.added = true;
  4014. if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) {
  4015. wrapper.updateTransform();
  4016. }
  4017. // fire an event for internal hooks
  4018. fireEvent(wrapper, 'add');
  4019. return wrapper;
  4020. },
  4021. /**
  4022. * VML always uses htmlUpdateTransform
  4023. */
  4024. updateTransform: SVGElement.prototype.htmlUpdateTransform,
  4025. /**
  4026. * Set the rotation of a span with oldIE's filter
  4027. */
  4028. setSpanRotation: function (rotation, sintheta, costheta) {
  4029. // Adjust for alignment and rotation. Rotation of useHTML content is not yet implemented
  4030. // but it can probably be implemented for Firefox 3.5+ on user request. FF3.5+
  4031. // has support for CSS3 transform. The getBBox method also needs to be updated
  4032. // to compensate for the rotation, like it currently does for SVG.
  4033. // Test case: http://highcharts.com/tests/?file=text-rotation
  4034. css(this.element, {
  4035. filter: rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta,
  4036. ', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta,
  4037. ', sizingMethod=\'auto expand\')'].join('') : NONE
  4038. });
  4039. },
  4040. /**
  4041. * Converts a subset of an SVG path definition to its VML counterpart. Takes an array
  4042. * as the parameter and returns a string.
  4043. */
  4044. pathToVML: function (value) {
  4045. // convert paths
  4046. var i = value.length,
  4047. path = [],
  4048. clockwise;
  4049. while (i--) {
  4050. // Multiply by 10 to allow subpixel precision.
  4051. // Substracting half a pixel seems to make the coordinates
  4052. // align with SVG, but this hasn't been tested thoroughly
  4053. if (isNumber(value[i])) {
  4054. path[i] = mathRound(value[i] * 10) - 5;
  4055. } else if (value[i] === 'Z') { // close the path
  4056. path[i] = 'x';
  4057. } else {
  4058. path[i] = value[i];
  4059. // When the start X and end X coordinates of an arc are too close,
  4060. // they are rounded to the same value above. In this case, substract 1 from the end X
  4061. // position. #760, #1371.
  4062. if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) {
  4063. clockwise = value[i] === 'wa' ? 1 : -1; // #1642
  4064. if (path[i + 5] === path[i + 7]) {
  4065. path[i + 7] -= clockwise;
  4066. }
  4067. // Start and end Y (#1410)
  4068. if (path[i + 6] === path[i + 8]) {
  4069. path[i + 8] -= clockwise;
  4070. }
  4071. }
  4072. }
  4073. }
  4074. // Loop up again to handle path shortcuts (#2132)
  4075. /*while (i++ < path.length) {
  4076. if (path[i] === 'H') { // horizontal line to
  4077. path[i] = 'L';
  4078. path.splice(i + 2, 0, path[i - 1]);
  4079. } else if (path[i] === 'V') { // vertical line to
  4080. path[i] = 'L';
  4081. path.splice(i + 1, 0, path[i - 2]);
  4082. }
  4083. }*/
  4084. return path.join(' ') || 'x';
  4085. },
  4086. /**
  4087. * Get or set attributes
  4088. */
  4089. attr: function (hash, val) {
  4090. var wrapper = this,
  4091. key,
  4092. value,
  4093. i,
  4094. result,
  4095. element = wrapper.element || {},
  4096. elemStyle = element.style,
  4097. nodeName = element.nodeName,
  4098. renderer = wrapper.renderer,
  4099. symbolName = wrapper.symbolName,
  4100. hasSetSymbolSize,
  4101. shadows = wrapper.shadows,
  4102. skipAttr,
  4103. attrSetters = wrapper.attrSetters,
  4104. ret = wrapper;
  4105. // single key-value pair
  4106. if (isString(hash) && defined(val)) {
  4107. key = hash;
  4108. hash = {};
  4109. hash[key] = val;
  4110. }
  4111. // used as a getter, val is undefined
  4112. if (isString(hash)) {
  4113. key = hash;
  4114. if (key === 'strokeWidth' || key === 'stroke-width') {
  4115. ret = wrapper.strokeweight;
  4116. } else {
  4117. ret = wrapper[key];
  4118. }
  4119. // setter
  4120. } else {
  4121. for (key in hash) {
  4122. value = hash[key];
  4123. skipAttr = false;
  4124. // check for a specific attribute setter
  4125. result = attrSetters[key] && attrSetters[key].call(wrapper, value, key);
  4126. if (result !== false && value !== null) { // #620
  4127. if (result !== UNDEFINED) {
  4128. value = result; // the attribute setter has returned a new value to set
  4129. }
  4130. // prepare paths
  4131. // symbols
  4132. if (symbolName && /^(x|y|r|start|end|width|height|innerR|anchorX|anchorY)/.test(key)) {
  4133. // if one of the symbol size affecting parameters are changed,
  4134. // check all the others only once for each call to an element's
  4135. // .attr() method
  4136. if (!hasSetSymbolSize) {
  4137. wrapper.symbolAttr(hash);
  4138. hasSetSymbolSize = true;
  4139. }
  4140. skipAttr = true;
  4141. } else if (key === 'd') {
  4142. value = value || [];
  4143. wrapper.d = value.join(' '); // used in getter for animation
  4144. element.path = value = wrapper.pathToVML(value);
  4145. // update shadows
  4146. if (shadows) {
  4147. i = shadows.length;
  4148. while (i--) {
  4149. shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value;
  4150. }
  4151. }
  4152. skipAttr = true;
  4153. // handle visibility
  4154. } else if (key === 'visibility') {
  4155. // let the shadow follow the main element
  4156. if (shadows) {
  4157. i = shadows.length;
  4158. while (i--) {
  4159. shadows[i].style[key] = value;
  4160. }
  4161. }
  4162. // Instead of toggling the visibility CSS property, move the div out of the viewport.
  4163. // This works around #61 and #586
  4164. if (nodeName === 'DIV') {
  4165. value = value === HIDDEN ? '-999em' : 0;
  4166. // In order to redraw, IE7 needs the div to be visible when tucked away
  4167. // outside the viewport. So the visibility is actually opposite of
  4168. // the expected value. This applies to the tooltip only.
  4169. if (!docMode8) {
  4170. elemStyle[key] = value ? VISIBLE : HIDDEN;
  4171. }
  4172. key = 'top';
  4173. }
  4174. elemStyle[key] = value;
  4175. skipAttr = true;
  4176. // directly mapped to css
  4177. } else if (key === 'zIndex') {
  4178. if (value) {
  4179. elemStyle[key] = value;
  4180. }
  4181. skipAttr = true;
  4182. // x, y, width, height
  4183. } else if (inArray(key, ['x', 'y', 'width', 'height']) !== -1) {
  4184. wrapper[key] = value; // used in getter
  4185. if (key === 'x' || key === 'y') {
  4186. key = { x: 'left', y: 'top' }[key];
  4187. } else {
  4188. value = mathMax(0, value); // don't set width or height below zero (#311)
  4189. }
  4190. // clipping rectangle special
  4191. if (wrapper.updateClipping) {
  4192. wrapper[key] = value; // the key is now 'left' or 'top' for 'x' and 'y'
  4193. wrapper.updateClipping();
  4194. } else {
  4195. // normal
  4196. elemStyle[key] = value;
  4197. }
  4198. skipAttr = true;
  4199. // class name
  4200. } else if (key === 'class' && nodeName === 'DIV') {
  4201. // IE8 Standards mode has problems retrieving the className
  4202. element.className = value;
  4203. // stroke
  4204. } else if (key === 'stroke') {
  4205. value = renderer.color(value, element, key);
  4206. key = 'strokecolor';
  4207. // stroke width
  4208. } else if (key === 'stroke-width' || key === 'strokeWidth') {
  4209. element.stroked = value ? true : false;
  4210. key = 'strokeweight';
  4211. wrapper[key] = value; // used in getter, issue #113
  4212. if (isNumber(value)) {
  4213. value += PX;
  4214. }
  4215. // dashStyle
  4216. } else if (key === 'dashstyle') {
  4217. var strokeElem = element.getElementsByTagName('stroke')[0] ||
  4218. createElement(renderer.prepVML(['<stroke/>']), null, null, element);
  4219. strokeElem[key] = value || 'solid';
  4220. wrapper.dashstyle = value; /* because changing stroke-width will change the dash length
  4221. and cause an epileptic effect */
  4222. skipAttr = true;
  4223. // fill
  4224. } else if (key === 'fill') {
  4225. if (nodeName === 'SPAN') { // text color
  4226. elemStyle.color = value;
  4227. } else if (nodeName !== 'IMG') { // #1336
  4228. element.filled = value !== NONE ? true : false;
  4229. value = renderer.color(value, element, key, wrapper);
  4230. key = 'fillcolor';
  4231. }
  4232. // opacity: don't bother - animation is too slow and filters introduce artifacts
  4233. } else if (key === 'opacity') {
  4234. /*css(element, {
  4235. opacity: value
  4236. });*/
  4237. skipAttr = true;
  4238. // rotation on VML elements
  4239. } else if (nodeName === 'shape' && key === 'rotation') {
  4240. wrapper[key] = element.style[key] = value; // style is for #1873
  4241. // Correction for the 1x1 size of the shape container. Used in gauge needles.
  4242. element.style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX;
  4243. element.style.top = mathRound(mathCos(value * deg2rad)) + PX;
  4244. // translation for animation
  4245. } else if (key === 'translateX' || key === 'translateY' || key === 'rotation') {
  4246. wrapper[key] = value;
  4247. wrapper.updateTransform();
  4248. skipAttr = true;
  4249. // text for rotated and non-rotated elements
  4250. } else if (key === 'text') {
  4251. this.bBox = null;
  4252. element.innerHTML = value;
  4253. skipAttr = true;
  4254. }
  4255. if (!skipAttr) {
  4256. if (docMode8) { // IE8 setAttribute bug
  4257. element[key] = value;
  4258. } else {
  4259. attr(element, key, value);
  4260. }
  4261. }
  4262. }
  4263. }
  4264. }
  4265. return ret;
  4266. },
  4267. /**
  4268. * Set the element's clipping to a predefined rectangle
  4269. *
  4270. * @param {String} id The id of the clip rectangle
  4271. */
  4272. clip: function (clipRect) {
  4273. var wrapper = this,
  4274. clipMembers,
  4275. cssRet;
  4276. if (clipRect) {
  4277. clipMembers = clipRect.members;
  4278. erase(clipMembers, wrapper); // Ensure unique list of elements (#1258)
  4279. clipMembers.push(wrapper);
  4280. wrapper.destroyClip = function () {
  4281. erase(clipMembers, wrapper);
  4282. };
  4283. cssRet = clipRect.getCSS(wrapper);
  4284. } else {
  4285. if (wrapper.destroyClip) {
  4286. wrapper.destroyClip();
  4287. }
  4288. cssRet = { clip: docMode8 ? 'inherit' : 'rect(auto)' }; // #1214
  4289. }
  4290. return wrapper.css(cssRet);
  4291. },
  4292. /**
  4293. * Set styles for the element
  4294. * @param {Object} styles
  4295. */
  4296. css: SVGElement.prototype.htmlCss,
  4297. /**
  4298. * Removes a child either by removeChild or move to garbageBin.
  4299. * Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not.
  4300. */
  4301. safeRemoveChild: function (element) {
  4302. // discardElement will detach the node from its parent before attaching it
  4303. // to the garbage bin. Therefore it is important that the node is attached and have parent.
  4304. if (element.parentNode) {
  4305. discardElement(element);
  4306. }
  4307. },
  4308. /**
  4309. * Extend element.destroy by removing it from the clip members array
  4310. */
  4311. destroy: function () {
  4312. if (this.destroyClip) {
  4313. this.destroyClip();
  4314. }
  4315. return SVGElement.prototype.destroy.apply(this);
  4316. },
  4317. /**
  4318. * Add an event listener. VML override for normalizing event parameters.
  4319. * @param {String} eventType
  4320. * @param {Function} handler
  4321. */
  4322. on: function (eventType, handler) {
  4323. // simplest possible event model for internal use
  4324. this.element['on' + eventType] = function () {
  4325. var evt = win.event;
  4326. evt.target = evt.srcElement;
  4327. handler(evt);
  4328. };
  4329. return this;
  4330. },
  4331. /**
  4332. * In stacked columns, cut off the shadows so that they don't overlap
  4333. */
  4334. cutOffPath: function (path, length) {
  4335. var len;
  4336. path = path.split(/[ ,]/);
  4337. len = path.length;
  4338. if (len === 9 || len === 11) {
  4339. path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length;
  4340. }
  4341. return path.join(' ');
  4342. },
  4343. /**
  4344. * Apply a drop shadow by copying elements and giving them different strokes
  4345. * @param {Boolean|Object} shadowOptions
  4346. */
  4347. shadow: function (shadowOptions, group, cutOff) {
  4348. var shadows = [],
  4349. i,
  4350. element = this.element,
  4351. renderer = this.renderer,
  4352. shadow,
  4353. elemStyle = element.style,
  4354. markup,
  4355. path = element.path,
  4356. strokeWidth,
  4357. modifiedPath,
  4358. shadowWidth,
  4359. shadowElementOpacity;
  4360. // some times empty paths are not strings
  4361. if (path && typeof path.value !== 'string') {
  4362. path = 'x';
  4363. }
  4364. modifiedPath = path;
  4365. if (shadowOptions) {
  4366. shadowWidth = pick(shadowOptions.width, 3);
  4367. shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth;
  4368. for (i = 1; i <= 3; i++) {
  4369. strokeWidth = (shadowWidth * 2) + 1 - (2 * i);
  4370. // Cut off shadows for stacked column items
  4371. if (cutOff) {
  4372. modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5);
  4373. }
  4374. markup = ['<shape isShadow="true" strokeweight="', strokeWidth,
  4375. '" filled="false" path="', modifiedPath,
  4376. '" coordsize="10 10" style="', element.style.cssText, '" />'];
  4377. shadow = createElement(renderer.prepVML(markup),
  4378. null, {
  4379. left: pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1),
  4380. top: pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1)
  4381. }
  4382. );
  4383. if (cutOff) {
  4384. shadow.cutOff = strokeWidth + 1;
  4385. }
  4386. // apply the opacity
  4387. markup = ['<stroke color="', shadowOptions.color || 'black', '" opacity="', shadowElementOpacity * i, '"/>'];
  4388. createElement(renderer.prepVML(markup), null, null, shadow);
  4389. // insert it
  4390. if (group) {
  4391. group.element.appendChild(shadow);
  4392. } else {
  4393. element.parentNode.insertBefore(shadow, element);
  4394. }
  4395. // reconciliation it
  4396. shadows.push(shadow);
  4397. }
  4398. this.shadows = shadows;
  4399. }
  4400. return this;
  4401. }
  4402. };
  4403. VMLElement = extendClass(SVGElement, VMLElement);
  4404. /**
  4405. * The VML renderer
  4406. */
  4407. var VMLRendererExtension = { // inherit SVGRenderer
  4408. Element: VMLElement,
  4409. isIE8: userAgent.indexOf('MSIE 8.0') > -1,
  4410. /**
  4411. * Initialize the VMLRenderer
  4412. * @param {Object} container
  4413. * @param {Number} width
  4414. * @param {Number} height
  4415. */
  4416. init: function (container, width, height) {
  4417. var renderer = this,
  4418. boxWrapper,
  4419. box;
  4420. renderer.alignedObjects = [];
  4421. boxWrapper = renderer.createElement(DIV);
  4422. box = boxWrapper.element;
  4423. box.style.position = RELATIVE; // for freeform drawing using renderer directly
  4424. container.appendChild(boxWrapper.element);
  4425. // generate the containing box
  4426. renderer.isVML = true;
  4427. renderer.box = box;
  4428. renderer.boxWrapper = boxWrapper;
  4429. renderer.setSize(width, height, false);
  4430. // The only way to make IE6 and IE7 print is to use a global namespace. However,
  4431. // with IE8 the only way to make the dynamic shapes visible in screen and print mode
  4432. // seems to be to add the xmlns attribute and the behaviour style inline.
  4433. if (!doc.namespaces.hcv) {
  4434. doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml');
  4435. // Setup default CSS (#2153)
  4436. (doc.styleSheets.length ? doc.styleSheets[0] : doc.createStyleSheet()).cssText +=
  4437. 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' +
  4438. '{ behavior:url(#default#VML); display: inline-block; } ';
  4439. }
  4440. },
  4441. /**
  4442. * Detect whether the renderer is hidden. This happens when one of the parent elements
  4443. * has display: none
  4444. */
  4445. isHidden: function () {
  4446. return !this.box.offsetWidth;
  4447. },
  4448. /**
  4449. * Define a clipping rectangle. In VML it is accomplished by storing the values
  4450. * for setting the CSS style to all associated members.
  4451. *
  4452. * @param {Number} x
  4453. * @param {Number} y
  4454. * @param {Number} width
  4455. * @param {Number} height
  4456. */
  4457. clipRect: function (x, y, width, height) {
  4458. // create a dummy element
  4459. var clipRect = this.createElement(),
  4460. isObj = isObject(x);
  4461. // mimic a rectangle with its style object for automatic updating in attr
  4462. return extend(clipRect, {
  4463. members: [],
  4464. left: (isObj ? x.x : x) + 1,
  4465. top: (isObj ? x.y : y) + 1,
  4466. width: (isObj ? x.width : width) - 1,
  4467. height: (isObj ? x.height : height) - 1,
  4468. getCSS: function (wrapper) {
  4469. var element = wrapper.element,
  4470. nodeName = element.nodeName,
  4471. isShape = nodeName === 'shape',
  4472. inverted = wrapper.inverted,
  4473. rect = this,
  4474. top = rect.top - (isShape ? element.offsetTop : 0),
  4475. left = rect.left,
  4476. right = left + rect.width,
  4477. bottom = top + rect.height,
  4478. ret = {
  4479. clip: 'rect(' +
  4480. mathRound(inverted ? left : top) + 'px,' +
  4481. mathRound(inverted ? bottom : right) + 'px,' +
  4482. mathRound(inverted ? right : bottom) + 'px,' +
  4483. mathRound(inverted ? top : left) + 'px)'
  4484. };
  4485. // issue 74 workaround
  4486. if (!inverted && docMode8 && nodeName === 'DIV') {
  4487. extend(ret, {
  4488. width: right + PX,
  4489. height: bottom + PX
  4490. });
  4491. }
  4492. return ret;
  4493. },
  4494. // used in attr and animation to update the clipping of all members
  4495. updateClipping: function () {
  4496. each(clipRect.members, function (member) {
  4497. member.css(clipRect.getCSS(member));
  4498. });
  4499. }
  4500. });
  4501. },
  4502. /**
  4503. * Take a color and return it if it's a string, make it a gradient if it's a
  4504. * gradient configuration object, and apply opacity.
  4505. *
  4506. * @param {Object} color The color or config object
  4507. */
  4508. color: function (color, elem, prop, wrapper) {
  4509. var renderer = this,
  4510. colorObject,
  4511. regexRgba = /^rgba/,
  4512. markup,
  4513. fillType,
  4514. ret = NONE;
  4515. // Check for linear or radial gradient
  4516. if (color && color.linearGradient) {
  4517. fillType = 'gradient';
  4518. } else if (color && color.radialGradient) {
  4519. fillType = 'pattern';
  4520. }
  4521. if (fillType) {
  4522. var stopColor,
  4523. stopOpacity,
  4524. gradient = color.linearGradient || color.radialGradient,
  4525. x1,
  4526. y1,
  4527. x2,
  4528. y2,
  4529. opacity1,
  4530. opacity2,
  4531. color1,
  4532. color2,
  4533. fillAttr = '',
  4534. stops = color.stops,
  4535. firstStop,
  4536. lastStop,
  4537. colors = [],
  4538. addFillNode = function () {
  4539. // Add the fill subnode. When colors attribute is used, the meanings of opacity and o:opacity2
  4540. // are reversed.
  4541. markup = ['<fill colors="' + colors.join(',') + '" opacity="', opacity2, '" o:opacity2="', opacity1,
  4542. '" type="', fillType, '" ', fillAttr, 'focus="100%" method="any" />'];
  4543. createElement(renderer.prepVML(markup), null, null, elem);
  4544. };
  4545. // Extend from 0 to 1
  4546. firstStop = stops[0];
  4547. lastStop = stops[stops.length - 1];
  4548. if (firstStop[0] > 0) {
  4549. stops.unshift([
  4550. 0,
  4551. firstStop[1]
  4552. ]);
  4553. }
  4554. if (lastStop[0] < 1) {
  4555. stops.push([
  4556. 1,
  4557. lastStop[1]
  4558. ]);
  4559. }
  4560. // Compute the stops
  4561. each(stops, function (stop, i) {
  4562. if (regexRgba.test(stop[1])) {
  4563. colorObject = Color(stop[1]);
  4564. stopColor = colorObject.get('rgb');
  4565. stopOpacity = colorObject.get('a');
  4566. } else {
  4567. stopColor = stop[1];
  4568. stopOpacity = 1;
  4569. }
  4570. // Build the color attribute
  4571. colors.push((stop[0] * 100) + '% ' + stopColor);
  4572. // Only start and end opacities are allowed, so we use the first and the last
  4573. if (!i) {
  4574. opacity1 = stopOpacity;
  4575. color2 = stopColor;
  4576. } else {
  4577. opacity2 = stopOpacity;
  4578. color1 = stopColor;
  4579. }
  4580. });
  4581. // Apply the gradient to fills only.
  4582. if (prop === 'fill') {
  4583. // Handle linear gradient angle
  4584. if (fillType === 'gradient') {
  4585. x1 = gradient.x1 || gradient[0] || 0;
  4586. y1 = gradient.y1 || gradient[1] || 0;
  4587. x2 = gradient.x2 || gradient[2] || 0;
  4588. y2 = gradient.y2 || gradient[3] || 0;
  4589. fillAttr = 'angle="' + (90 - math.atan(
  4590. (y2 - y1) / // y vector
  4591. (x2 - x1) // x vector
  4592. ) * 180 / mathPI) + '"';
  4593. addFillNode();
  4594. // Radial (circular) gradient
  4595. } else {
  4596. var r = gradient.r,
  4597. sizex = r * 2,
  4598. sizey = r * 2,
  4599. cx = gradient.cx,
  4600. cy = gradient.cy,
  4601. radialReference = elem.radialReference,
  4602. bBox,
  4603. applyRadialGradient = function () {
  4604. if (radialReference) {
  4605. bBox = wrapper.getBBox();
  4606. cx += (radialReference[0] - bBox.x) / bBox.width - 0.5;
  4607. cy += (radialReference[1] - bBox.y) / bBox.height - 0.5;
  4608. sizex *= radialReference[2] / bBox.width;
  4609. sizey *= radialReference[2] / bBox.height;
  4610. }
  4611. fillAttr = 'src="' + defaultOptions.global.VMLRadialGradientURL + '" ' +
  4612. 'size="' + sizex + ',' + sizey + '" ' +
  4613. 'origin="0.5,0.5" ' +
  4614. 'position="' + cx + ',' + cy + '" ' +
  4615. 'color2="' + color2 + '" ';
  4616. addFillNode();
  4617. };
  4618. // Apply radial gradient
  4619. if (wrapper.added) {
  4620. applyRadialGradient();
  4621. } else {
  4622. // We need to know the bounding box to get the size and position right
  4623. addEvent(wrapper, 'add', applyRadialGradient);
  4624. }
  4625. // The fill element's color attribute is broken in IE8 standards mode, so we
  4626. // need to set the parent shape's fillcolor attribute instead.
  4627. ret = color1;
  4628. }
  4629. // Gradients are not supported for VML stroke, return the first color. #722.
  4630. } else {
  4631. ret = stopColor;
  4632. }
  4633. // if the color is an rgba color, split it and add a fill node
  4634. // to hold the opacity component
  4635. } else if (regexRgba.test(color) && elem.tagName !== 'IMG') {
  4636. colorObject = Color(color);
  4637. markup = ['<', prop, ' opacity="', colorObject.get('a'), '"/>'];
  4638. createElement(this.prepVML(markup), null, null, elem);
  4639. ret = colorObject.get('rgb');
  4640. } else {
  4641. var propNodes = elem.getElementsByTagName(prop); // 'stroke' or 'fill' node
  4642. if (propNodes.length) {
  4643. propNodes[0].opacity = 1;
  4644. propNodes[0].type = 'solid';
  4645. }
  4646. ret = color;
  4647. }
  4648. return ret;
  4649. },
  4650. /**
  4651. * Take a VML string and prepare it for either IE8 or IE6/IE7.
  4652. * @param {Array} markup A string array of the VML markup to prepare
  4653. */
  4654. prepVML: function (markup) {
  4655. var vmlStyle = 'display:inline-block;behavior:url(#default#VML);',
  4656. isIE8 = this.isIE8;
  4657. markup = markup.join('');
  4658. if (isIE8) { // add xmlns and style inline
  4659. markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />');
  4660. if (markup.indexOf('style="') === -1) {
  4661. markup = markup.replace('/>', ' style="' + vmlStyle + '" />');
  4662. } else {
  4663. markup = markup.replace('style="', 'style="' + vmlStyle);
  4664. }
  4665. } else { // add namespace
  4666. markup = markup.replace('<', '<hcv:');
  4667. }
  4668. return markup;
  4669. },
  4670. /**
  4671. * Create rotated and aligned text
  4672. * @param {String} str
  4673. * @param {Number} x
  4674. * @param {Number} y
  4675. */
  4676. text: SVGRenderer.prototype.html,
  4677. /**
  4678. * Create and return a path element
  4679. * @param {Array} path
  4680. */
  4681. path: function (path) {
  4682. var attr = {
  4683. // subpixel precision down to 0.1 (width and height = 1px)
  4684. coordsize: '10 10'
  4685. };
  4686. if (isArray(path)) {
  4687. attr.d = path;
  4688. } else if (isObject(path)) { // attributes
  4689. extend(attr, path);
  4690. }
  4691. // create the shape
  4692. return this.createElement('shape').attr(attr);
  4693. },
  4694. /**
  4695. * Create and return a circle element. In VML circles are implemented as
  4696. * shapes, which is faster than v:oval
  4697. * @param {Number} x
  4698. * @param {Number} y
  4699. * @param {Number} r
  4700. */
  4701. circle: function (x, y, r) {
  4702. var circle = this.symbol('circle');
  4703. if (isObject(x)) {
  4704. r = x.r;
  4705. y = x.y;
  4706. x = x.x;
  4707. }
  4708. circle.isCircle = true; // Causes x and y to mean center (#1682)
  4709. circle.r = r;
  4710. return circle.attr({ x: x, y: y });
  4711. },
  4712. /**
  4713. * Create a group using an outer div and an inner v:group to allow rotating
  4714. * and flipping. A simple v:group would have problems with positioning
  4715. * child HTML elements and CSS clip.
  4716. *
  4717. * @param {String} name The name of the group
  4718. */
  4719. g: function (name) {
  4720. var wrapper,
  4721. attribs;
  4722. // set the class name
  4723. if (name) {
  4724. attribs = { 'className': PREFIX + name, 'class': PREFIX + name };
  4725. }
  4726. // the div to hold HTML and clipping
  4727. wrapper = this.createElement(DIV).attr(attribs);
  4728. return wrapper;
  4729. },
  4730. /**
  4731. * VML override to create a regular HTML image
  4732. * @param {String} src
  4733. * @param {Number} x
  4734. * @param {Number} y
  4735. * @param {Number} width
  4736. * @param {Number} height
  4737. */
  4738. image: function (src, x, y, width, height) {
  4739. var obj = this.createElement('img')
  4740. .attr({ src: src });
  4741. if (arguments.length > 1) {
  4742. obj.attr({
  4743. x: x,
  4744. y: y,
  4745. width: width,
  4746. height: height
  4747. });
  4748. }
  4749. return obj;
  4750. },
  4751. /**
  4752. * VML uses a shape for rect to overcome bugs and rotation problems
  4753. */
  4754. rect: function (x, y, width, height, r, strokeWidth) {
  4755. var wrapper = this.symbol('rect');
  4756. wrapper.r = isObject(x) ? x.r : r;
  4757. //return wrapper.attr(wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0)));
  4758. return wrapper.attr(
  4759. isObject(x) ?
  4760. x :
  4761. // do not crispify when an object is passed in (as in column charts)
  4762. wrapper.crisp(strokeWidth, x, y, mathMax(width, 0), mathMax(height, 0))
  4763. );
  4764. },
  4765. /**
  4766. * In the VML renderer, each child of an inverted div (group) is inverted
  4767. * @param {Object} element
  4768. * @param {Object} parentNode
  4769. */
  4770. invertChild: function (element, parentNode) {
  4771. var parentStyle = parentNode.style;
  4772. css(element, {
  4773. flip: 'x',
  4774. left: pInt(parentStyle.width) - 1,
  4775. top: pInt(parentStyle.height) - 1,
  4776. rotation: -90
  4777. });
  4778. },
  4779. /**
  4780. * Symbol definitions that override the parent SVG renderer's symbols
  4781. *
  4782. */
  4783. symbols: {
  4784. // VML specific arc function
  4785. arc: function (x, y, w, h, options) {
  4786. var start = options.start,
  4787. end = options.end,
  4788. radius = options.r || w || h,
  4789. innerRadius = options.innerR,
  4790. cosStart = mathCos(start),
  4791. sinStart = mathSin(start),
  4792. cosEnd = mathCos(end),
  4793. sinEnd = mathSin(end),
  4794. ret;
  4795. if (end - start === 0) { // no angle, don't show it.
  4796. return ['x'];
  4797. }
  4798. ret = [
  4799. 'wa', // clockwise arc to
  4800. x - radius, // left
  4801. y - radius, // top
  4802. x + radius, // right
  4803. y + radius, // bottom
  4804. x + radius * cosStart, // start x
  4805. y + radius * sinStart, // start y
  4806. x + radius * cosEnd, // end x
  4807. y + radius * sinEnd // end y
  4808. ];
  4809. if (options.open && !innerRadius) {
  4810. ret.push(
  4811. 'e',
  4812. M,
  4813. x,// - innerRadius,
  4814. y// - innerRadius
  4815. );
  4816. }
  4817. ret.push(
  4818. 'at', // anti clockwise arc to
  4819. x - innerRadius, // left
  4820. y - innerRadius, // top
  4821. x + innerRadius, // right
  4822. y + innerRadius, // bottom
  4823. x + innerRadius * cosEnd, // start x
  4824. y + innerRadius * sinEnd, // start y
  4825. x + innerRadius * cosStart, // end x
  4826. y + innerRadius * sinStart, // end y
  4827. 'x', // finish path
  4828. 'e' // close
  4829. );
  4830. ret.isArc = true;
  4831. return ret;
  4832. },
  4833. // Add circle symbol path. This performs significantly faster than v:oval.
  4834. circle: function (x, y, w, h, wrapper) {
  4835. if (wrapper) {
  4836. w = h = 2 * wrapper.r;
  4837. }
  4838. // Center correction, #1682
  4839. if (wrapper && wrapper.isCircle) {
  4840. x -= w / 2;
  4841. y -= h / 2;
  4842. }
  4843. // Return the path
  4844. return [
  4845. 'wa', // clockwisearcto
  4846. x, // left
  4847. y, // top
  4848. x + w, // right
  4849. y + h, // bottom
  4850. x + w, // start x
  4851. y + h / 2, // start y
  4852. x + w, // end x
  4853. y + h / 2, // end y
  4854. //'x', // finish path
  4855. 'e' // close
  4856. ];
  4857. },
  4858. /**
  4859. * Add rectangle symbol path which eases rotation and omits arcsize problems
  4860. * compared to the built-in VML roundrect shape
  4861. *
  4862. * @param {Number} left Left position
  4863. * @param {Number} top Top position
  4864. * @param {Number} r Border radius
  4865. * @param {Object} options Width and height
  4866. */
  4867. rect: function (left, top, width, height, options) {
  4868. var right = left + width,
  4869. bottom = top + height,
  4870. ret,
  4871. r;
  4872. // No radius, return the more lightweight square
  4873. if (!defined(options) || !options.r) {
  4874. ret = SVGRenderer.prototype.symbols.square.apply(0, arguments);
  4875. // Has radius add arcs for the corners
  4876. } else {
  4877. r = mathMin(options.r, width, height);
  4878. ret = [
  4879. M,
  4880. left + r, top,
  4881. L,
  4882. right - r, top,
  4883. 'wa',
  4884. right - 2 * r, top,
  4885. right, top + 2 * r,
  4886. right - r, top,
  4887. right, top + r,
  4888. L,
  4889. right, bottom - r,
  4890. 'wa',
  4891. right - 2 * r, bottom - 2 * r,
  4892. right, bottom,
  4893. right, bottom - r,
  4894. right - r, bottom,
  4895. L,
  4896. left + r, bottom,
  4897. 'wa',
  4898. left, bottom - 2 * r,
  4899. left + 2 * r, bottom,
  4900. left + r, bottom,
  4901. left, bottom - r,
  4902. L,
  4903. left, top + r,
  4904. 'wa',
  4905. left, top,
  4906. left + 2 * r, top + 2 * r,
  4907. left, top + r,
  4908. left + r, top,
  4909. 'x',
  4910. 'e'
  4911. ];
  4912. }
  4913. return ret;
  4914. }
  4915. }
  4916. };
  4917. Highcharts.VMLRenderer = VMLRenderer = function () {
  4918. this.init.apply(this, arguments);
  4919. };
  4920. VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension);
  4921. // general renderer
  4922. Renderer = VMLRenderer;
  4923. }
  4924. /* ****************************************************************************
  4925. * *
  4926. * END OF INTERNET EXPLORER <= 8 SPECIFIC CODE *
  4927. * *
  4928. *****************************************************************************/
  4929. /* ****************************************************************************
  4930. * *
  4931. * START OF ANDROID < 3 SPECIFIC CODE. THIS CAN BE REMOVED IF YOU'RE NOT *
  4932. * TARGETING THAT SYSTEM. *
  4933. * *
  4934. *****************************************************************************/
  4935. var CanVGRenderer,
  4936. CanVGController;
  4937. if (useCanVG) {
  4938. /**
  4939. * The CanVGRenderer is empty from start to keep the source footprint small.
  4940. * When requested, the CanVGController downloads the rest of the source packaged
  4941. * together with the canvg library.
  4942. */
  4943. Highcharts.CanVGRenderer = CanVGRenderer = function () {
  4944. // Override the global SVG namespace to fake SVG/HTML that accepts CSS
  4945. SVG_NS = 'http://www.w3.org/1999/xhtml';
  4946. };
  4947. /**
  4948. * Start with an empty symbols object. This is needed when exporting is used (exporting.src.js will add a few symbols), but
  4949. * the implementation from SvgRenderer will not be merged in until first render.
  4950. */
  4951. CanVGRenderer.prototype.symbols = {};
  4952. /**
  4953. * Handles on demand download of canvg rendering support.
  4954. */
  4955. CanVGController = (function () {
  4956. // List of renderering calls
  4957. var deferredRenderCalls = [];
  4958. /**
  4959. * When downloaded, we are ready to draw deferred charts.
  4960. */
  4961. function drawDeferred() {
  4962. var callLength = deferredRenderCalls.length,
  4963. callIndex;
  4964. // Draw all pending render calls
  4965. for (callIndex = 0; callIndex < callLength; callIndex++) {
  4966. deferredRenderCalls[callIndex]();
  4967. }
  4968. // Clear the list
  4969. deferredRenderCalls = [];
  4970. }
  4971. return {
  4972. push: function (func, scriptLocation) {
  4973. // Only get the script once
  4974. if (deferredRenderCalls.length === 0) {
  4975. getScript(scriptLocation, drawDeferred);
  4976. }
  4977. // Register render call
  4978. deferredRenderCalls.push(func);
  4979. }
  4980. };
  4981. }());
  4982. Renderer = CanVGRenderer;
  4983. } // end CanVGRenderer
  4984. /* ****************************************************************************
  4985. * *
  4986. * END OF ANDROID < 3 SPECIFIC CODE *
  4987. * *
  4988. *****************************************************************************/
  4989. /**
  4990. * The Tick class
  4991. */
  4992. function Tick(axis, pos, type, noLabel) {
  4993. this.axis = axis;
  4994. this.pos = pos;
  4995. this.type = type || '';
  4996. this.isNew = true;
  4997. if (!type && !noLabel) {
  4998. this.addLabel();
  4999. }
  5000. }
  5001. Tick.prototype = {
  5002. /**
  5003. * Write the tick label
  5004. */
  5005. addLabel: function () {
  5006. var tick = this,
  5007. axis = tick.axis,
  5008. options = axis.options,
  5009. chart = axis.chart,
  5010. horiz = axis.horiz,
  5011. categories = axis.categories,
  5012. names = axis.series[0] && axis.series[0].names,
  5013. pos = tick.pos,
  5014. labelOptions = options.labels,
  5015. str,
  5016. tickPositions = axis.tickPositions,
  5017. width = (horiz && categories &&
  5018. !labelOptions.step && !labelOptions.staggerLines &&
  5019. !labelOptions.rotation &&
  5020. chart.plotWidth / tickPositions.length) ||
  5021. (!horiz && (chart.margin[3] || chart.chartWidth * 0.33)), // #1580, #1931
  5022. isFirst = pos === tickPositions[0],
  5023. isLast = pos === tickPositions[tickPositions.length - 1],
  5024. css,
  5025. attr,
  5026. value = categories ?
  5027. pick(categories[pos], names && names[pos], pos) :
  5028. pos,
  5029. label = tick.label,
  5030. tickPositionInfo = tickPositions.info,
  5031. dateTimeLabelFormat;
  5032. // Set the datetime label format. If a higher rank is set for this position, use that. If not,
  5033. // use the general format.
  5034. if (axis.isDatetimeAxis && tickPositionInfo) {
  5035. dateTimeLabelFormat = options.dateTimeLabelFormats[tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName];
  5036. }
  5037. // set properties for access in render method
  5038. tick.isFirst = isFirst;
  5039. tick.isLast = isLast;
  5040. // get the string
  5041. str = axis.labelFormatter.call({
  5042. axis: axis,
  5043. chart: chart,
  5044. isFirst: isFirst,
  5045. isLast: isLast,
  5046. dateTimeLabelFormat: dateTimeLabelFormat,
  5047. value: axis.isLog ? correctFloat(lin2log(value)) : value
  5048. });
  5049. // prepare CSS
  5050. css = width && { width: mathMax(1, mathRound(width - 2 * (labelOptions.padding || 10))) + PX };
  5051. css = extend(css, labelOptions.style);
  5052. // first call
  5053. if (!defined(label)) {
  5054. attr = {
  5055. align: axis.labelAlign
  5056. };
  5057. if (isNumber(labelOptions.rotation)) {
  5058. attr.rotation = labelOptions.rotation;
  5059. }
  5060. if (width && labelOptions.ellipsis) {
  5061. attr._clipHeight = axis.len / tickPositions.length;
  5062. }
  5063. tick.label =
  5064. defined(str) && labelOptions.enabled ?
  5065. chart.renderer.text(
  5066. str,
  5067. 0,
  5068. 0,
  5069. labelOptions.useHTML
  5070. )
  5071. .attr(attr)
  5072. // without position absolute, IE export sometimes is wrong
  5073. .css(css)
  5074. .add(axis.labelGroup) :
  5075. null;
  5076. // update
  5077. } else if (label) {
  5078. label.attr({
  5079. text: str
  5080. })
  5081. .css(css);
  5082. }
  5083. },
  5084. /**
  5085. * Get the offset height or width of the label
  5086. */
  5087. getLabelSize: function () {
  5088. var label = this.label,
  5089. axis = this.axis;
  5090. return label ?
  5091. ((this.labelBBox = label.getBBox()))[axis.horiz ? 'height' : 'width'] :
  5092. 0;
  5093. },
  5094. /**
  5095. * Find how far the labels extend to the right and left of the tick's x position. Used for anti-collision
  5096. * detection with overflow logic.
  5097. */
  5098. getLabelSides: function () {
  5099. var bBox = this.labelBBox, // assume getLabelSize has run at this point
  5100. axis = this.axis,
  5101. options = axis.options,
  5102. labelOptions = options.labels,
  5103. width = bBox.width,
  5104. leftSide = width * { left: 0, center: 0.5, right: 1 }[axis.labelAlign] - labelOptions.x;
  5105. return [-leftSide, width - leftSide];
  5106. },
  5107. /**
  5108. * Handle the label overflow by adjusting the labels to the left and right edge, or
  5109. * hide them if they collide into the neighbour label.
  5110. */
  5111. handleOverflow: function (index, xy) {
  5112. var show = true,
  5113. axis = this.axis,
  5114. chart = axis.chart,
  5115. isFirst = this.isFirst,
  5116. isLast = this.isLast,
  5117. x = xy.x,
  5118. reversed = axis.reversed,
  5119. tickPositions = axis.tickPositions;
  5120. if (isFirst || isLast) {
  5121. var sides = this.getLabelSides(),
  5122. leftSide = sides[0],
  5123. rightSide = sides[1],
  5124. plotLeft = chart.plotLeft,
  5125. plotRight = plotLeft + axis.len,
  5126. neighbour = axis.ticks[tickPositions[index + (isFirst ? 1 : -1)]],
  5127. neighbourEdge = neighbour && neighbour.label.xy && neighbour.label.xy.x + neighbour.getLabelSides()[isFirst ? 0 : 1];
  5128. if ((isFirst && !reversed) || (isLast && reversed)) {
  5129. // Is the label spilling out to the left of the plot area?
  5130. if (x + leftSide < plotLeft) {
  5131. // Align it to plot left
  5132. x = plotLeft - leftSide;
  5133. // Hide it if it now overlaps the neighbour label
  5134. if (neighbour && x + rightSide > neighbourEdge) {
  5135. show = false;
  5136. }
  5137. }
  5138. } else {
  5139. // Is the label spilling out to the right of the plot area?
  5140. if (x + rightSide > plotRight) {
  5141. // Align it to plot right
  5142. x = plotRight - rightSide;
  5143. // Hide it if it now overlaps the neighbour label
  5144. if (neighbour && x + leftSide < neighbourEdge) {
  5145. show = false;
  5146. }
  5147. }
  5148. }
  5149. // Set the modified x position of the label
  5150. xy.x = x;
  5151. }
  5152. return show;
  5153. },
  5154. /**
  5155. * Get the x and y position for ticks and labels
  5156. */
  5157. getPosition: function (horiz, pos, tickmarkOffset, old) {
  5158. var axis = this.axis,
  5159. chart = axis.chart,
  5160. cHeight = (old && chart.oldChartHeight) || chart.chartHeight;
  5161. return {
  5162. x: horiz ?
  5163. axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB :
  5164. axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0),
  5165. y: horiz ?
  5166. cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) :
  5167. cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB
  5168. };
  5169. },
  5170. /**
  5171. * Get the x, y position of the tick label
  5172. */
  5173. getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) {
  5174. var axis = this.axis,
  5175. transA = axis.transA,
  5176. reversed = axis.reversed,
  5177. staggerLines = axis.staggerLines,
  5178. baseline = axis.chart.renderer.fontMetrics(labelOptions.style.fontSize).b,
  5179. rotation = labelOptions.rotation;
  5180. x = x + labelOptions.x - (tickmarkOffset && horiz ?
  5181. tickmarkOffset * transA * (reversed ? -1 : 1) : 0);
  5182. y = y + labelOptions.y - (tickmarkOffset && !horiz ?
  5183. tickmarkOffset * transA * (reversed ? 1 : -1) : 0);
  5184. // Correct for rotation (#1764)
  5185. if (rotation && axis.side === 2) {
  5186. y -= baseline - baseline * mathCos(rotation * deg2rad);
  5187. }
  5188. // Vertically centered
  5189. if (!defined(labelOptions.y) && !rotation) { // #1951
  5190. y += baseline - label.getBBox().height / 2;
  5191. }
  5192. // Correct for staggered labels
  5193. if (staggerLines) {
  5194. y += (index / (step || 1) % staggerLines) * (axis.labelOffset / staggerLines);
  5195. }
  5196. return {
  5197. x: x,
  5198. y: y
  5199. };
  5200. },
  5201. /**
  5202. * Extendible method to return the path of the marker
  5203. */
  5204. getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) {
  5205. return renderer.crispLine([
  5206. M,
  5207. x,
  5208. y,
  5209. L,
  5210. x + (horiz ? 0 : -tickLength),
  5211. y + (horiz ? tickLength : 0)
  5212. ], tickWidth);
  5213. },
  5214. /**
  5215. * Put everything in place
  5216. *
  5217. * @param index {Number}
  5218. * @param old {Boolean} Use old coordinates to prepare an animation into new position
  5219. */
  5220. render: function (index, old, opacity) {
  5221. var tick = this,
  5222. axis = tick.axis,
  5223. options = axis.options,
  5224. chart = axis.chart,
  5225. renderer = chart.renderer,
  5226. horiz = axis.horiz,
  5227. type = tick.type,
  5228. label = tick.label,
  5229. pos = tick.pos,
  5230. labelOptions = options.labels,
  5231. gridLine = tick.gridLine,
  5232. gridPrefix = type ? type + 'Grid' : 'grid',
  5233. tickPrefix = type ? type + 'Tick' : 'tick',
  5234. gridLineWidth = options[gridPrefix + 'LineWidth'],
  5235. gridLineColor = options[gridPrefix + 'LineColor'],
  5236. dashStyle = options[gridPrefix + 'LineDashStyle'],
  5237. tickLength = options[tickPrefix + 'Length'],
  5238. tickWidth = options[tickPrefix + 'Width'] || 0,
  5239. tickColor = options[tickPrefix + 'Color'],
  5240. tickPosition = options[tickPrefix + 'Position'],
  5241. gridLinePath,
  5242. mark = tick.mark,
  5243. markPath,
  5244. step = labelOptions.step,
  5245. attribs,
  5246. show = true,
  5247. tickmarkOffset = axis.tickmarkOffset,
  5248. xy = tick.getPosition(horiz, pos, tickmarkOffset, old),
  5249. x = xy.x,
  5250. y = xy.y,
  5251. reverseCrisp = ((horiz && x === axis.pos + axis.len) || (!horiz && y === axis.pos)) ? -1 : 1, // #1480, #1687
  5252. staggerLines = axis.staggerLines;
  5253. this.isActive = true;
  5254. // create the grid line
  5255. if (gridLineWidth) {
  5256. gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLineWidth * reverseCrisp, old, true);
  5257. if (gridLine === UNDEFINED) {
  5258. attribs = {
  5259. stroke: gridLineColor,
  5260. 'stroke-width': gridLineWidth
  5261. };
  5262. if (dashStyle) {
  5263. attribs.dashstyle = dashStyle;
  5264. }
  5265. if (!type) {
  5266. attribs.zIndex = 1;
  5267. }
  5268. if (old) {
  5269. attribs.opacity = 0;
  5270. }
  5271. tick.gridLine = gridLine =
  5272. gridLineWidth ?
  5273. renderer.path(gridLinePath)
  5274. .attr(attribs).add(axis.gridGroup) :
  5275. null;
  5276. }
  5277. // If the parameter 'old' is set, the current call will be followed
  5278. // by another call, therefore do not do any animations this time
  5279. if (!old && gridLine && gridLinePath) {
  5280. gridLine[tick.isNew ? 'attr' : 'animate']({
  5281. d: gridLinePath,
  5282. opacity: opacity
  5283. });
  5284. }
  5285. }
  5286. // create the tick mark
  5287. if (tickWidth && tickLength) {
  5288. // negate the length
  5289. if (tickPosition === 'inside') {
  5290. tickLength = -tickLength;
  5291. }
  5292. if (axis.opposite) {
  5293. tickLength = -tickLength;
  5294. }
  5295. markPath = tick.getMarkPath(x, y, tickLength, tickWidth * reverseCrisp, horiz, renderer);
  5296. if (mark) { // updating
  5297. mark.animate({
  5298. d: markPath,
  5299. opacity: opacity
  5300. });
  5301. } else { // first time
  5302. tick.mark = renderer.path(
  5303. markPath
  5304. ).attr({
  5305. stroke: tickColor,
  5306. 'stroke-width': tickWidth,
  5307. opacity: opacity
  5308. }).add(axis.axisGroup);
  5309. }
  5310. }
  5311. // the label is created on init - now move it into place
  5312. if (label && !isNaN(x)) {
  5313. label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step);
  5314. // Apply show first and show last. If the tick is both first and last, it is
  5315. // a single centered tick, in which case we show the label anyway (#2100).
  5316. if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) ||
  5317. (tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) {
  5318. show = false;
  5319. // Handle label overflow and show or hide accordingly
  5320. } else if (!staggerLines && horiz && labelOptions.overflow === 'justify' && !tick.handleOverflow(index, xy)) {
  5321. show = false;
  5322. }
  5323. // apply step
  5324. if (step && index % step) {
  5325. // show those indices dividable by step
  5326. show = false;
  5327. }
  5328. // Set the new position, and show or hide
  5329. if (show && !isNaN(xy.y)) {
  5330. xy.opacity = opacity;
  5331. label[tick.isNew ? 'attr' : 'animate'](xy);
  5332. tick.isNew = false;
  5333. } else {
  5334. label.attr('y', -9999); // #1338
  5335. }
  5336. }
  5337. },
  5338. /**
  5339. * Destructor for the tick prototype
  5340. */
  5341. destroy: function () {
  5342. destroyObjectProperties(this, this.axis);
  5343. }
  5344. };
  5345. /**
  5346. * The object wrapper for plot lines and plot bands
  5347. * @param {Object} options
  5348. */
  5349. function PlotLineOrBand(axis, options) {
  5350. this.axis = axis;
  5351. if (options) {
  5352. this.options = options;
  5353. this.id = options.id;
  5354. }
  5355. }
  5356. PlotLineOrBand.prototype = {
  5357. /**
  5358. * Render the plot line or plot band. If it is already existing,
  5359. * move it.
  5360. */
  5361. render: function () {
  5362. var plotLine = this,
  5363. axis = plotLine.axis,
  5364. horiz = axis.horiz,
  5365. halfPointRange = (axis.pointRange || 0) / 2,
  5366. options = plotLine.options,
  5367. optionsLabel = options.label,
  5368. label = plotLine.label,
  5369. width = options.width,
  5370. to = options.to,
  5371. from = options.from,
  5372. isBand = defined(from) && defined(to),
  5373. value = options.value,
  5374. dashStyle = options.dashStyle,
  5375. svgElem = plotLine.svgElem,
  5376. path = [],
  5377. addEvent,
  5378. eventType,
  5379. xs,
  5380. ys,
  5381. x,
  5382. y,
  5383. color = options.color,
  5384. zIndex = options.zIndex,
  5385. events = options.events,
  5386. attribs,
  5387. renderer = axis.chart.renderer;
  5388. // logarithmic conversion
  5389. if (axis.isLog) {
  5390. from = log2lin(from);
  5391. to = log2lin(to);
  5392. value = log2lin(value);
  5393. }
  5394. // plot line
  5395. if (width) {
  5396. path = axis.getPlotLinePath(value, width);
  5397. attribs = {
  5398. stroke: color,
  5399. 'stroke-width': width
  5400. };
  5401. if (dashStyle) {
  5402. attribs.dashstyle = dashStyle;
  5403. }
  5404. } else if (isBand) { // plot band
  5405. // keep within plot area
  5406. from = mathMax(from, axis.min - halfPointRange);
  5407. to = mathMin(to, axis.max + halfPointRange);
  5408. path = axis.getPlotBandPath(from, to, options);
  5409. attribs = {
  5410. fill: color
  5411. };
  5412. if (options.borderWidth) {
  5413. attribs.stroke = options.borderColor;
  5414. attribs['stroke-width'] = options.borderWidth;
  5415. }
  5416. } else {
  5417. return;
  5418. }
  5419. // zIndex
  5420. if (defined(zIndex)) {
  5421. attribs.zIndex = zIndex;
  5422. }
  5423. // common for lines and bands
  5424. if (svgElem) {
  5425. if (path) {
  5426. svgElem.animate({
  5427. d: path
  5428. }, null, svgElem.onGetPath);
  5429. } else {
  5430. svgElem.hide();
  5431. svgElem.onGetPath = function () {
  5432. svgElem.show();
  5433. };
  5434. }
  5435. } else if (path && path.length) {
  5436. plotLine.svgElem = svgElem = renderer.path(path)
  5437. .attr(attribs).add();
  5438. // events
  5439. if (events) {
  5440. addEvent = function (eventType) {
  5441. svgElem.on(eventType, function (e) {
  5442. events[eventType].apply(plotLine, [e]);
  5443. });
  5444. };
  5445. for (eventType in events) {
  5446. addEvent(eventType);
  5447. }
  5448. }
  5449. }
  5450. // the plot band/line label
  5451. if (optionsLabel && defined(optionsLabel.text) && path && path.length && axis.width > 0 && axis.height > 0) {
  5452. // apply defaults
  5453. optionsLabel = merge({
  5454. align: horiz && isBand && 'center',
  5455. x: horiz ? !isBand && 4 : 10,
  5456. verticalAlign : !horiz && isBand && 'middle',
  5457. y: horiz ? isBand ? 16 : 10 : isBand ? 6 : -4,
  5458. rotation: horiz && !isBand && 90
  5459. }, optionsLabel);
  5460. // add the SVG element
  5461. if (!label) {
  5462. plotLine.label = label = renderer.text(
  5463. optionsLabel.text,
  5464. 0,
  5465. 0,
  5466. optionsLabel.useHTML
  5467. )
  5468. .attr({
  5469. align: optionsLabel.textAlign || optionsLabel.align,
  5470. rotation: optionsLabel.rotation,
  5471. zIndex: zIndex
  5472. })
  5473. .css(optionsLabel.style)
  5474. .add();
  5475. }
  5476. // get the bounding box and align the label
  5477. xs = [path[1], path[4], pick(path[6], path[1])];
  5478. ys = [path[2], path[5], pick(path[7], path[2])];
  5479. x = arrayMin(xs);
  5480. y = arrayMin(ys);
  5481. label.align(optionsLabel, false, {
  5482. x: x,
  5483. y: y,
  5484. width: arrayMax(xs) - x,
  5485. height: arrayMax(ys) - y
  5486. });
  5487. label.show();
  5488. } else if (label) { // move out of sight
  5489. label.hide();
  5490. }
  5491. // chainable
  5492. return plotLine;
  5493. },
  5494. /**
  5495. * Remove the plot line or band
  5496. */
  5497. destroy: function () {
  5498. // remove it from the lookup
  5499. erase(this.axis.plotLinesAndBands, this);
  5500. delete this.axis;
  5501. destroyObjectProperties(this);
  5502. }
  5503. };
  5504. /**
  5505. * The class for stack items
  5506. */
  5507. function StackItem(axis, options, isNegative, x, stackOption, stacking) {
  5508. var inverted = axis.chart.inverted;
  5509. this.axis = axis;
  5510. // Tells if the stack is negative
  5511. this.isNegative = isNegative;
  5512. // Save the options to be able to style the label
  5513. this.options = options;
  5514. // Save the x value to be able to position the label later
  5515. this.x = x;
  5516. // Initialize total value
  5517. this.total = null;
  5518. // This will keep each points' extremes stored by series.index
  5519. this.points = {};
  5520. // Save the stack option on the series configuration object, and whether to treat it as percent
  5521. this.stack = stackOption;
  5522. this.percent = stacking === 'percent';
  5523. // The align options and text align varies on whether the stack is negative and
  5524. // if the chart is inverted or not.
  5525. // First test the user supplied value, then use the dynamic.
  5526. this.alignOptions = {
  5527. align: options.align || (inverted ? (isNegative ? 'left' : 'right') : 'center'),
  5528. verticalAlign: options.verticalAlign || (inverted ? 'middle' : (isNegative ? 'bottom' : 'top')),
  5529. y: pick(options.y, inverted ? 4 : (isNegative ? 14 : -6)),
  5530. x: pick(options.x, inverted ? (isNegative ? -6 : 6) : 0)
  5531. };
  5532. this.textAlign = options.textAlign || (inverted ? (isNegative ? 'right' : 'left') : 'center');
  5533. }
  5534. StackItem.prototype = {
  5535. destroy: function () {
  5536. destroyObjectProperties(this, this.axis);
  5537. },
  5538. /**
  5539. * Renders the stack total label and adds it to the stack label group.
  5540. */
  5541. render: function (group) {
  5542. var options = this.options,
  5543. formatOption = options.format,
  5544. str = formatOption ?
  5545. format(formatOption, this) :
  5546. options.formatter.call(this); // format the text in the label
  5547. // Change the text to reflect the new total and set visibility to hidden in case the serie is hidden
  5548. if (this.label) {
  5549. this.label.attr({text: str, visibility: HIDDEN});
  5550. // Create new label
  5551. } else {
  5552. this.label =
  5553. this.axis.chart.renderer.text(str, 0, 0, options.useHTML) // dummy positions, actual position updated with setOffset method in columnseries
  5554. .css(options.style) // apply style
  5555. .attr({
  5556. align: this.textAlign, // fix the text-anchor
  5557. rotation: options.rotation, // rotation
  5558. visibility: HIDDEN // hidden until setOffset is called
  5559. })
  5560. .add(group); // add to the labels-group
  5561. }
  5562. },
  5563. /**
  5564. * Sets the offset that the stack has from the x value and repositions the label.
  5565. */
  5566. setOffset: function (xOffset, xWidth) {
  5567. var stackItem = this,
  5568. axis = stackItem.axis,
  5569. chart = axis.chart,
  5570. inverted = chart.inverted,
  5571. neg = this.isNegative, // special treatment is needed for negative stacks
  5572. y = axis.translate(this.percent ? 100 : this.total, 0, 0, 0, 1), // stack value translated mapped to chart coordinates
  5573. yZero = axis.translate(0), // stack origin
  5574. h = mathAbs(y - yZero), // stack height
  5575. x = chart.xAxis[0].translate(this.x) + xOffset, // stack x position
  5576. plotHeight = chart.plotHeight,
  5577. stackBox = { // this is the box for the complete stack
  5578. x: inverted ? (neg ? y : y - h) : x,
  5579. y: inverted ? plotHeight - x - xWidth : (neg ? (plotHeight - y - h) : plotHeight - y),
  5580. width: inverted ? h : xWidth,
  5581. height: inverted ? xWidth : h
  5582. },
  5583. label = this.label,
  5584. alignAttr;
  5585. if (label) {
  5586. label.align(this.alignOptions, null, stackBox); // align the label to the box
  5587. // Set visibility (#678)
  5588. alignAttr = label.alignAttr;
  5589. label.attr({
  5590. visibility: this.options.crop === false || chart.isInsidePlot(alignAttr.x, alignAttr.y) ?
  5591. (hasSVG ? 'inherit' : VISIBLE) :
  5592. HIDDEN
  5593. });
  5594. }
  5595. }
  5596. };
  5597. /**
  5598. * Create a new axis object
  5599. * @param {Object} chart
  5600. * @param {Object} options
  5601. */
  5602. function Axis() {
  5603. this.init.apply(this, arguments);
  5604. }
  5605. Axis.prototype = {
  5606. /**
  5607. * Default options for the X axis - the Y axis has extended defaults
  5608. */
  5609. defaultOptions: {
  5610. // allowDecimals: null,
  5611. // alternateGridColor: null,
  5612. // categories: [],
  5613. dateTimeLabelFormats: {
  5614. millisecond: '%H:%M:%S.%L',
  5615. second: '%H:%M:%S',
  5616. minute: '%H:%M',
  5617. hour: '%H:%M',
  5618. day: '%e. %b',
  5619. week: '%e. %b',
  5620. month: '%b \'%y',
  5621. year: '%Y'
  5622. },
  5623. endOnTick: false,
  5624. gridLineColor: '#C0C0C0',
  5625. // gridLineDashStyle: 'solid',
  5626. // gridLineWidth: 0,
  5627. // reversed: false,
  5628. labels: defaultLabelOptions,
  5629. // { step: null },
  5630. lineColor: '#C0D0E0',
  5631. lineWidth: 1,
  5632. //linkedTo: null,
  5633. //max: undefined,
  5634. //min: undefined,
  5635. minPadding: 0.01,
  5636. maxPadding: 0.01,
  5637. //minRange: null,
  5638. minorGridLineColor: '#E0E0E0',
  5639. // minorGridLineDashStyle: null,
  5640. minorGridLineWidth: 1,
  5641. minorTickColor: '#A0A0A0',
  5642. //minorTickInterval: null,
  5643. minorTickLength: 2,
  5644. minorTickPosition: 'outside', // inside or outside
  5645. //minorTickWidth: 0,
  5646. //opposite: false,
  5647. //offset: 0,
  5648. //plotBands: [{
  5649. // events: {},
  5650. // zIndex: 1,
  5651. // labels: { align, x, verticalAlign, y, style, rotation, textAlign }
  5652. //}],
  5653. //plotLines: [{
  5654. // events: {}
  5655. // dashStyle: {}
  5656. // zIndex:
  5657. // labels: { align, x, verticalAlign, y, style, rotation, textAlign }
  5658. //}],
  5659. //reversed: false,
  5660. // showFirstLabel: true,
  5661. // showLastLabel: true,
  5662. startOfWeek: 1,
  5663. startOnTick: false,
  5664. tickColor: '#C0D0E0',
  5665. //tickInterval: null,
  5666. tickLength: 5,
  5667. tickmarkPlacement: 'between', // on or between
  5668. tickPixelInterval: 100,
  5669. tickPosition: 'outside',
  5670. tickWidth: 1,
  5671. title: {
  5672. //text: null,
  5673. align: 'middle', // low, middle or high
  5674. //margin: 0 for horizontal, 10 for vertical axes,
  5675. //rotation: 0,
  5676. //side: 'outside',
  5677. style: {
  5678. color: '#4d759e',
  5679. //font: defaultFont.replace('normal', 'bold')
  5680. fontWeight: 'bold'
  5681. }
  5682. //x: 0,
  5683. //y: 0
  5684. },
  5685. type: 'linear' // linear, logarithmic or datetime
  5686. },
  5687. /**
  5688. * This options set extends the defaultOptions for Y axes
  5689. */
  5690. defaultYAxisOptions: {
  5691. endOnTick: true,
  5692. gridLineWidth: 1,
  5693. tickPixelInterval: 72,
  5694. showLastLabel: true,
  5695. labels: {
  5696. x: -8,
  5697. y: 3
  5698. },
  5699. lineWidth: 0,
  5700. maxPadding: 0.05,
  5701. minPadding: 0.05,
  5702. startOnTick: true,
  5703. tickWidth: 0,
  5704. title: {
  5705. rotation: 270,
  5706. text: 'Values'
  5707. },
  5708. stackLabels: {
  5709. enabled: false,
  5710. //align: dynamic,
  5711. //y: dynamic,
  5712. //x: dynamic,
  5713. //verticalAlign: dynamic,
  5714. //textAlign: dynamic,
  5715. //rotation: 0,
  5716. formatter: function () {
  5717. return numberFormat(this.total, -1);
  5718. },
  5719. style: defaultLabelOptions.style
  5720. }
  5721. },
  5722. /**
  5723. * These options extend the defaultOptions for left axes
  5724. */
  5725. defaultLeftAxisOptions: {
  5726. labels: {
  5727. x: -8,
  5728. y: null
  5729. },
  5730. title: {
  5731. rotation: 270
  5732. }
  5733. },
  5734. /**
  5735. * These options extend the defaultOptions for right axes
  5736. */
  5737. defaultRightAxisOptions: {
  5738. labels: {
  5739. x: 8,
  5740. y: null
  5741. },
  5742. title: {
  5743. rotation: 90
  5744. }
  5745. },
  5746. /**
  5747. * These options extend the defaultOptions for bottom axes
  5748. */
  5749. defaultBottomAxisOptions: {
  5750. labels: {
  5751. x: 0,
  5752. y: 14
  5753. // overflow: undefined,
  5754. // staggerLines: null
  5755. },
  5756. title: {
  5757. rotation: 0
  5758. }
  5759. },
  5760. /**
  5761. * These options extend the defaultOptions for left axes
  5762. */
  5763. defaultTopAxisOptions: {
  5764. labels: {
  5765. x: 0,
  5766. y: -5
  5767. // overflow: undefined
  5768. // staggerLines: null
  5769. },
  5770. title: {
  5771. rotation: 0
  5772. }
  5773. },
  5774. /**
  5775. * Initialize the axis
  5776. */
  5777. init: function (chart, userOptions) {
  5778. var isXAxis = userOptions.isX,
  5779. axis = this;
  5780. // Flag, is the axis horizontal
  5781. axis.horiz = chart.inverted ? !isXAxis : isXAxis;
  5782. // Flag, isXAxis
  5783. axis.isXAxis = isXAxis;
  5784. axis.xOrY = isXAxis ? 'x' : 'y';
  5785. axis.opposite = userOptions.opposite; // needed in setOptions
  5786. axis.side = axis.horiz ?
  5787. (axis.opposite ? 0 : 2) : // top : bottom
  5788. (axis.opposite ? 1 : 3); // right : left
  5789. axis.setOptions(userOptions);
  5790. var options = this.options,
  5791. type = options.type,
  5792. isDatetimeAxis = type === 'datetime';
  5793. axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format
  5794. // Flag, stagger lines or not
  5795. axis.userOptions = userOptions;
  5796. //axis.axisTitleMargin = UNDEFINED,// = options.title.margin,
  5797. axis.minPixelPadding = 0;
  5798. //axis.ignoreMinPadding = UNDEFINED; // can be set to true by a column or bar series
  5799. //axis.ignoreMaxPadding = UNDEFINED;
  5800. axis.chart = chart;
  5801. axis.reversed = options.reversed;
  5802. axis.zoomEnabled = options.zoomEnabled !== false;
  5803. // Initial categories
  5804. axis.categories = options.categories || type === 'category';
  5805. // Elements
  5806. //axis.axisGroup = UNDEFINED;
  5807. //axis.gridGroup = UNDEFINED;
  5808. //axis.axisTitle = UNDEFINED;
  5809. //axis.axisLine = UNDEFINED;
  5810. // Shorthand types
  5811. axis.isLog = type === 'logarithmic';
  5812. axis.isDatetimeAxis = isDatetimeAxis;
  5813. // Flag, if axis is linked to another axis
  5814. axis.isLinked = defined(options.linkedTo);
  5815. // Linked axis.
  5816. //axis.linkedParent = UNDEFINED;
  5817. // Tick positions
  5818. //axis.tickPositions = UNDEFINED; // array containing predefined positions
  5819. // Tick intervals
  5820. //axis.tickInterval = UNDEFINED;
  5821. //axis.minorTickInterval = UNDEFINED;
  5822. axis.tickmarkOffset = (axis.categories && options.tickmarkPlacement === 'between') ? 0.5 : 0;
  5823. // Major ticks
  5824. axis.ticks = {};
  5825. // Minor ticks
  5826. axis.minorTicks = {};
  5827. //axis.tickAmount = UNDEFINED;
  5828. // List of plotLines/Bands
  5829. axis.plotLinesAndBands = [];
  5830. // Alternate bands
  5831. axis.alternateBands = {};
  5832. // Axis metrics
  5833. //axis.left = UNDEFINED;
  5834. //axis.top = UNDEFINED;
  5835. //axis.width = UNDEFINED;
  5836. //axis.height = UNDEFINED;
  5837. //axis.bottom = UNDEFINED;
  5838. //axis.right = UNDEFINED;
  5839. //axis.transA = UNDEFINED;
  5840. //axis.transB = UNDEFINED;
  5841. //axis.oldTransA = UNDEFINED;
  5842. axis.len = 0;
  5843. //axis.oldMin = UNDEFINED;
  5844. //axis.oldMax = UNDEFINED;
  5845. //axis.oldUserMin = UNDEFINED;
  5846. //axis.oldUserMax = UNDEFINED;
  5847. //axis.oldAxisLength = UNDEFINED;
  5848. axis.minRange = axis.userMinRange = options.minRange || options.maxZoom;
  5849. axis.range = options.range;
  5850. axis.offset = options.offset || 0;
  5851. // Dictionary for stacks
  5852. axis.stacks = {};
  5853. axis.oldStacks = {};
  5854. // Dictionary for stacks max values
  5855. axis.stackExtremes = {};
  5856. // Min and max in the data
  5857. //axis.dataMin = UNDEFINED,
  5858. //axis.dataMax = UNDEFINED,
  5859. // The axis range
  5860. axis.max = null;
  5861. axis.min = null;
  5862. // User set min and max
  5863. //axis.userMin = UNDEFINED,
  5864. //axis.userMax = UNDEFINED,
  5865. // Run Axis
  5866. var eventType,
  5867. events = axis.options.events;
  5868. // Register
  5869. if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update()
  5870. chart.axes.push(axis);
  5871. chart[isXAxis ? 'xAxis' : 'yAxis'].push(axis);
  5872. }
  5873. axis.series = axis.series || []; // populated by Series
  5874. // inverted charts have reversed xAxes as default
  5875. if (chart.inverted && isXAxis && axis.reversed === UNDEFINED) {
  5876. axis.reversed = true;
  5877. }
  5878. axis.removePlotBand = axis.removePlotBandOrLine;
  5879. axis.removePlotLine = axis.removePlotBandOrLine;
  5880. // register event listeners
  5881. for (eventType in events) {
  5882. addEvent(axis, eventType, events[eventType]);
  5883. }
  5884. // extend logarithmic axis
  5885. if (axis.isLog) {
  5886. axis.val2lin = log2lin;
  5887. axis.lin2val = lin2log;
  5888. }
  5889. },
  5890. /**
  5891. * Merge and set options
  5892. */
  5893. setOptions: function (userOptions) {
  5894. this.options = merge(
  5895. this.defaultOptions,
  5896. this.isXAxis ? {} : this.defaultYAxisOptions,
  5897. [this.defaultTopAxisOptions, this.defaultRightAxisOptions,
  5898. this.defaultBottomAxisOptions, this.defaultLeftAxisOptions][this.side],
  5899. merge(
  5900. defaultOptions[this.isXAxis ? 'xAxis' : 'yAxis'], // if set in setOptions (#1053)
  5901. userOptions
  5902. )
  5903. );
  5904. },
  5905. /**
  5906. * Update the axis with a new options structure
  5907. */
  5908. update: function (newOptions, redraw) {
  5909. var chart = this.chart;
  5910. newOptions = chart.options[this.xOrY + 'Axis'][this.options.index] = merge(this.userOptions, newOptions);
  5911. this.destroy(true);
  5912. this._addedPlotLB = this.userMin = this.userMax = UNDEFINED; // #1611, #2306
  5913. this.init(chart, extend(newOptions, { events: UNDEFINED }));
  5914. chart.isDirtyBox = true;
  5915. if (pick(redraw, true)) {
  5916. chart.redraw();
  5917. }
  5918. },
  5919. /**
  5920. * Remove the axis from the chart
  5921. */
  5922. remove: function (redraw) {
  5923. var chart = this.chart,
  5924. key = this.xOrY + 'Axis'; // xAxis or yAxis
  5925. // Remove associated series
  5926. each(this.series, function (series) {
  5927. series.remove(false);
  5928. });
  5929. // Remove the axis
  5930. erase(chart.axes, this);
  5931. erase(chart[key], this);
  5932. chart.options[key].splice(this.options.index, 1);
  5933. each(chart[key], function (axis, i) { // Re-index, #1706
  5934. axis.options.index = i;
  5935. });
  5936. this.destroy();
  5937. chart.isDirtyBox = true;
  5938. if (pick(redraw, true)) {
  5939. chart.redraw();
  5940. }
  5941. },
  5942. /**
  5943. * The default label formatter. The context is a special config object for the label.
  5944. */
  5945. defaultLabelFormatter: function () {
  5946. var axis = this.axis,
  5947. value = this.value,
  5948. categories = axis.categories,
  5949. dateTimeLabelFormat = this.dateTimeLabelFormat,
  5950. numericSymbols = defaultOptions.lang.numericSymbols,
  5951. i = numericSymbols && numericSymbols.length,
  5952. multi,
  5953. ret,
  5954. formatOption = axis.options.labels.format,
  5955. // make sure the same symbol is added for all labels on a linear axis
  5956. numericSymbolDetector = axis.isLog ? value : axis.tickInterval;
  5957. if (formatOption) {
  5958. ret = format(formatOption, this);
  5959. } else if (categories) {
  5960. ret = value;
  5961. } else if (dateTimeLabelFormat) { // datetime axis
  5962. ret = dateFormat(dateTimeLabelFormat, value);
  5963. } else if (i && numericSymbolDetector >= 1000) {
  5964. // Decide whether we should add a numeric symbol like k (thousands) or M (millions).
  5965. // If we are to enable this in tooltip or other places as well, we can move this
  5966. // logic to the numberFormatter and enable it by a parameter.
  5967. while (i-- && ret === UNDEFINED) {
  5968. multi = Math.pow(1000, i + 1);
  5969. if (numericSymbolDetector >= multi && numericSymbols[i] !== null) {
  5970. ret = numberFormat(value / multi, -1) + numericSymbols[i];
  5971. }
  5972. }
  5973. }
  5974. if (ret === UNDEFINED) {
  5975. if (value >= 1000) { // add thousands separators
  5976. ret = numberFormat(value, 0);
  5977. } else { // small numbers
  5978. ret = numberFormat(value, -1);
  5979. }
  5980. }
  5981. return ret;
  5982. },
  5983. /**
  5984. * Get the minimum and maximum for the series of each axis
  5985. */
  5986. getSeriesExtremes: function () {
  5987. var axis = this,
  5988. chart = axis.chart;
  5989. axis.hasVisibleSeries = false;
  5990. // reset dataMin and dataMax in case we're redrawing
  5991. axis.dataMin = axis.dataMax = null;
  5992. // reset cached stacking extremes
  5993. axis.stackExtremes = {};
  5994. axis.buildStacks();
  5995. // loop through this axis' series
  5996. each(axis.series, function (series) {
  5997. if (series.visible || !chart.options.chart.ignoreHiddenSeries) {
  5998. var seriesOptions = series.options,
  5999. xData,
  6000. threshold = seriesOptions.threshold,
  6001. seriesDataMin,
  6002. seriesDataMax;
  6003. axis.hasVisibleSeries = true;
  6004. // Validate threshold in logarithmic axes
  6005. if (axis.isLog && threshold <= 0) {
  6006. threshold = null;
  6007. }
  6008. // Get dataMin and dataMax for X axes
  6009. if (axis.isXAxis) {
  6010. xData = series.xData;
  6011. if (xData.length) {
  6012. axis.dataMin = mathMin(pick(axis.dataMin, xData[0]), arrayMin(xData));
  6013. axis.dataMax = mathMax(pick(axis.dataMax, xData[0]), arrayMax(xData));
  6014. }
  6015. // Get dataMin and dataMax for Y axes, as well as handle stacking and processed data
  6016. } else {
  6017. // Get this particular series extremes
  6018. series.getExtremes();
  6019. seriesDataMax = series.dataMax;
  6020. seriesDataMin = series.dataMin;
  6021. // Get the dataMin and dataMax so far. If percentage is used, the min and max are
  6022. // always 0 and 100. If seriesDataMin and seriesDataMax is null, then series
  6023. // doesn't have active y data, we continue with nulls
  6024. if (defined(seriesDataMin) && defined(seriesDataMax)) {
  6025. axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin);
  6026. axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax);
  6027. }
  6028. // Adjust to threshold
  6029. if (defined(threshold)) {
  6030. if (axis.dataMin >= threshold) {
  6031. axis.dataMin = threshold;
  6032. axis.ignoreMinPadding = true;
  6033. } else if (axis.dataMax < threshold) {
  6034. axis.dataMax = threshold;
  6035. axis.ignoreMaxPadding = true;
  6036. }
  6037. }
  6038. }
  6039. }
  6040. });
  6041. },
  6042. /**
  6043. * Translate from axis value to pixel position on the chart, or back
  6044. *
  6045. */
  6046. translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacement) {
  6047. var axis = this,
  6048. axisLength = axis.len,
  6049. sign = 1,
  6050. cvsOffset = 0,
  6051. localA = old ? axis.oldTransA : axis.transA,
  6052. localMin = old ? axis.oldMin : axis.min,
  6053. returnValue,
  6054. minPixelPadding = axis.minPixelPadding,
  6055. postTranslate = (axis.options.ordinal || (axis.isLog && handleLog)) && axis.lin2val;
  6056. if (!localA) {
  6057. localA = axis.transA;
  6058. }
  6059. // In vertical axes, the canvas coordinates start from 0 at the top like in
  6060. // SVG.
  6061. if (cvsCoord) {
  6062. sign *= -1; // canvas coordinates inverts the value
  6063. cvsOffset = axisLength;
  6064. }
  6065. // Handle reversed axis
  6066. if (axis.reversed) {
  6067. sign *= -1;
  6068. cvsOffset -= sign * axisLength;
  6069. }
  6070. // From pixels to value
  6071. if (backwards) { // reverse translation
  6072. val = val * sign + cvsOffset;
  6073. val -= minPixelPadding;
  6074. returnValue = val / localA + localMin; // from chart pixel to value
  6075. if (postTranslate) { // log and ordinal axes
  6076. returnValue = axis.lin2val(returnValue);
  6077. }
  6078. // From value to pixels
  6079. } else {
  6080. if (postTranslate) { // log and ordinal axes
  6081. val = axis.val2lin(val);
  6082. }
  6083. if (pointPlacement === 'between') {
  6084. pointPlacement = 0.5;
  6085. }
  6086. returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) +
  6087. (isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0);
  6088. }
  6089. return returnValue;
  6090. },
  6091. /**
  6092. * Utility method to translate an axis value to pixel position.
  6093. * @param {Number} value A value in terms of axis units
  6094. * @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart
  6095. * or just the axis/pane itself.
  6096. */
  6097. toPixels: function (value, paneCoordinates) {
  6098. return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos);
  6099. },
  6100. /*
  6101. * Utility method to translate a pixel position in to an axis value
  6102. * @param {Number} pixel The pixel value coordinate
  6103. * @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the
  6104. * axis/pane itself.
  6105. */
  6106. toValue: function (pixel, paneCoordinates) {
  6107. return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true);
  6108. },
  6109. /**
  6110. * Create the path for a plot line that goes from the given value on
  6111. * this axis, across the plot to the opposite side
  6112. * @param {Number} value
  6113. * @param {Number} lineWidth Used for calculation crisp line
  6114. * @param {Number] old Use old coordinates (for resizing and rescaling)
  6115. */
  6116. getPlotLinePath: function (value, lineWidth, old, force) {
  6117. var axis = this,
  6118. chart = axis.chart,
  6119. axisLeft = axis.left,
  6120. axisTop = axis.top,
  6121. x1,
  6122. y1,
  6123. x2,
  6124. y2,
  6125. translatedValue = axis.translate(value, null, null, old),
  6126. cHeight = (old && chart.oldChartHeight) || chart.chartHeight,
  6127. cWidth = (old && chart.oldChartWidth) || chart.chartWidth,
  6128. skip,
  6129. transB = axis.transB;
  6130. x1 = x2 = mathRound(translatedValue + transB);
  6131. y1 = y2 = mathRound(cHeight - translatedValue - transB);
  6132. if (isNaN(translatedValue)) { // no min or max
  6133. skip = true;
  6134. } else if (axis.horiz) {
  6135. y1 = axisTop;
  6136. y2 = cHeight - axis.bottom;
  6137. if (x1 < axisLeft || x1 > axisLeft + axis.width) {
  6138. skip = true;
  6139. }
  6140. } else {
  6141. x1 = axisLeft;
  6142. x2 = cWidth - axis.right;
  6143. if (y1 < axisTop || y1 > axisTop + axis.height) {
  6144. skip = true;
  6145. }
  6146. }
  6147. return skip && !force ?
  6148. null :
  6149. chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 0);
  6150. },
  6151. /**
  6152. * Create the path for a plot band
  6153. */
  6154. getPlotBandPath: function (from, to) {
  6155. var toPath = this.getPlotLinePath(to),
  6156. path = this.getPlotLinePath(from);
  6157. if (path && toPath) {
  6158. path.push(
  6159. toPath[4],
  6160. toPath[5],
  6161. toPath[1],
  6162. toPath[2]
  6163. );
  6164. } else { // outside the axis area
  6165. path = null;
  6166. }
  6167. return path;
  6168. },
  6169. /**
  6170. * Set the tick positions of a linear axis to round values like whole tens or every five.
  6171. */
  6172. getLinearTickPositions: function (tickInterval, min, max) {
  6173. var pos,
  6174. lastPos,
  6175. roundedMin = correctFloat(mathFloor(min / tickInterval) * tickInterval),
  6176. roundedMax = correctFloat(mathCeil(max / tickInterval) * tickInterval),
  6177. tickPositions = [];
  6178. // Populate the intermediate values
  6179. pos = roundedMin;
  6180. while (pos <= roundedMax) {
  6181. // Place the tick on the rounded value
  6182. tickPositions.push(pos);
  6183. // Always add the raw tickInterval, not the corrected one.
  6184. pos = correctFloat(pos + tickInterval);
  6185. // If the interval is not big enough in the current min - max range to actually increase
  6186. // the loop variable, we need to break out to prevent endless loop. Issue #619
  6187. if (pos === lastPos) {
  6188. break;
  6189. }
  6190. // Record the last value
  6191. lastPos = pos;
  6192. }
  6193. return tickPositions;
  6194. },
  6195. /**
  6196. * Set the tick positions of a logarithmic axis
  6197. */
  6198. getLogTickPositions: function (interval, min, max, minor) {
  6199. var axis = this,
  6200. options = axis.options,
  6201. axisLength = axis.len,
  6202. // Since we use this method for both major and minor ticks,
  6203. // use a local variable and return the result
  6204. positions = [];
  6205. // Reset
  6206. if (!minor) {
  6207. axis._minorAutoInterval = null;
  6208. }
  6209. // First case: All ticks fall on whole logarithms: 1, 10, 100 etc.
  6210. if (interval >= 0.5) {
  6211. interval = mathRound(interval);
  6212. positions = axis.getLinearTickPositions(interval, min, max);
  6213. // Second case: We need intermediary ticks. For example
  6214. // 1, 2, 4, 6, 8, 10, 20, 40 etc.
  6215. } else if (interval >= 0.08) {
  6216. var roundedMin = mathFloor(min),
  6217. intermediate,
  6218. i,
  6219. j,
  6220. len,
  6221. pos,
  6222. lastPos,
  6223. break2;
  6224. if (interval > 0.3) {
  6225. intermediate = [1, 2, 4];
  6226. } else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc
  6227. intermediate = [1, 2, 4, 6, 8];
  6228. } else { // 0.1 equals ten minor ticks per 1, 10, 100 etc
  6229. intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  6230. }
  6231. for (i = roundedMin; i < max + 1 && !break2; i++) {
  6232. len = intermediate.length;
  6233. for (j = 0; j < len && !break2; j++) {
  6234. pos = log2lin(lin2log(i) * intermediate[j]);
  6235. if (pos > min && (!minor || lastPos <= max)) { // #1670
  6236. positions.push(lastPos);
  6237. }
  6238. if (lastPos > max) {
  6239. break2 = true;
  6240. }
  6241. lastPos = pos;
  6242. }
  6243. }
  6244. // Third case: We are so deep in between whole logarithmic values that
  6245. // we might as well handle the tick positions like a linear axis. For
  6246. // example 1.01, 1.02, 1.03, 1.04.
  6247. } else {
  6248. var realMin = lin2log(min),
  6249. realMax = lin2log(max),
  6250. tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'],
  6251. filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption,
  6252. tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1),
  6253. totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength;
  6254. interval = pick(
  6255. filteredTickIntervalOption,
  6256. axis._minorAutoInterval,
  6257. (realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1)
  6258. );
  6259. interval = normalizeTickInterval(
  6260. interval,
  6261. null,
  6262. getMagnitude(interval)
  6263. );
  6264. positions = map(axis.getLinearTickPositions(
  6265. interval,
  6266. realMin,
  6267. realMax
  6268. ), log2lin);
  6269. if (!minor) {
  6270. axis._minorAutoInterval = interval / 5;
  6271. }
  6272. }
  6273. // Set the axis-level tickInterval variable
  6274. if (!minor) {
  6275. axis.tickInterval = interval;
  6276. }
  6277. return positions;
  6278. },
  6279. /**
  6280. * Return the minor tick positions. For logarithmic axes, reuse the same logic
  6281. * as for major ticks.
  6282. */
  6283. getMinorTickPositions: function () {
  6284. var axis = this,
  6285. options = axis.options,
  6286. tickPositions = axis.tickPositions,
  6287. minorTickInterval = axis.minorTickInterval,
  6288. minorTickPositions = [],
  6289. pos,
  6290. i,
  6291. len;
  6292. if (axis.isLog) {
  6293. len = tickPositions.length;
  6294. for (i = 1; i < len; i++) {
  6295. minorTickPositions = minorTickPositions.concat(
  6296. axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true)
  6297. );
  6298. }
  6299. } else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314
  6300. minorTickPositions = minorTickPositions.concat(
  6301. getTimeTicks(
  6302. normalizeTimeTickInterval(minorTickInterval),
  6303. axis.min,
  6304. axis.max,
  6305. options.startOfWeek
  6306. )
  6307. );
  6308. if (minorTickPositions[0] < axis.min) {
  6309. minorTickPositions.shift();
  6310. }
  6311. } else {
  6312. for (pos = axis.min + (tickPositions[0] - axis.min) % minorTickInterval; pos <= axis.max; pos += minorTickInterval) {
  6313. minorTickPositions.push(pos);
  6314. }
  6315. }
  6316. return minorTickPositions;
  6317. },
  6318. /**
  6319. * Adjust the min and max for the minimum range. Keep in mind that the series data is
  6320. * not yet processed, so we don't have information on data cropping and grouping, or
  6321. * updated axis.pointRange or series.pointRange. The data can't be processed until
  6322. * we have finally established min and max.
  6323. */
  6324. adjustForMinRange: function () {
  6325. var axis = this,
  6326. options = axis.options,
  6327. min = axis.min,
  6328. max = axis.max,
  6329. zoomOffset,
  6330. spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange,
  6331. closestDataRange,
  6332. i,
  6333. distance,
  6334. xData,
  6335. loopLength,
  6336. minArgs,
  6337. maxArgs;
  6338. // Set the automatic minimum range based on the closest point distance
  6339. if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) {
  6340. if (defined(options.min) || defined(options.max)) {
  6341. axis.minRange = null; // don't do this again
  6342. } else {
  6343. // Find the closest distance between raw data points, as opposed to
  6344. // closestPointRange that applies to processed points (cropped and grouped)
  6345. each(axis.series, function (series) {
  6346. xData = series.xData;
  6347. loopLength = series.xIncrement ? 1 : xData.length - 1;
  6348. for (i = loopLength; i > 0; i--) {
  6349. distance = xData[i] - xData[i - 1];
  6350. if (closestDataRange === UNDEFINED || distance < closestDataRange) {
  6351. closestDataRange = distance;
  6352. }
  6353. }
  6354. });
  6355. axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin);
  6356. }
  6357. }
  6358. // if minRange is exceeded, adjust
  6359. if (max - min < axis.minRange) {
  6360. var minRange = axis.minRange;
  6361. zoomOffset = (minRange - max + min) / 2;
  6362. // if min and max options have been set, don't go beyond it
  6363. minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)];
  6364. if (spaceAvailable) { // if space is available, stay within the data range
  6365. minArgs[2] = axis.dataMin;
  6366. }
  6367. min = arrayMax(minArgs);
  6368. maxArgs = [min + minRange, pick(options.max, min + minRange)];
  6369. if (spaceAvailable) { // if space is availabe, stay within the data range
  6370. maxArgs[2] = axis.dataMax;
  6371. }
  6372. max = arrayMin(maxArgs);
  6373. // now if the max is adjusted, adjust the min back
  6374. if (max - min < minRange) {
  6375. minArgs[0] = max - minRange;
  6376. minArgs[1] = pick(options.min, max - minRange);
  6377. min = arrayMax(minArgs);
  6378. }
  6379. }
  6380. // Record modified extremes
  6381. axis.min = min;
  6382. axis.max = max;
  6383. },
  6384. /**
  6385. * Update translation information
  6386. */
  6387. setAxisTranslation: function (saveOld) {
  6388. var axis = this,
  6389. range = axis.max - axis.min,
  6390. pointRange = 0,
  6391. closestPointRange,
  6392. minPointOffset = 0,
  6393. pointRangePadding = 0,
  6394. linkedParent = axis.linkedParent,
  6395. ordinalCorrection,
  6396. transA = axis.transA;
  6397. // adjust translation for padding
  6398. if (axis.isXAxis) {
  6399. if (linkedParent) {
  6400. minPointOffset = linkedParent.minPointOffset;
  6401. pointRangePadding = linkedParent.pointRangePadding;
  6402. } else {
  6403. each(axis.series, function (series) {
  6404. var seriesPointRange = series.pointRange,
  6405. pointPlacement = series.options.pointPlacement,
  6406. seriesClosestPointRange = series.closestPointRange;
  6407. if (seriesPointRange > range) { // #1446
  6408. seriesPointRange = 0;
  6409. }
  6410. pointRange = mathMax(pointRange, seriesPointRange);
  6411. // minPointOffset is the value padding to the left of the axis in order to make
  6412. // room for points with a pointRange, typically columns. When the pointPlacement option
  6413. // is 'between' or 'on', this padding does not apply.
  6414. minPointOffset = mathMax(
  6415. minPointOffset,
  6416. isString(pointPlacement) ? 0 : seriesPointRange / 2
  6417. );
  6418. // Determine the total padding needed to the length of the axis to make room for the
  6419. // pointRange. If the series' pointPlacement is 'on', no padding is added.
  6420. pointRangePadding = mathMax(
  6421. pointRangePadding,
  6422. pointPlacement === 'on' ? 0 : seriesPointRange
  6423. );
  6424. // Set the closestPointRange
  6425. if (!series.noSharedTooltip && defined(seriesClosestPointRange)) {
  6426. closestPointRange = defined(closestPointRange) ?
  6427. mathMin(closestPointRange, seriesClosestPointRange) :
  6428. seriesClosestPointRange;
  6429. }
  6430. });
  6431. }
  6432. // Record minPointOffset and pointRangePadding
  6433. ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853
  6434. axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection;
  6435. axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection;
  6436. // pointRange means the width reserved for each point, like in a column chart
  6437. axis.pointRange = mathMin(pointRange, range);
  6438. // closestPointRange means the closest distance between points. In columns
  6439. // it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange
  6440. // is some other value
  6441. axis.closestPointRange = closestPointRange;
  6442. }
  6443. // Secondary values
  6444. if (saveOld) {
  6445. axis.oldTransA = transA;
  6446. }
  6447. axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1);
  6448. axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend
  6449. axis.minPixelPadding = transA * minPointOffset;
  6450. },
  6451. /**
  6452. * Set the tick positions to round values and optionally extend the extremes
  6453. * to the nearest tick
  6454. */
  6455. setTickPositions: function (secondPass) {
  6456. var axis = this,
  6457. chart = axis.chart,
  6458. options = axis.options,
  6459. isLog = axis.isLog,
  6460. isDatetimeAxis = axis.isDatetimeAxis,
  6461. isXAxis = axis.isXAxis,
  6462. isLinked = axis.isLinked,
  6463. tickPositioner = axis.options.tickPositioner,
  6464. maxPadding = options.maxPadding,
  6465. minPadding = options.minPadding,
  6466. length,
  6467. linkedParentExtremes,
  6468. tickIntervalOption = options.tickInterval,
  6469. minTickIntervalOption = options.minTickInterval,
  6470. tickPixelIntervalOption = options.tickPixelInterval,
  6471. tickPositions,
  6472. keepTwoTicksOnly,
  6473. categories = axis.categories;
  6474. // linked axis gets the extremes from the parent axis
  6475. if (isLinked) {
  6476. axis.linkedParent = chart[isXAxis ? 'xAxis' : 'yAxis'][options.linkedTo];
  6477. linkedParentExtremes = axis.linkedParent.getExtremes();
  6478. axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin);
  6479. axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax);
  6480. if (options.type !== axis.linkedParent.options.type) {
  6481. error(11, 1); // Can't link axes of different type
  6482. }
  6483. } else { // initial min and max from the extreme data values
  6484. axis.min = pick(axis.userMin, options.min, axis.dataMin);
  6485. axis.max = pick(axis.userMax, options.max, axis.dataMax);
  6486. }
  6487. if (isLog) {
  6488. if (!secondPass && mathMin(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978
  6489. error(10, 1); // Can't plot negative values on log axis
  6490. }
  6491. axis.min = correctFloat(log2lin(axis.min)); // correctFloat cures #934
  6492. axis.max = correctFloat(log2lin(axis.max));
  6493. }
  6494. // handle zoomed range
  6495. if (axis.range) {
  6496. axis.userMin = axis.min = mathMax(axis.min, axis.max - axis.range); // #618
  6497. axis.userMax = axis.max;
  6498. if (secondPass) {
  6499. axis.range = null; // don't use it when running setExtremes
  6500. }
  6501. }
  6502. // Hook for adjusting this.min and this.max. Used by bubble series.
  6503. if (axis.beforePadding) {
  6504. axis.beforePadding();
  6505. }
  6506. // adjust min and max for the minimum range
  6507. axis.adjustForMinRange();
  6508. // Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding
  6509. // into account, we do this after computing tick interval (#1337).
  6510. if (!categories && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) {
  6511. length = axis.max - axis.min;
  6512. if (length) {
  6513. if (!defined(options.min) && !defined(axis.userMin) && minPadding && (axis.dataMin < 0 || !axis.ignoreMinPadding)) {
  6514. axis.min -= length * minPadding;
  6515. }
  6516. if (!defined(options.max) && !defined(axis.userMax) && maxPadding && (axis.dataMax > 0 || !axis.ignoreMaxPadding)) {
  6517. axis.max += length * maxPadding;
  6518. }
  6519. }
  6520. }
  6521. // get tickInterval
  6522. if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) {
  6523. axis.tickInterval = 1;
  6524. } else if (isLinked && !tickIntervalOption &&
  6525. tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) {
  6526. axis.tickInterval = axis.linkedParent.tickInterval;
  6527. } else {
  6528. axis.tickInterval = pick(
  6529. tickIntervalOption,
  6530. categories ? // for categoried axis, 1 is default, for linear axis use tickPix
  6531. 1 :
  6532. // don't let it be more than the data range
  6533. (axis.max - axis.min) * tickPixelIntervalOption / mathMax(axis.len, tickPixelIntervalOption)
  6534. );
  6535. // For squished axes, set only two ticks
  6536. if (!defined(tickIntervalOption) && axis.len < tickPixelIntervalOption && !this.isRadial) {
  6537. keepTwoTicksOnly = true;
  6538. axis.tickInterval /= 4; // tick extremes closer to the real values
  6539. }
  6540. }
  6541. // Now we're finished detecting min and max, crop and group series data. This
  6542. // is in turn needed in order to find tick positions in ordinal axes.
  6543. if (isXAxis && !secondPass) {
  6544. each(axis.series, function (series) {
  6545. series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax);
  6546. });
  6547. }
  6548. // set the translation factor used in translate function
  6549. axis.setAxisTranslation(true);
  6550. // hook for ordinal axes and radial axes
  6551. if (axis.beforeSetTickPositions) {
  6552. axis.beforeSetTickPositions();
  6553. }
  6554. // hook for extensions, used in Highstock ordinal axes
  6555. if (axis.postProcessTickInterval) {
  6556. axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval);
  6557. }
  6558. // In column-like charts, don't cramp in more ticks than there are points (#1943)
  6559. if (axis.pointRange) {
  6560. axis.tickInterval = mathMax(axis.pointRange, axis.tickInterval);
  6561. }
  6562. // Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined.
  6563. if (!tickIntervalOption && axis.tickInterval < minTickIntervalOption) {
  6564. axis.tickInterval = minTickIntervalOption;
  6565. }
  6566. // for linear axes, get magnitude and normalize the interval
  6567. if (!isDatetimeAxis && !isLog) { // linear
  6568. if (!tickIntervalOption) {
  6569. axis.tickInterval = normalizeTickInterval(axis.tickInterval, null, getMagnitude(axis.tickInterval), options);
  6570. }
  6571. }
  6572. // get minorTickInterval
  6573. axis.minorTickInterval = options.minorTickInterval === 'auto' && axis.tickInterval ?
  6574. axis.tickInterval / 5 : options.minorTickInterval;
  6575. // find the tick positions
  6576. axis.tickPositions = tickPositions = options.tickPositions ?
  6577. [].concat(options.tickPositions) : // Work on a copy (#1565)
  6578. (tickPositioner && tickPositioner.apply(axis, [axis.min, axis.max]));
  6579. if (!tickPositions) {
  6580. // Too many ticks
  6581. if (!axis.ordinalPositions && (axis.max - axis.min) / axis.tickInterval > mathMax(2 * axis.len, 200)) {
  6582. error(19, true);
  6583. }
  6584. if (isDatetimeAxis) {
  6585. tickPositions = (axis.getNonLinearTimeTicks || getTimeTicks)(
  6586. normalizeTimeTickInterval(axis.tickInterval, options.units),
  6587. axis.min,
  6588. axis.max,
  6589. options.startOfWeek,
  6590. axis.ordinalPositions,
  6591. axis.closestPointRange,
  6592. true
  6593. );
  6594. } else if (isLog) {
  6595. tickPositions = axis.getLogTickPositions(axis.tickInterval, axis.min, axis.max);
  6596. } else {
  6597. tickPositions = axis.getLinearTickPositions(axis.tickInterval, axis.min, axis.max);
  6598. }
  6599. if (keepTwoTicksOnly) {
  6600. tickPositions.splice(1, tickPositions.length - 2);
  6601. }
  6602. axis.tickPositions = tickPositions;
  6603. }
  6604. if (!isLinked) {
  6605. // reset min/max or remove extremes based on start/end on tick
  6606. var roundedMin = tickPositions[0],
  6607. roundedMax = tickPositions[tickPositions.length - 1],
  6608. minPointOffset = axis.minPointOffset || 0,
  6609. singlePad;
  6610. if (options.startOnTick) {
  6611. axis.min = roundedMin;
  6612. } else if (axis.min - minPointOffset > roundedMin) {
  6613. tickPositions.shift();
  6614. }
  6615. if (options.endOnTick) {
  6616. axis.max = roundedMax;
  6617. } else if (axis.max + minPointOffset < roundedMax) {
  6618. tickPositions.pop();
  6619. }
  6620. // When there is only one point, or all points have the same value on this axis, then min
  6621. // and max are equal and tickPositions.length is 1. In this case, add some padding
  6622. // in order to center the point, but leave it with one tick. #1337.
  6623. if (tickPositions.length === 1) {
  6624. singlePad = 0.001; // The lowest possible number to avoid extra padding on columns
  6625. axis.min -= singlePad;
  6626. axis.max += singlePad;
  6627. }
  6628. }
  6629. },
  6630. /**
  6631. * Set the max ticks of either the x and y axis collection
  6632. */
  6633. setMaxTicks: function () {
  6634. var chart = this.chart,
  6635. maxTicks = chart.maxTicks || {},
  6636. tickPositions = this.tickPositions,
  6637. key = this._maxTicksKey = [this.xOrY, this.pos, this.len].join('-');
  6638. if (!this.isLinked && !this.isDatetimeAxis && tickPositions && tickPositions.length > (maxTicks[key] || 0) && this.options.alignTicks !== false) {
  6639. maxTicks[key] = tickPositions.length;
  6640. }
  6641. chart.maxTicks = maxTicks;
  6642. },
  6643. /**
  6644. * When using multiple axes, adjust the number of ticks to match the highest
  6645. * number of ticks in that group
  6646. */
  6647. adjustTickAmount: function () {
  6648. var axis = this,
  6649. chart = axis.chart,
  6650. key = axis._maxTicksKey,
  6651. tickPositions = axis.tickPositions,
  6652. maxTicks = chart.maxTicks;
  6653. if (maxTicks && maxTicks[key] && !axis.isDatetimeAxis && !axis.categories && !axis.isLinked && axis.options.alignTicks !== false) { // only apply to linear scale
  6654. var oldTickAmount = axis.tickAmount,
  6655. calculatedTickAmount = tickPositions.length,
  6656. tickAmount;
  6657. // set the axis-level tickAmount to use below
  6658. axis.tickAmount = tickAmount = maxTicks[key];
  6659. if (calculatedTickAmount < tickAmount) {
  6660. while (tickPositions.length < tickAmount) {
  6661. tickPositions.push(correctFloat(
  6662. tickPositions[tickPositions.length - 1] + axis.tickInterval
  6663. ));
  6664. }
  6665. axis.transA *= (calculatedTickAmount - 1) / (tickAmount - 1);
  6666. axis.max = tickPositions[tickPositions.length - 1];
  6667. }
  6668. if (defined(oldTickAmount) && tickAmount !== oldTickAmount) {
  6669. axis.isDirty = true;
  6670. }
  6671. }
  6672. },
  6673. /**
  6674. * Set the scale based on data min and max, user set min and max or options
  6675. *
  6676. */
  6677. setScale: function () {
  6678. var axis = this,
  6679. stacks = axis.stacks,
  6680. type,
  6681. i,
  6682. isDirtyData,
  6683. isDirtyAxisLength;
  6684. axis.oldMin = axis.min;
  6685. axis.oldMax = axis.max;
  6686. axis.oldAxisLength = axis.len;
  6687. // set the new axisLength
  6688. axis.setAxisSize();
  6689. //axisLength = horiz ? axisWidth : axisHeight;
  6690. isDirtyAxisLength = axis.len !== axis.oldAxisLength;
  6691. // is there new data?
  6692. each(axis.series, function (series) {
  6693. if (series.isDirtyData || series.isDirty ||
  6694. series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well
  6695. isDirtyData = true;
  6696. }
  6697. });
  6698. // do we really need to go through all this?
  6699. if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw ||
  6700. axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax) {
  6701. // reset stacks
  6702. if (!axis.isXAxis) {
  6703. for (type in stacks) {
  6704. delete stacks[type];
  6705. }
  6706. }
  6707. axis.forceRedraw = false;
  6708. // get data extremes if needed
  6709. axis.getSeriesExtremes();
  6710. // get fixed positions based on tickInterval
  6711. axis.setTickPositions();
  6712. // reconciliation old values to decide whether a rescale is necessary later on (#540)
  6713. axis.oldUserMin = axis.userMin;
  6714. axis.oldUserMax = axis.userMax;
  6715. // Mark as dirty if it is not already set to dirty and extremes have changed. #595.
  6716. if (!axis.isDirty) {
  6717. axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax;
  6718. }
  6719. } else if (!axis.isXAxis) {
  6720. if (axis.oldStacks) {
  6721. stacks = axis.stacks = axis.oldStacks;
  6722. }
  6723. // reset stacks
  6724. for (type in stacks) {
  6725. for (i in stacks[type]) {
  6726. stacks[type][i].cum = stacks[type][i].total;
  6727. }
  6728. }
  6729. }
  6730. // Set the maximum tick amount
  6731. axis.setMaxTicks();
  6732. },
  6733. /**
  6734. * Set the extremes and optionally redraw
  6735. * @param {Number} newMin
  6736. * @param {Number} newMax
  6737. * @param {Boolean} redraw
  6738. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  6739. * configuration
  6740. * @param {Object} eventArguments
  6741. *
  6742. */
  6743. setExtremes: function (newMin, newMax, redraw, animation, eventArguments) {
  6744. var axis = this,
  6745. chart = axis.chart;
  6746. redraw = pick(redraw, true); // defaults to true
  6747. // Extend the arguments with min and max
  6748. eventArguments = extend(eventArguments, {
  6749. min: newMin,
  6750. max: newMax
  6751. });
  6752. // Fire the event
  6753. fireEvent(axis, 'setExtremes', eventArguments, function () { // the default event handler
  6754. axis.userMin = newMin;
  6755. axis.userMax = newMax;
  6756. axis.eventArgs = eventArguments;
  6757. // Mark for running afterSetExtremes
  6758. axis.isDirtyExtremes = true;
  6759. // redraw
  6760. if (redraw) {
  6761. chart.redraw(animation);
  6762. }
  6763. });
  6764. },
  6765. /**
  6766. * Overridable method for zooming chart. Pulled out in a separate method to allow overriding
  6767. * in stock charts.
  6768. */
  6769. zoom: function (newMin, newMax) {
  6770. // Prevent pinch zooming out of range. Check for defined is for #1946.
  6771. if (!this.allowZoomOutside) {
  6772. if (defined(this.dataMin) && newMin <= this.dataMin) {
  6773. newMin = UNDEFINED;
  6774. }
  6775. if (defined(this.dataMax) && newMax >= this.dataMax) {
  6776. newMax = UNDEFINED;
  6777. }
  6778. }
  6779. // In full view, displaying the reset zoom button is not required
  6780. this.displayBtn = newMin !== UNDEFINED || newMax !== UNDEFINED;
  6781. // Do it
  6782. this.setExtremes(
  6783. newMin,
  6784. newMax,
  6785. false,
  6786. UNDEFINED,
  6787. { trigger: 'zoom' }
  6788. );
  6789. return true;
  6790. },
  6791. /**
  6792. * Update the axis metrics
  6793. */
  6794. setAxisSize: function () {
  6795. var chart = this.chart,
  6796. options = this.options,
  6797. offsetLeft = options.offsetLeft || 0,
  6798. offsetRight = options.offsetRight || 0,
  6799. horiz = this.horiz,
  6800. width,
  6801. height,
  6802. top,
  6803. left;
  6804. // Expose basic values to use in Series object and navigator
  6805. this.left = left = pick(options.left, chart.plotLeft + offsetLeft);
  6806. this.top = top = pick(options.top, chart.plotTop);
  6807. this.width = width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight);
  6808. this.height = height = pick(options.height, chart.plotHeight);
  6809. this.bottom = chart.chartHeight - height - top;
  6810. this.right = chart.chartWidth - width - left;
  6811. // Direction agnostic properties
  6812. this.len = mathMax(horiz ? width : height, 0); // mathMax fixes #905
  6813. this.pos = horiz ? left : top; // distance from SVG origin
  6814. },
  6815. /**
  6816. * Get the actual axis extremes
  6817. */
  6818. getExtremes: function () {
  6819. var axis = this,
  6820. isLog = axis.isLog;
  6821. return {
  6822. min: isLog ? correctFloat(lin2log(axis.min)) : axis.min,
  6823. max: isLog ? correctFloat(lin2log(axis.max)) : axis.max,
  6824. dataMin: axis.dataMin,
  6825. dataMax: axis.dataMax,
  6826. userMin: axis.userMin,
  6827. userMax: axis.userMax
  6828. };
  6829. },
  6830. /**
  6831. * Get the zero plane either based on zero or on the min or max value.
  6832. * Used in bar and area plots
  6833. */
  6834. getThreshold: function (threshold) {
  6835. var axis = this,
  6836. isLog = axis.isLog;
  6837. var realMin = isLog ? lin2log(axis.min) : axis.min,
  6838. realMax = isLog ? lin2log(axis.max) : axis.max;
  6839. if (realMin > threshold || threshold === null) {
  6840. threshold = realMin;
  6841. } else if (realMax < threshold) {
  6842. threshold = realMax;
  6843. }
  6844. return axis.translate(threshold, 0, 1, 0, 1);
  6845. },
  6846. addPlotBand: function (options) {
  6847. this.addPlotBandOrLine(options, 'plotBands');
  6848. },
  6849. addPlotLine: function (options) {
  6850. this.addPlotBandOrLine(options, 'plotLines');
  6851. },
  6852. /**
  6853. * Add a plot band or plot line after render time
  6854. *
  6855. * @param options {Object} The plotBand or plotLine configuration object
  6856. */
  6857. addPlotBandOrLine: function (options, coll) {
  6858. var obj = new PlotLineOrBand(this, options).render(),
  6859. userOptions = this.userOptions;
  6860. if (obj) { // #2189
  6861. // Add it to the user options for exporting and Axis.update
  6862. if (coll) {
  6863. userOptions[coll] = userOptions[coll] || [];
  6864. userOptions[coll].push(options);
  6865. }
  6866. this.plotLinesAndBands.push(obj);
  6867. }
  6868. return obj;
  6869. },
  6870. /**
  6871. * Compute auto alignment for the axis label based on which side the axis is on
  6872. * and the given rotation for the label
  6873. */
  6874. autoLabelAlign: function (rotation) {
  6875. var ret,
  6876. angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360;
  6877. if (angle > 15 && angle < 165) {
  6878. ret = 'right';
  6879. } else if (angle > 195 && angle < 345) {
  6880. ret = 'left';
  6881. } else {
  6882. ret = 'center';
  6883. }
  6884. return ret;
  6885. },
  6886. /**
  6887. * Render the tick labels to a preliminary position to get their sizes
  6888. */
  6889. getOffset: function () {
  6890. var axis = this,
  6891. chart = axis.chart,
  6892. renderer = chart.renderer,
  6893. options = axis.options,
  6894. tickPositions = axis.tickPositions,
  6895. ticks = axis.ticks,
  6896. horiz = axis.horiz,
  6897. side = axis.side,
  6898. invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side,
  6899. hasData,
  6900. showAxis,
  6901. titleOffset = 0,
  6902. titleOffsetOption,
  6903. titleMargin = 0,
  6904. axisTitleOptions = options.title,
  6905. labelOptions = options.labels,
  6906. labelOffset = 0, // reset
  6907. axisOffset = chart.axisOffset,
  6908. clipOffset = chart.clipOffset,
  6909. directionFactor = [-1, 1, 1, -1][side],
  6910. n,
  6911. i,
  6912. autoStaggerLines = 1,
  6913. maxStaggerLines = pick(labelOptions.maxStaggerLines, 5),
  6914. sortedPositions,
  6915. lastRight,
  6916. overlap,
  6917. pos,
  6918. bBox,
  6919. x,
  6920. w,
  6921. lineNo;
  6922. // For reuse in Axis.render
  6923. axis.hasData = hasData = (axis.hasVisibleSeries || (defined(axis.min) && defined(axis.max) && !!tickPositions));
  6924. axis.showAxis = showAxis = hasData || pick(options.showEmpty, true);
  6925. // Set/reset staggerLines
  6926. axis.staggerLines = axis.horiz && labelOptions.staggerLines;
  6927. // Create the axisGroup and gridGroup elements on first iteration
  6928. if (!axis.axisGroup) {
  6929. axis.gridGroup = renderer.g('grid')
  6930. .attr({ zIndex: options.gridZIndex || 1 })
  6931. .add();
  6932. axis.axisGroup = renderer.g('axis')
  6933. .attr({ zIndex: options.zIndex || 2 })
  6934. .add();
  6935. axis.labelGroup = renderer.g('axis-labels')
  6936. .attr({ zIndex: labelOptions.zIndex || 7 })
  6937. .add();
  6938. }
  6939. if (hasData || axis.isLinked) {
  6940. // Set the explicit or automatic label alignment
  6941. axis.labelAlign = pick(labelOptions.align || axis.autoLabelAlign(labelOptions.rotation));
  6942. each(tickPositions, function (pos) {
  6943. if (!ticks[pos]) {
  6944. ticks[pos] = new Tick(axis, pos);
  6945. } else {
  6946. ticks[pos].addLabel(); // update labels depending on tick interval
  6947. }
  6948. });
  6949. // Handle automatic stagger lines
  6950. if (axis.horiz && !axis.staggerLines && maxStaggerLines && !labelOptions.rotation) {
  6951. sortedPositions = axis.reversed ? [].concat(tickPositions).reverse() : tickPositions;
  6952. while (autoStaggerLines < maxStaggerLines) {
  6953. lastRight = [];
  6954. overlap = false;
  6955. for (i = 0; i < sortedPositions.length; i++) {
  6956. pos = sortedPositions[i];
  6957. bBox = ticks[pos].label && ticks[pos].label.getBBox();
  6958. w = bBox ? bBox.width : 0;
  6959. lineNo = i % autoStaggerLines;
  6960. if (w) {
  6961. x = axis.translate(pos); // don't handle log
  6962. if (lastRight[lineNo] !== UNDEFINED && x < lastRight[lineNo]) {
  6963. overlap = true;
  6964. }
  6965. lastRight[lineNo] = x + w;
  6966. }
  6967. }
  6968. if (overlap) {
  6969. autoStaggerLines++;
  6970. } else {
  6971. break;
  6972. }
  6973. }
  6974. if (autoStaggerLines > 1) {
  6975. axis.staggerLines = autoStaggerLines;
  6976. }
  6977. }
  6978. each(tickPositions, function (pos) {
  6979. // left side must be align: right and right side must have align: left for labels
  6980. if (side === 0 || side === 2 || { 1: 'left', 3: 'right' }[side] === axis.labelAlign) {
  6981. // get the highest offset
  6982. labelOffset = mathMax(
  6983. ticks[pos].getLabelSize(),
  6984. labelOffset
  6985. );
  6986. }
  6987. });
  6988. if (axis.staggerLines) {
  6989. labelOffset *= axis.staggerLines;
  6990. axis.labelOffset = labelOffset;
  6991. }
  6992. } else { // doesn't have data
  6993. for (n in ticks) {
  6994. ticks[n].destroy();
  6995. delete ticks[n];
  6996. }
  6997. }
  6998. if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) {
  6999. if (!axis.axisTitle) {
  7000. axis.axisTitle = renderer.text(
  7001. axisTitleOptions.text,
  7002. 0,
  7003. 0,
  7004. axisTitleOptions.useHTML
  7005. )
  7006. .attr({
  7007. zIndex: 7,
  7008. rotation: axisTitleOptions.rotation || 0,
  7009. align:
  7010. axisTitleOptions.textAlign ||
  7011. { low: 'left', middle: 'center', high: 'right' }[axisTitleOptions.align]
  7012. })
  7013. .css(axisTitleOptions.style)
  7014. .add(axis.axisGroup);
  7015. axis.axisTitle.isNew = true;
  7016. }
  7017. if (showAxis) {
  7018. titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width'];
  7019. titleMargin = pick(axisTitleOptions.margin, horiz ? 5 : 10);
  7020. titleOffsetOption = axisTitleOptions.offset;
  7021. }
  7022. // hide or show the title depending on whether showEmpty is set
  7023. axis.axisTitle[showAxis ? 'show' : 'hide']();
  7024. }
  7025. // handle automatic or user set offset
  7026. axis.offset = directionFactor * pick(options.offset, axisOffset[side]);
  7027. axis.axisTitleMargin =
  7028. pick(titleOffsetOption,
  7029. labelOffset + titleMargin +
  7030. (side !== 2 && labelOffset && directionFactor * options.labels[horiz ? 'y' : 'x'])
  7031. );
  7032. axisOffset[side] = mathMax(
  7033. axisOffset[side],
  7034. axis.axisTitleMargin + titleOffset + directionFactor * axis.offset
  7035. );
  7036. clipOffset[invertedSide] = mathMax(clipOffset[invertedSide], mathFloor(options.lineWidth / 2) * 2);
  7037. },
  7038. /**
  7039. * Get the path for the axis line
  7040. */
  7041. getLinePath: function (lineWidth) {
  7042. var chart = this.chart,
  7043. opposite = this.opposite,
  7044. offset = this.offset,
  7045. horiz = this.horiz,
  7046. lineLeft = this.left + (opposite ? this.width : 0) + offset,
  7047. lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset;
  7048. if (opposite) {
  7049. lineWidth *= -1; // crispify the other way - #1480, #1687
  7050. }
  7051. return chart.renderer.crispLine([
  7052. M,
  7053. horiz ?
  7054. this.left :
  7055. lineLeft,
  7056. horiz ?
  7057. lineTop :
  7058. this.top,
  7059. L,
  7060. horiz ?
  7061. chart.chartWidth - this.right :
  7062. lineLeft,
  7063. horiz ?
  7064. lineTop :
  7065. chart.chartHeight - this.bottom
  7066. ], lineWidth);
  7067. },
  7068. /**
  7069. * Position the title
  7070. */
  7071. getTitlePosition: function () {
  7072. // compute anchor points for each of the title align options
  7073. var horiz = this.horiz,
  7074. axisLeft = this.left,
  7075. axisTop = this.top,
  7076. axisLength = this.len,
  7077. axisTitleOptions = this.options.title,
  7078. margin = horiz ? axisLeft : axisTop,
  7079. opposite = this.opposite,
  7080. offset = this.offset,
  7081. fontSize = pInt(axisTitleOptions.style.fontSize || 12),
  7082. // the position in the length direction of the axis
  7083. alongAxis = {
  7084. low: margin + (horiz ? 0 : axisLength),
  7085. middle: margin + axisLength / 2,
  7086. high: margin + (horiz ? axisLength : 0)
  7087. }[axisTitleOptions.align],
  7088. // the position in the perpendicular direction of the axis
  7089. offAxis = (horiz ? axisTop + this.height : axisLeft) +
  7090. (horiz ? 1 : -1) * // horizontal axis reverses the margin
  7091. (opposite ? -1 : 1) * // so does opposite axes
  7092. this.axisTitleMargin +
  7093. (this.side === 2 ? fontSize : 0);
  7094. return {
  7095. x: horiz ?
  7096. alongAxis :
  7097. offAxis + (opposite ? this.width : 0) + offset +
  7098. (axisTitleOptions.x || 0), // x
  7099. y: horiz ?
  7100. offAxis - (opposite ? this.height : 0) + offset :
  7101. alongAxis + (axisTitleOptions.y || 0) // y
  7102. };
  7103. },
  7104. /**
  7105. * Render the axis
  7106. */
  7107. render: function () {
  7108. var axis = this,
  7109. chart = axis.chart,
  7110. renderer = chart.renderer,
  7111. options = axis.options,
  7112. isLog = axis.isLog,
  7113. isLinked = axis.isLinked,
  7114. tickPositions = axis.tickPositions,
  7115. axisTitle = axis.axisTitle,
  7116. stacks = axis.stacks,
  7117. ticks = axis.ticks,
  7118. minorTicks = axis.minorTicks,
  7119. alternateBands = axis.alternateBands,
  7120. stackLabelOptions = options.stackLabels,
  7121. alternateGridColor = options.alternateGridColor,
  7122. tickmarkOffset = axis.tickmarkOffset,
  7123. lineWidth = options.lineWidth,
  7124. linePath,
  7125. hasRendered = chart.hasRendered,
  7126. slideInTicks = hasRendered && defined(axis.oldMin) && !isNaN(axis.oldMin),
  7127. hasData = axis.hasData,
  7128. showAxis = axis.showAxis,
  7129. from,
  7130. to;
  7131. // Mark all elements inActive before we go over and mark the active ones
  7132. each([ticks, minorTicks, alternateBands], function (coll) {
  7133. var pos;
  7134. for (pos in coll) {
  7135. coll[pos].isActive = false;
  7136. }
  7137. });
  7138. // If the series has data draw the ticks. Else only the line and title
  7139. if (hasData || isLinked) {
  7140. // minor ticks
  7141. if (axis.minorTickInterval && !axis.categories) {
  7142. each(axis.getMinorTickPositions(), function (pos) {
  7143. if (!minorTicks[pos]) {
  7144. minorTicks[pos] = new Tick(axis, pos, 'minor');
  7145. }
  7146. // render new ticks in old position
  7147. if (slideInTicks && minorTicks[pos].isNew) {
  7148. minorTicks[pos].render(null, true);
  7149. }
  7150. minorTicks[pos].render(null, false, 1);
  7151. });
  7152. }
  7153. // Major ticks. Pull out the first item and render it last so that
  7154. // we can get the position of the neighbour label. #808.
  7155. if (tickPositions.length) { // #1300
  7156. each(tickPositions.slice(1).concat([tickPositions[0]]), function (pos, i) {
  7157. // Reorganize the indices
  7158. i = (i === tickPositions.length - 1) ? 0 : i + 1;
  7159. // linked axes need an extra check to find out if
  7160. if (!isLinked || (pos >= axis.min && pos <= axis.max)) {
  7161. if (!ticks[pos]) {
  7162. ticks[pos] = new Tick(axis, pos);
  7163. }
  7164. // render new ticks in old position
  7165. if (slideInTicks && ticks[pos].isNew) {
  7166. ticks[pos].render(i, true);
  7167. }
  7168. ticks[pos].render(i, false, 1);
  7169. }
  7170. });
  7171. // In a categorized axis, the tick marks are displayed between labels. So
  7172. // we need to add a tick mark and grid line at the left edge of the X axis.
  7173. if (tickmarkOffset && axis.min === 0) {
  7174. if (!ticks[-1]) {
  7175. ticks[-1] = new Tick(axis, -1, null, true);
  7176. }
  7177. ticks[-1].render(-1);
  7178. }
  7179. }
  7180. // alternate grid color
  7181. if (alternateGridColor) {
  7182. each(tickPositions, function (pos, i) {
  7183. if (i % 2 === 0 && pos < axis.max) {
  7184. if (!alternateBands[pos]) {
  7185. alternateBands[pos] = new PlotLineOrBand(axis);
  7186. }
  7187. from = pos + tickmarkOffset; // #949
  7188. to = tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] + tickmarkOffset : axis.max;
  7189. alternateBands[pos].options = {
  7190. from: isLog ? lin2log(from) : from,
  7191. to: isLog ? lin2log(to) : to,
  7192. color: alternateGridColor
  7193. };
  7194. alternateBands[pos].render();
  7195. alternateBands[pos].isActive = true;
  7196. }
  7197. });
  7198. }
  7199. // custom plot lines and bands
  7200. if (!axis._addedPlotLB) { // only first time
  7201. each((options.plotLines || []).concat(options.plotBands || []), function (plotLineOptions) {
  7202. axis.addPlotBandOrLine(plotLineOptions);
  7203. });
  7204. axis._addedPlotLB = true;
  7205. }
  7206. } // end if hasData
  7207. // Remove inactive ticks
  7208. each([ticks, minorTicks, alternateBands], function (coll) {
  7209. var pos,
  7210. i,
  7211. forDestruction = [],
  7212. delay = globalAnimation ? globalAnimation.duration || 500 : 0,
  7213. destroyInactiveItems = function () {
  7214. i = forDestruction.length;
  7215. while (i--) {
  7216. // When resizing rapidly, the same items may be destroyed in different timeouts,
  7217. // or the may be reactivated
  7218. if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) {
  7219. coll[forDestruction[i]].destroy();
  7220. delete coll[forDestruction[i]];
  7221. }
  7222. }
  7223. };
  7224. for (pos in coll) {
  7225. if (!coll[pos].isActive) {
  7226. // Render to zero opacity
  7227. coll[pos].render(pos, false, 0);
  7228. coll[pos].isActive = false;
  7229. forDestruction.push(pos);
  7230. }
  7231. }
  7232. // When the objects are finished fading out, destroy them
  7233. if (coll === alternateBands || !chart.hasRendered || !delay) {
  7234. destroyInactiveItems();
  7235. } else if (delay) {
  7236. setTimeout(destroyInactiveItems, delay);
  7237. }
  7238. });
  7239. // Static items. As the axis group is cleared on subsequent calls
  7240. // to render, these items are added outside the group.
  7241. // axis line
  7242. if (lineWidth) {
  7243. linePath = axis.getLinePath(lineWidth);
  7244. if (!axis.axisLine) {
  7245. axis.axisLine = renderer.path(linePath)
  7246. .attr({
  7247. stroke: options.lineColor,
  7248. 'stroke-width': lineWidth,
  7249. zIndex: 7
  7250. })
  7251. .add(axis.axisGroup);
  7252. } else {
  7253. axis.axisLine.animate({ d: linePath });
  7254. }
  7255. // show or hide the line depending on options.showEmpty
  7256. axis.axisLine[showAxis ? 'show' : 'hide']();
  7257. }
  7258. if (axisTitle && showAxis) {
  7259. axisTitle[axisTitle.isNew ? 'attr' : 'animate'](
  7260. axis.getTitlePosition()
  7261. );
  7262. axisTitle.isNew = false;
  7263. }
  7264. // Stacked totals:
  7265. if (stackLabelOptions && stackLabelOptions.enabled) {
  7266. var stackKey, oneStack, stackCategory,
  7267. stackTotalGroup = axis.stackTotalGroup;
  7268. // Create a separate group for the stack total labels
  7269. if (!stackTotalGroup) {
  7270. axis.stackTotalGroup = stackTotalGroup =
  7271. renderer.g('stack-labels')
  7272. .attr({
  7273. visibility: VISIBLE,
  7274. zIndex: 6
  7275. })
  7276. .add();
  7277. }
  7278. // plotLeft/Top will change when y axis gets wider so we need to translate the
  7279. // stackTotalGroup at every render call. See bug #506 and #516
  7280. stackTotalGroup.translate(chart.plotLeft, chart.plotTop);
  7281. // Render each stack total
  7282. for (stackKey in stacks) {
  7283. oneStack = stacks[stackKey];
  7284. for (stackCategory in oneStack) {
  7285. oneStack[stackCategory].render(stackTotalGroup);
  7286. }
  7287. }
  7288. }
  7289. // End stacked totals
  7290. axis.isDirty = false;
  7291. },
  7292. /**
  7293. * Remove a plot band or plot line from the chart by id
  7294. * @param {Object} id
  7295. */
  7296. removePlotBandOrLine: function (id) {
  7297. var plotLinesAndBands = this.plotLinesAndBands,
  7298. options = this.options,
  7299. userOptions = this.userOptions,
  7300. i = plotLinesAndBands.length;
  7301. while (i--) {
  7302. if (plotLinesAndBands[i].id === id) {
  7303. plotLinesAndBands[i].destroy();
  7304. }
  7305. }
  7306. each([options.plotLines || [], userOptions.plotLines || [], options.plotBands || [], userOptions.plotBands || []], function (arr) {
  7307. i = arr.length;
  7308. while (i--) {
  7309. if (arr[i].id === id) {
  7310. erase(arr, arr[i]);
  7311. }
  7312. }
  7313. });
  7314. },
  7315. /**
  7316. * Update the axis title by options
  7317. */
  7318. setTitle: function (newTitleOptions, redraw) {
  7319. this.update({ title: newTitleOptions }, redraw);
  7320. },
  7321. /**
  7322. * Redraw the axis to reflect changes in the data or axis extremes
  7323. */
  7324. redraw: function () {
  7325. var axis = this,
  7326. chart = axis.chart,
  7327. pointer = chart.pointer;
  7328. // hide tooltip and hover states
  7329. if (pointer.reset) {
  7330. pointer.reset(true);
  7331. }
  7332. // render the axis
  7333. axis.render();
  7334. // move plot lines and bands
  7335. each(axis.plotLinesAndBands, function (plotLine) {
  7336. plotLine.render();
  7337. });
  7338. // mark associated series as dirty and ready for redraw
  7339. each(axis.series, function (series) {
  7340. series.isDirty = true;
  7341. });
  7342. },
  7343. /**
  7344. * Build the stacks from top down
  7345. */
  7346. buildStacks: function () {
  7347. var series = this.series,
  7348. i = series.length;
  7349. if (!this.isXAxis) {
  7350. while (i--) {
  7351. series[i].setStackedPoints();
  7352. }
  7353. // Loop up again to compute percent stack
  7354. if (this.usePercentage) {
  7355. for (i = 0; i < series.length; i++) {
  7356. series[i].setPercentStacks();
  7357. }
  7358. }
  7359. }
  7360. },
  7361. /**
  7362. * Set new axis categories and optionally redraw
  7363. * @param {Array} categories
  7364. * @param {Boolean} redraw
  7365. */
  7366. setCategories: function (categories, redraw) {
  7367. this.update({ categories: categories }, redraw);
  7368. },
  7369. /**
  7370. * Destroys an Axis instance.
  7371. */
  7372. destroy: function (keepEvents) {
  7373. var axis = this,
  7374. stacks = axis.stacks,
  7375. stackKey,
  7376. plotLinesAndBands = axis.plotLinesAndBands,
  7377. i;
  7378. // Remove the events
  7379. if (!keepEvents) {
  7380. removeEvent(axis);
  7381. }
  7382. // Destroy each stack total
  7383. for (stackKey in stacks) {
  7384. destroyObjectProperties(stacks[stackKey]);
  7385. stacks[stackKey] = null;
  7386. }
  7387. // Destroy collections
  7388. each([axis.ticks, axis.minorTicks, axis.alternateBands], function (coll) {
  7389. destroyObjectProperties(coll);
  7390. });
  7391. i = plotLinesAndBands.length;
  7392. while (i--) { // #1975
  7393. plotLinesAndBands[i].destroy();
  7394. }
  7395. // Destroy local variables
  7396. each(['stackTotalGroup', 'axisLine', 'axisGroup', 'gridGroup', 'labelGroup', 'axisTitle'], function (prop) {
  7397. if (axis[prop]) {
  7398. axis[prop] = axis[prop].destroy();
  7399. }
  7400. });
  7401. }
  7402. }; // end Axis
  7403. /**
  7404. * The tooltip object
  7405. * @param {Object} chart The chart instance
  7406. * @param {Object} options Tooltip options
  7407. */
  7408. function Tooltip() {
  7409. this.init.apply(this, arguments);
  7410. }
  7411. Tooltip.prototype = {
  7412. init: function (chart, options) {
  7413. var borderWidth = options.borderWidth,
  7414. style = options.style,
  7415. padding = pInt(style.padding);
  7416. // Save the chart and options
  7417. this.chart = chart;
  7418. this.options = options;
  7419. // Keep track of the current series
  7420. //this.currentSeries = UNDEFINED;
  7421. // List of crosshairs
  7422. this.crosshairs = [];
  7423. // Current values of x and y when animating
  7424. this.now = { x: 0, y: 0 };
  7425. // The tooltip is initially hidden
  7426. this.isHidden = true;
  7427. // create the label
  7428. this.label = chart.renderer.label('', 0, 0, options.shape, null, null, options.useHTML, null, 'tooltip')
  7429. .attr({
  7430. padding: padding,
  7431. fill: options.backgroundColor,
  7432. 'stroke-width': borderWidth,
  7433. r: options.borderRadius,
  7434. zIndex: 8
  7435. })
  7436. .css(style)
  7437. .css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117)
  7438. .add()
  7439. .attr({ y: -999 }); // #2301
  7440. // When using canVG the shadow shows up as a gray circle
  7441. // even if the tooltip is hidden.
  7442. if (!useCanVG) {
  7443. this.label.shadow(options.shadow);
  7444. }
  7445. // Public property for getting the shared state.
  7446. this.shared = options.shared;
  7447. },
  7448. /**
  7449. * Destroy the tooltip and its elements.
  7450. */
  7451. destroy: function () {
  7452. each(this.crosshairs, function (crosshair) {
  7453. if (crosshair) {
  7454. crosshair.destroy();
  7455. }
  7456. });
  7457. // Destroy and clear local variables
  7458. if (this.label) {
  7459. this.label = this.label.destroy();
  7460. }
  7461. clearTimeout(this.hideTimer);
  7462. clearTimeout(this.tooltipTimeout);
  7463. },
  7464. /**
  7465. * Provide a soft movement for the tooltip
  7466. *
  7467. * @param {Number} x
  7468. * @param {Number} y
  7469. * @private
  7470. */
  7471. move: function (x, y, anchorX, anchorY) {
  7472. var tooltip = this,
  7473. now = tooltip.now,
  7474. animate = tooltip.options.animation !== false && !tooltip.isHidden;
  7475. // get intermediate values for animation
  7476. extend(now, {
  7477. x: animate ? (2 * now.x + x) / 3 : x,
  7478. y: animate ? (now.y + y) / 2 : y,
  7479. anchorX: animate ? (2 * now.anchorX + anchorX) / 3 : anchorX,
  7480. anchorY: animate ? (now.anchorY + anchorY) / 2 : anchorY
  7481. });
  7482. // move to the intermediate value
  7483. tooltip.label.attr(now);
  7484. // run on next tick of the mouse tracker
  7485. if (animate && (mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1)) {
  7486. // never allow two timeouts
  7487. clearTimeout(this.tooltipTimeout);
  7488. // set the fixed interval ticking for the smooth tooltip
  7489. this.tooltipTimeout = setTimeout(function () {
  7490. // The interval function may still be running during destroy, so check that the chart is really there before calling.
  7491. if (tooltip) {
  7492. tooltip.move(x, y, anchorX, anchorY);
  7493. }
  7494. }, 32);
  7495. }
  7496. },
  7497. /**
  7498. * Hide the tooltip
  7499. */
  7500. hide: function () {
  7501. var tooltip = this,
  7502. hoverPoints;
  7503. clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766)
  7504. if (!this.isHidden) {
  7505. hoverPoints = this.chart.hoverPoints;
  7506. this.hideTimer = setTimeout(function () {
  7507. tooltip.label.fadeOut();
  7508. tooltip.isHidden = true;
  7509. }, pick(this.options.hideDelay, 500));
  7510. // hide previous hoverPoints and set new
  7511. if (hoverPoints) {
  7512. each(hoverPoints, function (point) {
  7513. point.setState();
  7514. });
  7515. }
  7516. this.chart.hoverPoints = null;
  7517. }
  7518. },
  7519. /**
  7520. * Hide the crosshairs
  7521. */
  7522. hideCrosshairs: function () {
  7523. each(this.crosshairs, function (crosshair) {
  7524. if (crosshair) {
  7525. crosshair.hide();
  7526. }
  7527. });
  7528. },
  7529. /**
  7530. * Extendable method to get the anchor position of the tooltip
  7531. * from a point or set of points
  7532. */
  7533. getAnchor: function (points, mouseEvent) {
  7534. var ret,
  7535. chart = this.chart,
  7536. inverted = chart.inverted,
  7537. plotTop = chart.plotTop,
  7538. plotX = 0,
  7539. plotY = 0,
  7540. yAxis;
  7541. points = splat(points);
  7542. // Pie uses a special tooltipPos
  7543. ret = points[0].tooltipPos;
  7544. // When tooltip follows mouse, relate the position to the mouse
  7545. if (this.followPointer && mouseEvent) {
  7546. if (mouseEvent.chartX === UNDEFINED) {
  7547. mouseEvent = chart.pointer.normalize(mouseEvent);
  7548. }
  7549. ret = [
  7550. mouseEvent.chartX - chart.plotLeft,
  7551. mouseEvent.chartY - plotTop
  7552. ];
  7553. }
  7554. // When shared, use the average position
  7555. if (!ret) {
  7556. each(points, function (point) {
  7557. yAxis = point.series.yAxis;
  7558. plotX += point.plotX;
  7559. plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) +
  7560. (!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151
  7561. });
  7562. plotX /= points.length;
  7563. plotY /= points.length;
  7564. ret = [
  7565. inverted ? chart.plotWidth - plotY : plotX,
  7566. this.shared && !inverted && points.length > 1 && mouseEvent ?
  7567. mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424)
  7568. inverted ? chart.plotHeight - plotX : plotY
  7569. ];
  7570. }
  7571. return map(ret, mathRound);
  7572. },
  7573. /**
  7574. * Place the tooltip in a chart without spilling over
  7575. * and not covering the point it self.
  7576. */
  7577. getPosition: function (boxWidth, boxHeight, point) {
  7578. // Set up the variables
  7579. var chart = this.chart,
  7580. plotLeft = chart.plotLeft,
  7581. plotTop = chart.plotTop,
  7582. plotWidth = chart.plotWidth,
  7583. plotHeight = chart.plotHeight,
  7584. distance = pick(this.options.distance, 12),
  7585. pointX = point.plotX,
  7586. pointY = point.plotY,
  7587. x = pointX + plotLeft + (chart.inverted ? distance : -boxWidth - distance),
  7588. y = pointY - boxHeight + plotTop + 15, // 15 means the point is 15 pixels up from the bottom of the tooltip
  7589. alignedRight;
  7590. // It is too far to the left, adjust it
  7591. if (x < 7) {
  7592. x = plotLeft + mathMax(pointX, 0) + distance;
  7593. }
  7594. // Test to see if the tooltip is too far to the right,
  7595. // if it is, move it back to be inside and then up to not cover the point.
  7596. if ((x + boxWidth) > (plotLeft + plotWidth)) {
  7597. x -= (x + boxWidth) - (plotLeft + plotWidth);
  7598. y = pointY - boxHeight + plotTop - distance;
  7599. alignedRight = true;
  7600. }
  7601. // If it is now above the plot area, align it to the top of the plot area
  7602. if (y < plotTop + 5) {
  7603. y = plotTop + 5;
  7604. // If the tooltip is still covering the point, move it below instead
  7605. if (alignedRight && pointY >= y && pointY <= (y + boxHeight)) {
  7606. y = pointY + plotTop + distance; // below
  7607. }
  7608. }
  7609. // Now if the tooltip is below the chart, move it up. It's better to cover the
  7610. // point than to disappear outside the chart. #834.
  7611. if (y + boxHeight > plotTop + plotHeight) {
  7612. y = mathMax(plotTop, plotTop + plotHeight - boxHeight - distance); // below
  7613. }
  7614. return {x: x, y: y};
  7615. },
  7616. /**
  7617. * In case no user defined formatter is given, this will be used. Note that the context
  7618. * here is an object holding point, series, x, y etc.
  7619. */
  7620. defaultFormatter: function (tooltip) {
  7621. var items = this.points || splat(this),
  7622. series = items[0].series,
  7623. s;
  7624. // build the header
  7625. s = [series.tooltipHeaderFormatter(items[0])];
  7626. // build the values
  7627. each(items, function (item) {
  7628. series = item.series;
  7629. s.push((series.tooltipFormatter && series.tooltipFormatter(item)) ||
  7630. item.point.tooltipFormatter(series.tooltipOptions.pointFormat));
  7631. });
  7632. // footer
  7633. s.push(tooltip.options.footerFormat || '');
  7634. return s.join('');
  7635. },
  7636. /**
  7637. * Refresh the tooltip's text and position.
  7638. * @param {Object} point
  7639. */
  7640. refresh: function (point, mouseEvent) {
  7641. var tooltip = this,
  7642. chart = tooltip.chart,
  7643. label = tooltip.label,
  7644. options = tooltip.options,
  7645. x,
  7646. y,
  7647. anchor,
  7648. textConfig = {},
  7649. text,
  7650. pointConfig = [],
  7651. formatter = options.formatter || tooltip.defaultFormatter,
  7652. hoverPoints = chart.hoverPoints,
  7653. borderColor,
  7654. crosshairsOptions = options.crosshairs,
  7655. shared = tooltip.shared,
  7656. currentSeries;
  7657. clearTimeout(this.hideTimer);
  7658. // get the reference point coordinates (pie charts use tooltipPos)
  7659. tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer;
  7660. anchor = tooltip.getAnchor(point, mouseEvent);
  7661. x = anchor[0];
  7662. y = anchor[1];
  7663. // shared tooltip, array is sent over
  7664. if (shared && !(point.series && point.series.noSharedTooltip)) {
  7665. // hide previous hoverPoints and set new
  7666. chart.hoverPoints = point;
  7667. if (hoverPoints) {
  7668. each(hoverPoints, function (point) {
  7669. point.setState();
  7670. });
  7671. }
  7672. each(point, function (item) {
  7673. item.setState(HOVER_STATE);
  7674. pointConfig.push(item.getLabelConfig());
  7675. });
  7676. textConfig = {
  7677. x: point[0].category,
  7678. y: point[0].y
  7679. };
  7680. textConfig.points = pointConfig;
  7681. point = point[0];
  7682. // single point tooltip
  7683. } else {
  7684. textConfig = point.getLabelConfig();
  7685. }
  7686. text = formatter.call(textConfig, tooltip);
  7687. // register the current series
  7688. currentSeries = point.series;
  7689. // update the inner HTML
  7690. if (text === false) {
  7691. this.hide();
  7692. } else {
  7693. // show it
  7694. if (tooltip.isHidden) {
  7695. stop(label);
  7696. label.attr('opacity', 1).show();
  7697. }
  7698. // update text
  7699. label.attr({
  7700. text: text
  7701. });
  7702. // set the stroke color of the box
  7703. borderColor = options.borderColor || point.color || currentSeries.color || '#606060';
  7704. label.attr({
  7705. stroke: borderColor
  7706. });
  7707. tooltip.updatePosition({ plotX: x, plotY: y });
  7708. this.isHidden = false;
  7709. }
  7710. // crosshairs
  7711. if (crosshairsOptions) {
  7712. crosshairsOptions = splat(crosshairsOptions); // [x, y]
  7713. var path,
  7714. i = crosshairsOptions.length,
  7715. attribs,
  7716. axis,
  7717. val,
  7718. series;
  7719. while (i--) {
  7720. series = point.series;
  7721. axis = series[i ? 'yAxis' : 'xAxis'];
  7722. if (crosshairsOptions[i] && axis) {
  7723. val = i ? pick(point.stackY, point.y) : point.x; // #814
  7724. if (axis.isLog) { // #1671
  7725. val = log2lin(val);
  7726. }
  7727. if (i === 1 && series.modifyValue) { // #1205, #2316
  7728. val = series.modifyValue(val);
  7729. }
  7730. path = axis.getPlotLinePath(
  7731. val,
  7732. 1
  7733. );
  7734. if (tooltip.crosshairs[i]) {
  7735. tooltip.crosshairs[i].attr({ d: path, visibility: VISIBLE });
  7736. } else {
  7737. attribs = {
  7738. 'stroke-width': crosshairsOptions[i].width || 1,
  7739. stroke: crosshairsOptions[i].color || '#C0C0C0',
  7740. zIndex: crosshairsOptions[i].zIndex || 2
  7741. };
  7742. if (crosshairsOptions[i].dashStyle) {
  7743. attribs.dashstyle = crosshairsOptions[i].dashStyle;
  7744. }
  7745. tooltip.crosshairs[i] = chart.renderer.path(path)
  7746. .attr(attribs)
  7747. .add();
  7748. }
  7749. }
  7750. }
  7751. }
  7752. fireEvent(chart, 'tooltipRefresh', {
  7753. text: text,
  7754. x: x + chart.plotLeft,
  7755. y: y + chart.plotTop,
  7756. borderColor: borderColor
  7757. });
  7758. },
  7759. /**
  7760. * Find the new position and perform the move
  7761. */
  7762. updatePosition: function (point) {
  7763. var chart = this.chart,
  7764. label = this.label,
  7765. pos = (this.options.positioner || this.getPosition).call(
  7766. this,
  7767. label.width,
  7768. label.height,
  7769. point
  7770. );
  7771. // do the move
  7772. this.move(
  7773. mathRound(pos.x),
  7774. mathRound(pos.y),
  7775. point.plotX + chart.plotLeft,
  7776. point.plotY + chart.plotTop
  7777. );
  7778. }
  7779. };
  7780. /**
  7781. * The mouse tracker object. All methods starting with "on" are primary DOM event handlers.
  7782. * Subsequent methods should be named differently from what they are doing.
  7783. * @param {Object} chart The Chart instance
  7784. * @param {Object} options The root options object
  7785. */
  7786. function Pointer(chart, options) {
  7787. this.init(chart, options);
  7788. }
  7789. Pointer.prototype = {
  7790. /**
  7791. * Initialize Pointer
  7792. */
  7793. init: function (chart, options) {
  7794. var chartOptions = options.chart,
  7795. chartEvents = chartOptions.events,
  7796. zoomType = useCanVG ? '' : chartOptions.zoomType,
  7797. inverted = chart.inverted,
  7798. zoomX,
  7799. zoomY;
  7800. // Store references
  7801. this.options = options;
  7802. this.chart = chart;
  7803. // Zoom status
  7804. this.zoomX = zoomX = /x/.test(zoomType);
  7805. this.zoomY = zoomY = /y/.test(zoomType);
  7806. this.zoomHor = (zoomX && !inverted) || (zoomY && inverted);
  7807. this.zoomVert = (zoomY && !inverted) || (zoomX && inverted);
  7808. // Do we need to handle click on a touch device?
  7809. this.runChartClick = chartEvents && !!chartEvents.click;
  7810. this.pinchDown = [];
  7811. this.lastValidTouch = {};
  7812. if (options.tooltip.enabled) {
  7813. chart.tooltip = new Tooltip(chart, options.tooltip);
  7814. }
  7815. this.setDOMEvents();
  7816. },
  7817. /**
  7818. * Add crossbrowser support for chartX and chartY
  7819. * @param {Object} e The event object in standard browsers
  7820. */
  7821. normalize: function (e, chartPosition) {
  7822. var chartX,
  7823. chartY,
  7824. ePos;
  7825. // common IE normalizing
  7826. e = e || win.event;
  7827. if (!e.target) {
  7828. e.target = e.srcElement;
  7829. }
  7830. // Framework specific normalizing (#1165)
  7831. e = washMouseEvent(e);
  7832. // iOS
  7833. ePos = e.touches ? e.touches.item(0) : e;
  7834. // Get mouse position
  7835. if (!chartPosition) {
  7836. this.chartPosition = chartPosition = offset(this.chart.container);
  7837. }
  7838. // chartX and chartY
  7839. if (ePos.pageX === UNDEFINED) { // IE < 9. #886.
  7840. chartX = mathMax(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is
  7841. // for IE10 quirks mode within framesets
  7842. chartY = e.y;
  7843. } else {
  7844. chartX = ePos.pageX - chartPosition.left;
  7845. chartY = ePos.pageY - chartPosition.top;
  7846. }
  7847. return extend(e, {
  7848. chartX: mathRound(chartX),
  7849. chartY: mathRound(chartY)
  7850. });
  7851. },
  7852. /**
  7853. * Get the click position in terms of axis values.
  7854. *
  7855. * @param {Object} e A pointer event
  7856. */
  7857. getCoordinates: function (e) {
  7858. var coordinates = {
  7859. xAxis: [],
  7860. yAxis: []
  7861. };
  7862. each(this.chart.axes, function (axis) {
  7863. coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({
  7864. axis: axis,
  7865. value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY'])
  7866. });
  7867. });
  7868. return coordinates;
  7869. },
  7870. /**
  7871. * Return the index in the tooltipPoints array, corresponding to pixel position in
  7872. * the plot area.
  7873. */
  7874. getIndex: function (e) {
  7875. var chart = this.chart;
  7876. return chart.inverted ?
  7877. chart.plotHeight + chart.plotTop - e.chartY :
  7878. e.chartX - chart.plotLeft;
  7879. },
  7880. /**
  7881. * With line type charts with a single tracker, get the point closest to the mouse.
  7882. * Run Point.onMouseOver and display tooltip for the point or points.
  7883. */
  7884. runPointActions: function (e) {
  7885. var pointer = this,
  7886. chart = pointer.chart,
  7887. series = chart.series,
  7888. tooltip = chart.tooltip,
  7889. point,
  7890. points,
  7891. hoverPoint = chart.hoverPoint,
  7892. hoverSeries = chart.hoverSeries,
  7893. i,
  7894. j,
  7895. distance = chart.chartWidth,
  7896. index = pointer.getIndex(e),
  7897. anchor;
  7898. // shared tooltip
  7899. if (tooltip && pointer.options.tooltip.shared && !(hoverSeries && hoverSeries.noSharedTooltip)) {
  7900. points = [];
  7901. // loop over all series and find the ones with points closest to the mouse
  7902. i = series.length;
  7903. for (j = 0; j < i; j++) {
  7904. if (series[j].visible &&
  7905. series[j].options.enableMouseTracking !== false &&
  7906. !series[j].noSharedTooltip && series[j].tooltipPoints.length) {
  7907. point = series[j].tooltipPoints[index];
  7908. if (point && point.series) { // not a dummy point, #1544
  7909. point._dist = mathAbs(index - point.clientX);
  7910. distance = mathMin(distance, point._dist);
  7911. points.push(point);
  7912. }
  7913. }
  7914. }
  7915. // remove furthest points
  7916. i = points.length;
  7917. while (i--) {
  7918. if (points[i]._dist > distance) {
  7919. points.splice(i, 1);
  7920. }
  7921. }
  7922. // refresh the tooltip if necessary
  7923. if (points.length && (points[0].clientX !== pointer.hoverX)) {
  7924. tooltip.refresh(points, e);
  7925. pointer.hoverX = points[0].clientX;
  7926. }
  7927. }
  7928. // separate tooltip and general mouse events
  7929. if (hoverSeries && hoverSeries.tracker) { // only use for line-type series with common tracker
  7930. // get the point
  7931. point = hoverSeries.tooltipPoints[index];
  7932. // a new point is hovered, refresh the tooltip
  7933. if (point && point !== hoverPoint) {
  7934. // trigger the events
  7935. point.onMouseOver(e);
  7936. }
  7937. } else if (tooltip && tooltip.followPointer && !tooltip.isHidden) {
  7938. anchor = tooltip.getAnchor([{}], e);
  7939. tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] });
  7940. }
  7941. },
  7942. /**
  7943. * Reset the tracking by hiding the tooltip, the hover series state and the hover point
  7944. *
  7945. * @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible
  7946. */
  7947. reset: function (allowMove) {
  7948. var pointer = this,
  7949. chart = pointer.chart,
  7950. hoverSeries = chart.hoverSeries,
  7951. hoverPoint = chart.hoverPoint,
  7952. tooltip = chart.tooltip,
  7953. tooltipPoints = tooltip && tooltip.shared ? chart.hoverPoints : hoverPoint;
  7954. // Narrow in allowMove
  7955. allowMove = allowMove && tooltip && tooltipPoints;
  7956. // Check if the points have moved outside the plot area, #1003
  7957. if (allowMove && splat(tooltipPoints)[0].plotX === UNDEFINED) {
  7958. allowMove = false;
  7959. }
  7960. // Just move the tooltip, #349
  7961. if (allowMove) {
  7962. tooltip.refresh(tooltipPoints);
  7963. // Full reset
  7964. } else {
  7965. if (hoverPoint) {
  7966. hoverPoint.onMouseOut();
  7967. }
  7968. if (hoverSeries) {
  7969. hoverSeries.onMouseOut();
  7970. }
  7971. if (tooltip) {
  7972. tooltip.hide();
  7973. tooltip.hideCrosshairs();
  7974. }
  7975. pointer.hoverX = null;
  7976. }
  7977. },
  7978. /**
  7979. * Scale series groups to a certain scale and translation
  7980. */
  7981. scaleGroups: function (attribs, clip) {
  7982. var chart = this.chart,
  7983. seriesAttribs;
  7984. // Scale each series
  7985. each(chart.series, function (series) {
  7986. seriesAttribs = attribs || series.getPlotBox(); // #1701
  7987. if (series.xAxis && series.xAxis.zoomEnabled) {
  7988. series.group.attr(seriesAttribs);
  7989. if (series.markerGroup) {
  7990. series.markerGroup.attr(seriesAttribs);
  7991. series.markerGroup.clip(clip ? chart.clipRect : null);
  7992. }
  7993. if (series.dataLabelsGroup) {
  7994. series.dataLabelsGroup.attr(seriesAttribs);
  7995. }
  7996. }
  7997. });
  7998. // Clip
  7999. chart.clipRect.attr(clip || chart.clipBox);
  8000. },
  8001. /**
  8002. * Run translation operations for each direction (horizontal and vertical) independently
  8003. */
  8004. pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) {
  8005. var chart = this.chart,
  8006. xy = horiz ? 'x' : 'y',
  8007. XY = horiz ? 'X' : 'Y',
  8008. sChartXY = 'chart' + XY,
  8009. wh = horiz ? 'width' : 'height',
  8010. plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')],
  8011. selectionWH,
  8012. selectionXY,
  8013. clipXY,
  8014. scale = 1,
  8015. inverted = chart.inverted,
  8016. bounds = chart.bounds[horiz ? 'h' : 'v'],
  8017. singleTouch = pinchDown.length === 1,
  8018. touch0Start = pinchDown[0][sChartXY],
  8019. touch0Now = touches[0][sChartXY],
  8020. touch1Start = !singleTouch && pinchDown[1][sChartXY],
  8021. touch1Now = !singleTouch && touches[1][sChartXY],
  8022. outOfBounds,
  8023. transformScale,
  8024. scaleKey,
  8025. setScale = function () {
  8026. if (!singleTouch && mathAbs(touch0Start - touch1Start) > 20) { // Don't zoom if fingers are too close on this axis
  8027. scale = mathAbs(touch0Now - touch1Now) / mathAbs(touch0Start - touch1Start);
  8028. }
  8029. clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start;
  8030. selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale;
  8031. };
  8032. // Set the scale, first pass
  8033. setScale();
  8034. selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not
  8035. // Out of bounds
  8036. if (selectionXY < bounds.min) {
  8037. selectionXY = bounds.min;
  8038. outOfBounds = true;
  8039. } else if (selectionXY + selectionWH > bounds.max) {
  8040. selectionXY = bounds.max - selectionWH;
  8041. outOfBounds = true;
  8042. }
  8043. // Is the chart dragged off its bounds, determined by dataMin and dataMax?
  8044. if (outOfBounds) {
  8045. // Modify the touchNow position in order to create an elastic drag movement. This indicates
  8046. // to the user that the chart is responsive but can't be dragged further.
  8047. touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]);
  8048. if (!singleTouch) {
  8049. touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]);
  8050. }
  8051. // Set the scale, second pass to adapt to the modified touchNow positions
  8052. setScale();
  8053. } else {
  8054. lastValidTouch[xy] = [touch0Now, touch1Now];
  8055. }
  8056. // Set geometry for clipping, selection and transformation
  8057. if (!inverted) { // TODO: implement clipping for inverted charts
  8058. clip[xy] = clipXY - plotLeftTop;
  8059. clip[wh] = selectionWH;
  8060. }
  8061. scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY;
  8062. transformScale = inverted ? 1 / scale : scale;
  8063. selectionMarker[wh] = selectionWH;
  8064. selectionMarker[xy] = selectionXY;
  8065. transform[scaleKey] = scale;
  8066. transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start));
  8067. },
  8068. /**
  8069. * Handle touch events with two touches
  8070. */
  8071. pinch: function (e) {
  8072. var self = this,
  8073. chart = self.chart,
  8074. pinchDown = self.pinchDown,
  8075. followTouchMove = chart.tooltip && chart.tooltip.options.followTouchMove,
  8076. touches = e.touches,
  8077. touchesLength = touches.length,
  8078. lastValidTouch = self.lastValidTouch,
  8079. zoomHor = self.zoomHor || self.pinchHor,
  8080. zoomVert = self.zoomVert || self.pinchVert,
  8081. hasZoom = zoomHor || zoomVert,
  8082. selectionMarker = self.selectionMarker,
  8083. transform = {},
  8084. fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, PREFIX + 'tracker') &&
  8085. chart.runTrackerClick) || chart.runChartClick),
  8086. clip = {};
  8087. // On touch devices, only proceed to trigger click if a handler is defined
  8088. if ((hasZoom || followTouchMove) && !fireClickEvent) {
  8089. e.preventDefault();
  8090. }
  8091. // Normalize each touch
  8092. map(touches, function (e) {
  8093. return self.normalize(e);
  8094. });
  8095. // Register the touch start position
  8096. if (e.type === 'touchstart') {
  8097. each(touches, function (e, i) {
  8098. pinchDown[i] = { chartX: e.chartX, chartY: e.chartY };
  8099. });
  8100. lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX];
  8101. lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY];
  8102. // Identify the data bounds in pixels
  8103. each(chart.axes, function (axis) {
  8104. if (axis.zoomEnabled) {
  8105. var bounds = chart.bounds[axis.horiz ? 'h' : 'v'],
  8106. minPixelPadding = axis.minPixelPadding,
  8107. min = axis.toPixels(axis.dataMin),
  8108. max = axis.toPixels(axis.dataMax),
  8109. absMin = mathMin(min, max),
  8110. absMax = mathMax(min, max);
  8111. // Store the bounds for use in the touchmove handler
  8112. bounds.min = mathMin(axis.pos, absMin - minPixelPadding);
  8113. bounds.max = mathMax(axis.pos + axis.len, absMax + minPixelPadding);
  8114. }
  8115. });
  8116. // Event type is touchmove, handle panning and pinching
  8117. } else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first
  8118. // Set the marker
  8119. if (!selectionMarker) {
  8120. self.selectionMarker = selectionMarker = extend({
  8121. destroy: noop
  8122. }, chart.plotBox);
  8123. }
  8124. if (zoomHor) {
  8125. self.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
  8126. }
  8127. if (zoomVert) {
  8128. self.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
  8129. }
  8130. self.hasPinched = hasZoom;
  8131. // Scale and translate the groups to provide visual feedback during pinching
  8132. self.scaleGroups(transform, clip);
  8133. // Optionally move the tooltip on touchmove
  8134. if (!hasZoom && followTouchMove && touchesLength === 1) {
  8135. this.runPointActions(self.normalize(e));
  8136. }
  8137. }
  8138. },
  8139. /**
  8140. * Start a drag operation
  8141. */
  8142. dragStart: function (e) {
  8143. var chart = this.chart;
  8144. // Record the start position
  8145. chart.mouseIsDown = e.type;
  8146. chart.cancelClick = false;
  8147. chart.mouseDownX = this.mouseDownX = e.chartX;
  8148. chart.mouseDownY = this.mouseDownY = e.chartY;
  8149. },
  8150. /**
  8151. * Perform a drag operation in response to a mousemove event while the mouse is down
  8152. */
  8153. drag: function (e) {
  8154. var chart = this.chart,
  8155. chartOptions = chart.options.chart,
  8156. chartX = e.chartX,
  8157. chartY = e.chartY,
  8158. zoomHor = this.zoomHor,
  8159. zoomVert = this.zoomVert,
  8160. plotLeft = chart.plotLeft,
  8161. plotTop = chart.plotTop,
  8162. plotWidth = chart.plotWidth,
  8163. plotHeight = chart.plotHeight,
  8164. clickedInside,
  8165. size,
  8166. mouseDownX = this.mouseDownX,
  8167. mouseDownY = this.mouseDownY;
  8168. // If the mouse is outside the plot area, adjust to cooordinates
  8169. // inside to prevent the selection marker from going outside
  8170. if (chartX < plotLeft) {
  8171. chartX = plotLeft;
  8172. } else if (chartX > plotLeft + plotWidth) {
  8173. chartX = plotLeft + plotWidth;
  8174. }
  8175. if (chartY < plotTop) {
  8176. chartY = plotTop;
  8177. } else if (chartY > plotTop + plotHeight) {
  8178. chartY = plotTop + plotHeight;
  8179. }
  8180. // determine if the mouse has moved more than 10px
  8181. this.hasDragged = Math.sqrt(
  8182. Math.pow(mouseDownX - chartX, 2) +
  8183. Math.pow(mouseDownY - chartY, 2)
  8184. );
  8185. if (this.hasDragged > 10) {
  8186. clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop);
  8187. // make a selection
  8188. if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside) {
  8189. if (!this.selectionMarker) {
  8190. this.selectionMarker = chart.renderer.rect(
  8191. plotLeft,
  8192. plotTop,
  8193. zoomHor ? 1 : plotWidth,
  8194. zoomVert ? 1 : plotHeight,
  8195. 0
  8196. )
  8197. .attr({
  8198. fill: chartOptions.selectionMarkerFill || 'rgba(69,114,167,0.25)',
  8199. zIndex: 7
  8200. })
  8201. .add();
  8202. }
  8203. }
  8204. // adjust the width of the selection marker
  8205. if (this.selectionMarker && zoomHor) {
  8206. size = chartX - mouseDownX;
  8207. this.selectionMarker.attr({
  8208. width: mathAbs(size),
  8209. x: (size > 0 ? 0 : size) + mouseDownX
  8210. });
  8211. }
  8212. // adjust the height of the selection marker
  8213. if (this.selectionMarker && zoomVert) {
  8214. size = chartY - mouseDownY;
  8215. this.selectionMarker.attr({
  8216. height: mathAbs(size),
  8217. y: (size > 0 ? 0 : size) + mouseDownY
  8218. });
  8219. }
  8220. // panning
  8221. if (clickedInside && !this.selectionMarker && chartOptions.panning) {
  8222. chart.pan(e, chartOptions.panning);
  8223. }
  8224. }
  8225. },
  8226. /**
  8227. * On mouse up or touch end across the entire document, drop the selection.
  8228. */
  8229. drop: function (e) {
  8230. var chart = this.chart,
  8231. hasPinched = this.hasPinched;
  8232. if (this.selectionMarker) {
  8233. var selectionData = {
  8234. xAxis: [],
  8235. yAxis: [],
  8236. originalEvent: e.originalEvent || e
  8237. },
  8238. selectionBox = this.selectionMarker,
  8239. selectionLeft = selectionBox.x,
  8240. selectionTop = selectionBox.y,
  8241. runZoom;
  8242. // a selection has been made
  8243. if (this.hasDragged || hasPinched) {
  8244. // reconciliation each axis' min and max
  8245. each(chart.axes, function (axis) {
  8246. if (axis.zoomEnabled) {
  8247. var horiz = axis.horiz,
  8248. selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop)),
  8249. selectionMax = axis.toValue((horiz ? selectionLeft + selectionBox.width : selectionTop + selectionBox.height));
  8250. if (!isNaN(selectionMin) && !isNaN(selectionMax)) { // #859
  8251. selectionData[axis.xOrY + 'Axis'].push({
  8252. axis: axis,
  8253. min: mathMin(selectionMin, selectionMax), // for reversed axes,
  8254. max: mathMax(selectionMin, selectionMax)
  8255. });
  8256. runZoom = true;
  8257. }
  8258. }
  8259. });
  8260. if (runZoom) {
  8261. fireEvent(chart, 'selection', selectionData, function (args) {
  8262. chart.zoom(extend(args, hasPinched ? { animation: false } : null));
  8263. });
  8264. }
  8265. }
  8266. this.selectionMarker = this.selectionMarker.destroy();
  8267. // Reset scaling preview
  8268. if (hasPinched) {
  8269. this.scaleGroups();
  8270. }
  8271. }
  8272. // Reset all
  8273. if (chart) { // it may be destroyed on mouse up - #877
  8274. css(chart.container, { cursor: chart._cursor });
  8275. chart.cancelClick = this.hasDragged > 10; // #370
  8276. chart.mouseIsDown = this.hasDragged = this.hasPinched = false;
  8277. this.pinchDown = [];
  8278. }
  8279. },
  8280. onContainerMouseDown: function (e) {
  8281. e = this.normalize(e);
  8282. // issue #295, dragging not always working in Firefox
  8283. if (e.preventDefault) {
  8284. e.preventDefault();
  8285. }
  8286. this.dragStart(e);
  8287. },
  8288. onDocumentMouseUp: function (e) {
  8289. this.drop(e);
  8290. },
  8291. /**
  8292. * Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea.
  8293. * Issue #149 workaround. The mouseleave event does not always fire.
  8294. */
  8295. onDocumentMouseMove: function (e) {
  8296. var chart = this.chart,
  8297. chartPosition = this.chartPosition,
  8298. hoverSeries = chart.hoverSeries;
  8299. e = this.normalize(e, chartPosition);
  8300. // If we're outside, hide the tooltip
  8301. if (chartPosition && hoverSeries && !this.inClass(e.target, 'highcharts-tracker') &&
  8302. !chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
  8303. this.reset();
  8304. }
  8305. },
  8306. /**
  8307. * When mouse leaves the container, hide the tooltip.
  8308. */
  8309. onContainerMouseLeave: function () {
  8310. this.reset();
  8311. this.chartPosition = null; // also reset the chart position, used in #149 fix
  8312. },
  8313. // The mousemove, touchmove and touchstart event handler
  8314. onContainerMouseMove: function (e) {
  8315. var chart = this.chart;
  8316. // normalize
  8317. e = this.normalize(e);
  8318. // #295
  8319. e.returnValue = false;
  8320. if (chart.mouseIsDown === 'mousedown') {
  8321. this.drag(e);
  8322. }
  8323. // Show the tooltip and run mouse over events (#977)
  8324. if ((this.inClass(e.target, 'highcharts-tracker') ||
  8325. chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) {
  8326. this.runPointActions(e);
  8327. }
  8328. },
  8329. /**
  8330. * Utility to detect whether an element has, or has a parent with, a specific
  8331. * class name. Used on detection of tracker objects and on deciding whether
  8332. * hovering the tooltip should cause the active series to mouse out.
  8333. */
  8334. inClass: function (element, className) {
  8335. var elemClassName;
  8336. while (element) {
  8337. elemClassName = attr(element, 'class');
  8338. if (elemClassName) {
  8339. if (elemClassName.indexOf(className) !== -1) {
  8340. return true;
  8341. } else if (elemClassName.indexOf(PREFIX + 'container') !== -1) {
  8342. return false;
  8343. }
  8344. }
  8345. element = element.parentNode;
  8346. }
  8347. },
  8348. onTrackerMouseOut: function (e) {
  8349. var series = this.chart.hoverSeries;
  8350. if (series && !series.options.stickyTracking && !this.inClass(e.toElement || e.relatedTarget, PREFIX + 'tooltip')) {
  8351. series.onMouseOut();
  8352. }
  8353. },
  8354. onContainerClick: function (e) {
  8355. var chart = this.chart,
  8356. hoverPoint = chart.hoverPoint,
  8357. plotLeft = chart.plotLeft,
  8358. plotTop = chart.plotTop,
  8359. inverted = chart.inverted,
  8360. chartPosition,
  8361. plotX,
  8362. plotY;
  8363. e = this.normalize(e);
  8364. e.cancelBubble = true; // IE specific
  8365. if (!chart.cancelClick) {
  8366. // On tracker click, fire the series and point events. #783, #1583
  8367. if (hoverPoint && this.inClass(e.target, PREFIX + 'tracker')) {
  8368. chartPosition = this.chartPosition;
  8369. plotX = hoverPoint.plotX;
  8370. plotY = hoverPoint.plotY;
  8371. // add page position info
  8372. extend(hoverPoint, {
  8373. pageX: chartPosition.left + plotLeft +
  8374. (inverted ? chart.plotWidth - plotY : plotX),
  8375. pageY: chartPosition.top + plotTop +
  8376. (inverted ? chart.plotHeight - plotX : plotY)
  8377. });
  8378. // the series click event
  8379. fireEvent(hoverPoint.series, 'click', extend(e, {
  8380. point: hoverPoint
  8381. }));
  8382. // the point click event
  8383. if (chart.hoverPoint) { // it may be destroyed (#1844)
  8384. hoverPoint.firePointEvent('click', e);
  8385. }
  8386. // When clicking outside a tracker, fire a chart event
  8387. } else {
  8388. extend(e, this.getCoordinates(e));
  8389. // fire a click event in the chart
  8390. if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) {
  8391. fireEvent(chart, 'click', e);
  8392. }
  8393. }
  8394. }
  8395. },
  8396. onContainerTouchStart: function (e) {
  8397. var chart = this.chart;
  8398. if (e.touches.length === 1) {
  8399. e = this.normalize(e);
  8400. if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
  8401. // Prevent the click pseudo event from firing unless it is set in the options
  8402. /*if (!chart.runChartClick) {
  8403. e.preventDefault();
  8404. }*/
  8405. // Run mouse events and display tooltip etc
  8406. this.runPointActions(e);
  8407. this.pinch(e);
  8408. } else {
  8409. // Hide the tooltip on touching outside the plot area (#1203)
  8410. this.reset();
  8411. }
  8412. } else if (e.touches.length === 2) {
  8413. this.pinch(e);
  8414. }
  8415. },
  8416. onContainerTouchMove: function (e) {
  8417. if (e.touches.length === 1 || e.touches.length === 2) {
  8418. this.pinch(e);
  8419. }
  8420. },
  8421. onDocumentTouchEnd: function (e) {
  8422. this.drop(e);
  8423. },
  8424. /**
  8425. * Set the JS DOM events on the container and document. This method should contain
  8426. * a one-to-one assignment between methods and their handlers. Any advanced logic should
  8427. * be moved to the handler reflecting the event's name.
  8428. */
  8429. setDOMEvents: function () {
  8430. var pointer = this,
  8431. container = pointer.chart.container,
  8432. events;
  8433. this._events = events = [
  8434. [container, 'onmousedown', 'onContainerMouseDown'],
  8435. [container, 'onmousemove', 'onContainerMouseMove'],
  8436. [container, 'onclick', 'onContainerClick'],
  8437. [container, 'mouseleave', 'onContainerMouseLeave'],
  8438. [doc, 'mousemove', 'onDocumentMouseMove'],
  8439. [doc, 'mouseup', 'onDocumentMouseUp']
  8440. ];
  8441. if (hasTouch) {
  8442. events.push(
  8443. [container, 'ontouchstart', 'onContainerTouchStart'],
  8444. [container, 'ontouchmove', 'onContainerTouchMove'],
  8445. [doc, 'touchend', 'onDocumentTouchEnd']
  8446. );
  8447. }
  8448. each(events, function (eventConfig) {
  8449. // First, create the callback function that in turn calls the method on Pointer
  8450. pointer['_' + eventConfig[2]] = function (e) {
  8451. pointer[eventConfig[2]](e);
  8452. };
  8453. // Now attach the function, either as a direct property or through addEvent
  8454. if (eventConfig[1].indexOf('on') === 0) {
  8455. eventConfig[0][eventConfig[1]] = pointer['_' + eventConfig[2]];
  8456. } else {
  8457. addEvent(eventConfig[0], eventConfig[1], pointer['_' + eventConfig[2]]);
  8458. }
  8459. });
  8460. },
  8461. /**
  8462. * Destroys the Pointer object and disconnects DOM events.
  8463. */
  8464. destroy: function () {
  8465. var pointer = this;
  8466. // Release all DOM events
  8467. each(pointer._events, function (eventConfig) {
  8468. if (eventConfig[1].indexOf('on') === 0) {
  8469. eventConfig[0][eventConfig[1]] = null; // delete breaks oldIE
  8470. } else {
  8471. removeEvent(eventConfig[0], eventConfig[1], pointer['_' + eventConfig[2]]);
  8472. }
  8473. });
  8474. delete pointer._events;
  8475. // memory and CPU leak
  8476. clearInterval(pointer.tooltipTimeout);
  8477. }
  8478. };
  8479. /**
  8480. * The overview of the chart's series
  8481. */
  8482. function Legend(chart, options) {
  8483. this.init(chart, options);
  8484. }
  8485. Legend.prototype = {
  8486. /**
  8487. * Initialize the legend
  8488. */
  8489. init: function (chart, options) {
  8490. var legend = this,
  8491. itemStyle = options.itemStyle,
  8492. padding = pick(options.padding, 8),
  8493. itemMarginTop = options.itemMarginTop || 0;
  8494. this.options = options;
  8495. if (!options.enabled) {
  8496. return;
  8497. }
  8498. legend.baseline = pInt(itemStyle.fontSize) + 3 + itemMarginTop; // used in Series prototype
  8499. legend.itemStyle = itemStyle;
  8500. legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle);
  8501. legend.itemMarginTop = itemMarginTop;
  8502. legend.padding = padding;
  8503. legend.initialItemX = padding;
  8504. legend.initialItemY = padding - 5; // 5 is the number of pixels above the text
  8505. legend.maxItemWidth = 0;
  8506. legend.chart = chart;
  8507. legend.itemHeight = 0;
  8508. legend.lastLineHeight = 0;
  8509. // Render it
  8510. legend.render();
  8511. // move checkboxes
  8512. addEvent(legend.chart, 'endResize', function () {
  8513. legend.positionCheckboxes();
  8514. });
  8515. },
  8516. /**
  8517. * Set the colors for the legend item
  8518. * @param {Object} item A Series or Point instance
  8519. * @param {Object} visible Dimmed or colored
  8520. */
  8521. colorizeItem: function (item, visible) {
  8522. var legend = this,
  8523. options = legend.options,
  8524. legendItem = item.legendItem,
  8525. legendLine = item.legendLine,
  8526. legendSymbol = item.legendSymbol,
  8527. hiddenColor = legend.itemHiddenStyle.color,
  8528. textColor = visible ? options.itemStyle.color : hiddenColor,
  8529. symbolColor = visible ? item.color : hiddenColor,
  8530. markerOptions = item.options && item.options.marker,
  8531. symbolAttr = {
  8532. stroke: symbolColor,
  8533. fill: symbolColor
  8534. },
  8535. key,
  8536. val;
  8537. if (legendItem) {
  8538. legendItem.css({ fill: textColor, color: textColor }); // color for #1553, oldIE
  8539. }
  8540. if (legendLine) {
  8541. legendLine.attr({ stroke: symbolColor });
  8542. }
  8543. if (legendSymbol) {
  8544. // Apply marker options
  8545. if (markerOptions && legendSymbol.isMarker) { // #585
  8546. markerOptions = item.convertAttribs(markerOptions);
  8547. for (key in markerOptions) {
  8548. val = markerOptions[key];
  8549. if (val !== UNDEFINED) {
  8550. symbolAttr[key] = val;
  8551. }
  8552. }
  8553. }
  8554. legendSymbol.attr(symbolAttr);
  8555. }
  8556. },
  8557. /**
  8558. * Position the legend item
  8559. * @param {Object} item A Series or Point instance
  8560. */
  8561. positionItem: function (item) {
  8562. var legend = this,
  8563. options = legend.options,
  8564. symbolPadding = options.symbolPadding,
  8565. ltr = !options.rtl,
  8566. legendItemPos = item._legendItemPos,
  8567. itemX = legendItemPos[0],
  8568. itemY = legendItemPos[1],
  8569. checkbox = item.checkbox;
  8570. if (item.legendGroup) {
  8571. item.legendGroup.translate(
  8572. ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4,
  8573. itemY
  8574. );
  8575. }
  8576. if (checkbox) {
  8577. checkbox.x = itemX;
  8578. checkbox.y = itemY;
  8579. }
  8580. },
  8581. /**
  8582. * Destroy a single legend item
  8583. * @param {Object} item The series or point
  8584. */
  8585. destroyItem: function (item) {
  8586. var checkbox = item.checkbox;
  8587. // destroy SVG elements
  8588. each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) {
  8589. if (item[key]) {
  8590. item[key] = item[key].destroy();
  8591. }
  8592. });
  8593. if (checkbox) {
  8594. discardElement(item.checkbox);
  8595. }
  8596. },
  8597. /**
  8598. * Destroys the legend.
  8599. */
  8600. destroy: function () {
  8601. var legend = this,
  8602. legendGroup = legend.group,
  8603. box = legend.box;
  8604. if (box) {
  8605. legend.box = box.destroy();
  8606. }
  8607. if (legendGroup) {
  8608. legend.group = legendGroup.destroy();
  8609. }
  8610. },
  8611. /**
  8612. * Position the checkboxes after the width is determined
  8613. */
  8614. positionCheckboxes: function (scrollOffset) {
  8615. var alignAttr = this.group.alignAttr,
  8616. translateY,
  8617. clipHeight = this.clipHeight || this.legendHeight;
  8618. if (alignAttr) {
  8619. translateY = alignAttr.translateY;
  8620. each(this.allItems, function (item) {
  8621. var checkbox = item.checkbox,
  8622. top;
  8623. if (checkbox) {
  8624. top = (translateY + checkbox.y + (scrollOffset || 0) + 3);
  8625. css(checkbox, {
  8626. left: (alignAttr.translateX + item.legendItemWidth + checkbox.x - 20) + PX,
  8627. top: top + PX,
  8628. display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE
  8629. });
  8630. }
  8631. });
  8632. }
  8633. },
  8634. /**
  8635. * Render the legend title on top of the legend
  8636. */
  8637. renderTitle: function () {
  8638. var options = this.options,
  8639. padding = this.padding,
  8640. titleOptions = options.title,
  8641. titleHeight = 0,
  8642. bBox;
  8643. if (titleOptions.text) {
  8644. if (!this.title) {
  8645. this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title')
  8646. .attr({ zIndex: 1 })
  8647. .css(titleOptions.style)
  8648. .add(this.group);
  8649. }
  8650. bBox = this.title.getBBox();
  8651. titleHeight = bBox.height;
  8652. this.offsetWidth = bBox.width; // #1717
  8653. this.contentGroup.attr({ translateY: titleHeight });
  8654. }
  8655. this.titleHeight = titleHeight;
  8656. },
  8657. /**
  8658. * Render a single specific legend item
  8659. * @param {Object} item A series or point
  8660. */
  8661. renderItem: function (item) {
  8662. var legend = this,
  8663. chart = legend.chart,
  8664. renderer = chart.renderer,
  8665. options = legend.options,
  8666. horizontal = options.layout === 'horizontal',
  8667. symbolWidth = options.symbolWidth,
  8668. symbolPadding = options.symbolPadding,
  8669. itemStyle = legend.itemStyle,
  8670. itemHiddenStyle = legend.itemHiddenStyle,
  8671. padding = legend.padding,
  8672. itemDistance = horizontal ? pick(options.itemDistance, 8) : 0,
  8673. ltr = !options.rtl,
  8674. itemHeight,
  8675. widthOption = options.width,
  8676. itemMarginBottom = options.itemMarginBottom || 0,
  8677. itemMarginTop = legend.itemMarginTop,
  8678. initialItemX = legend.initialItemX,
  8679. bBox,
  8680. itemWidth,
  8681. li = item.legendItem,
  8682. series = item.series || item,
  8683. itemOptions = series.options,
  8684. showCheckbox = itemOptions.showCheckbox,
  8685. useHTML = options.useHTML;
  8686. if (!li) { // generate it once, later move it
  8687. // Generate the group box
  8688. // A group to hold the symbol and text. Text is to be appended in Legend class.
  8689. item.legendGroup = renderer.g('legend-item')
  8690. .attr({ zIndex: 1 })
  8691. .add(legend.scrollGroup);
  8692. // Draw the legend symbol inside the group box
  8693. series.drawLegendSymbol(legend, item);
  8694. // Generate the list item text and add it to the group
  8695. item.legendItem = li = renderer.text(
  8696. options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item),
  8697. ltr ? symbolWidth + symbolPadding : -symbolPadding,
  8698. legend.baseline,
  8699. useHTML
  8700. )
  8701. .css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021)
  8702. .attr({
  8703. align: ltr ? 'left' : 'right',
  8704. zIndex: 2
  8705. })
  8706. .add(item.legendGroup);
  8707. // Set the events on the item group, or in case of useHTML, the item itself (#1249)
  8708. (useHTML ? li : item.legendGroup).on('mouseover', function () {
  8709. item.setState(HOVER_STATE);
  8710. li.css(legend.options.itemHoverStyle);
  8711. })
  8712. .on('mouseout', function () {
  8713. li.css(item.visible ? itemStyle : itemHiddenStyle);
  8714. item.setState();
  8715. })
  8716. .on('click', function (event) {
  8717. var strLegendItemClick = 'legendItemClick',
  8718. fnLegendItemClick = function () {
  8719. item.setVisible();
  8720. };
  8721. // Pass over the click/touch event. #4.
  8722. event = {
  8723. browserEvent: event
  8724. };
  8725. // click the name or symbol
  8726. if (item.firePointEvent) { // point
  8727. item.firePointEvent(strLegendItemClick, event, fnLegendItemClick);
  8728. } else {
  8729. fireEvent(item, strLegendItemClick, event, fnLegendItemClick);
  8730. }
  8731. });
  8732. // Colorize the items
  8733. legend.colorizeItem(item, item.visible);
  8734. // add the HTML checkbox on top
  8735. if (itemOptions && showCheckbox) {
  8736. item.checkbox = createElement('input', {
  8737. type: 'checkbox',
  8738. checked: item.selected,
  8739. defaultChecked: item.selected // required by IE7
  8740. }, options.itemCheckboxStyle, chart.container);
  8741. addEvent(item.checkbox, 'click', function (event) {
  8742. var target = event.target;
  8743. fireEvent(item, 'checkboxClick', {
  8744. checked: target.checked
  8745. },
  8746. function () {
  8747. item.select();
  8748. }
  8749. );
  8750. });
  8751. }
  8752. }
  8753. // calculate the positions for the next line
  8754. bBox = li.getBBox();
  8755. itemWidth = item.legendItemWidth =
  8756. options.itemWidth || symbolWidth + symbolPadding + bBox.width + itemDistance +
  8757. (showCheckbox ? 20 : 0);
  8758. legend.itemHeight = itemHeight = bBox.height;
  8759. // if the item exceeds the width, start a new line
  8760. if (horizontal && legend.itemX - initialItemX + itemWidth >
  8761. (widthOption || (chart.chartWidth - 2 * padding - initialItemX))) {
  8762. legend.itemX = initialItemX;
  8763. legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom;
  8764. legend.lastLineHeight = 0; // reset for next line
  8765. }
  8766. // If the item exceeds the height, start a new column
  8767. /*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) {
  8768. legend.itemY = legend.initialItemY;
  8769. legend.itemX += legend.maxItemWidth;
  8770. legend.maxItemWidth = 0;
  8771. }*/
  8772. // Set the edge positions
  8773. legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth);
  8774. legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom;
  8775. legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915
  8776. // cache the position of the newly generated or reordered items
  8777. item._legendItemPos = [legend.itemX, legend.itemY];
  8778. // advance
  8779. if (horizontal) {
  8780. legend.itemX += itemWidth;
  8781. } else {
  8782. legend.itemY += itemMarginTop + itemHeight + itemMarginBottom;
  8783. legend.lastLineHeight = itemHeight;
  8784. }
  8785. // the width of the widest item
  8786. legend.offsetWidth = widthOption || mathMax(
  8787. (horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding,
  8788. legend.offsetWidth
  8789. );
  8790. },
  8791. /**
  8792. * Render the legend. This method can be called both before and after
  8793. * chart.render. If called after, it will only rearrange items instead
  8794. * of creating new ones.
  8795. */
  8796. render: function () {
  8797. var legend = this,
  8798. chart = legend.chart,
  8799. renderer = chart.renderer,
  8800. legendGroup = legend.group,
  8801. allItems,
  8802. display,
  8803. legendWidth,
  8804. legendHeight,
  8805. box = legend.box,
  8806. options = legend.options,
  8807. padding = legend.padding,
  8808. legendBorderWidth = options.borderWidth,
  8809. legendBackgroundColor = options.backgroundColor;
  8810. legend.itemX = legend.initialItemX;
  8811. legend.itemY = legend.initialItemY;
  8812. legend.offsetWidth = 0;
  8813. legend.lastItemY = 0;
  8814. if (!legendGroup) {
  8815. legend.group = legendGroup = renderer.g('legend')
  8816. .attr({ zIndex: 7 })
  8817. .add();
  8818. legend.contentGroup = renderer.g()
  8819. .attr({ zIndex: 1 }) // above background
  8820. .add(legendGroup);
  8821. legend.scrollGroup = renderer.g()
  8822. .add(legend.contentGroup);
  8823. }
  8824. legend.renderTitle();
  8825. // add each series or point
  8826. allItems = [];
  8827. each(chart.series, function (serie) {
  8828. var seriesOptions = serie.options;
  8829. if (!seriesOptions.showInLegend || defined(seriesOptions.linkedTo)) {
  8830. return;
  8831. }
  8832. // use points or series for the legend item depending on legendType
  8833. allItems = allItems.concat(
  8834. serie.legendItems ||
  8835. (seriesOptions.legendType === 'point' ?
  8836. serie.data :
  8837. serie)
  8838. );
  8839. });
  8840. // sort by legendIndex
  8841. stableSort(allItems, function (a, b) {
  8842. return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0);
  8843. });
  8844. // reversed legend
  8845. if (options.reversed) {
  8846. allItems.reverse();
  8847. }
  8848. legend.allItems = allItems;
  8849. legend.display = display = !!allItems.length;
  8850. // render the items
  8851. each(allItems, function (item) {
  8852. legend.renderItem(item);
  8853. });
  8854. // Draw the border
  8855. legendWidth = options.width || legend.offsetWidth;
  8856. legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight;
  8857. legendHeight = legend.handleOverflow(legendHeight);
  8858. if (legendBorderWidth || legendBackgroundColor) {
  8859. legendWidth += padding;
  8860. legendHeight += padding;
  8861. if (!box) {
  8862. legend.box = box = renderer.rect(
  8863. 0,
  8864. 0,
  8865. legendWidth,
  8866. legendHeight,
  8867. options.borderRadius,
  8868. legendBorderWidth || 0
  8869. ).attr({
  8870. stroke: options.borderColor,
  8871. 'stroke-width': legendBorderWidth || 0,
  8872. fill: legendBackgroundColor || NONE
  8873. })
  8874. .add(legendGroup)
  8875. .shadow(options.shadow);
  8876. box.isNew = true;
  8877. } else if (legendWidth > 0 && legendHeight > 0) {
  8878. box[box.isNew ? 'attr' : 'animate'](
  8879. box.crisp(null, null, null, legendWidth, legendHeight)
  8880. );
  8881. box.isNew = false;
  8882. }
  8883. // hide the border if no items
  8884. box[display ? 'show' : 'hide']();
  8885. }
  8886. legend.legendWidth = legendWidth;
  8887. legend.legendHeight = legendHeight;
  8888. // Now that the legend width and height are established, put the items in the
  8889. // final position
  8890. each(allItems, function (item) {
  8891. legend.positionItem(item);
  8892. });
  8893. // 1.x compatibility: positioning based on style
  8894. /*var props = ['left', 'right', 'top', 'bottom'],
  8895. prop,
  8896. i = 4;
  8897. while (i--) {
  8898. prop = props[i];
  8899. if (options.style[prop] && options.style[prop] !== 'auto') {
  8900. options[i < 2 ? 'align' : 'verticalAlign'] = prop;
  8901. options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1);
  8902. }
  8903. }*/
  8904. if (display) {
  8905. legendGroup.align(extend({
  8906. width: legendWidth,
  8907. height: legendHeight
  8908. }, options), true, 'spacingBox');
  8909. }
  8910. if (!chart.isResizing) {
  8911. this.positionCheckboxes();
  8912. }
  8913. },
  8914. /**
  8915. * Set up the overflow handling by adding navigation with up and down arrows below the
  8916. * legend.
  8917. */
  8918. handleOverflow: function (legendHeight) {
  8919. var legend = this,
  8920. chart = this.chart,
  8921. renderer = chart.renderer,
  8922. pageCount,
  8923. options = this.options,
  8924. optionsY = options.y,
  8925. alignTop = options.verticalAlign === 'top',
  8926. spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding,
  8927. maxHeight = options.maxHeight,
  8928. clipHeight,
  8929. clipRect = this.clipRect,
  8930. navOptions = options.navigation,
  8931. animation = pick(navOptions.animation, true),
  8932. arrowSize = navOptions.arrowSize || 12,
  8933. nav = this.nav;
  8934. // Adjust the height
  8935. if (options.layout === 'horizontal') {
  8936. spaceHeight /= 2;
  8937. }
  8938. if (maxHeight) {
  8939. spaceHeight = mathMin(spaceHeight, maxHeight);
  8940. }
  8941. // Reset the legend height and adjust the clipping rectangle
  8942. if (legendHeight > spaceHeight && !options.useHTML) {
  8943. this.clipHeight = clipHeight = spaceHeight - 20 - this.titleHeight;
  8944. this.pageCount = pageCount = mathCeil(legendHeight / clipHeight);
  8945. this.currentPage = pick(this.currentPage, 1);
  8946. this.fullHeight = legendHeight;
  8947. // Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787)
  8948. if (!clipRect) {
  8949. clipRect = legend.clipRect = renderer.clipRect(0, 0, 9999, 0);
  8950. legend.contentGroup.clip(clipRect);
  8951. }
  8952. clipRect.attr({
  8953. height: clipHeight
  8954. });
  8955. // Add navigation elements
  8956. if (!nav) {
  8957. this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group);
  8958. this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize)
  8959. .on('click', function () {
  8960. legend.scroll(-1, animation);
  8961. })
  8962. .add(nav);
  8963. this.pager = renderer.text('', 15, 10)
  8964. .css(navOptions.style)
  8965. .add(nav);
  8966. this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize)
  8967. .on('click', function () {
  8968. legend.scroll(1, animation);
  8969. })
  8970. .add(nav);
  8971. }
  8972. // Set initial position
  8973. legend.scroll(0);
  8974. legendHeight = spaceHeight;
  8975. } else if (nav) {
  8976. clipRect.attr({
  8977. height: chart.chartHeight
  8978. });
  8979. nav.hide();
  8980. this.scrollGroup.attr({
  8981. translateY: 1
  8982. });
  8983. this.clipHeight = 0; // #1379
  8984. }
  8985. return legendHeight;
  8986. },
  8987. /**
  8988. * Scroll the legend by a number of pages
  8989. * @param {Object} scrollBy
  8990. * @param {Object} animation
  8991. */
  8992. scroll: function (scrollBy, animation) {
  8993. var pageCount = this.pageCount,
  8994. currentPage = this.currentPage + scrollBy,
  8995. clipHeight = this.clipHeight,
  8996. navOptions = this.options.navigation,
  8997. activeColor = navOptions.activeColor,
  8998. inactiveColor = navOptions.inactiveColor,
  8999. pager = this.pager,
  9000. padding = this.padding,
  9001. scrollOffset;
  9002. // When resizing while looking at the last page
  9003. if (currentPage > pageCount) {
  9004. currentPage = pageCount;
  9005. }
  9006. if (currentPage > 0) {
  9007. if (animation !== UNDEFINED) {
  9008. setAnimation(animation, this.chart);
  9009. }
  9010. this.nav.attr({
  9011. translateX: padding,
  9012. translateY: clipHeight + 7 + this.titleHeight,
  9013. visibility: VISIBLE
  9014. });
  9015. this.up.attr({
  9016. fill: currentPage === 1 ? inactiveColor : activeColor
  9017. })
  9018. .css({
  9019. cursor: currentPage === 1 ? 'default' : 'pointer'
  9020. });
  9021. pager.attr({
  9022. text: currentPage + '/' + this.pageCount
  9023. });
  9024. this.down.attr({
  9025. x: 18 + this.pager.getBBox().width, // adjust to text width
  9026. fill: currentPage === pageCount ? inactiveColor : activeColor
  9027. })
  9028. .css({
  9029. cursor: currentPage === pageCount ? 'default' : 'pointer'
  9030. });
  9031. scrollOffset = -mathMin(clipHeight * (currentPage - 1), this.fullHeight - clipHeight + padding) + 1;
  9032. this.scrollGroup.animate({
  9033. translateY: scrollOffset
  9034. });
  9035. pager.attr({
  9036. text: currentPage + '/' + pageCount
  9037. });
  9038. this.currentPage = currentPage;
  9039. this.positionCheckboxes(scrollOffset);
  9040. }
  9041. }
  9042. };
  9043. // Workaround for #2030, horizontal legend items not displaying in IE11 Preview.
  9044. // TODO: When IE11 is released, check again for this bug, and remove the fix
  9045. // or make a better one.
  9046. if (/Trident.*?11\.0/.test(userAgent)) {
  9047. wrap(Legend.prototype, 'positionItem', function (proceed, item) {
  9048. var legend = this;
  9049. setTimeout(function () {
  9050. proceed.call(legend, item);
  9051. });
  9052. });
  9053. }
  9054. /**
  9055. * The chart class
  9056. * @param {Object} options
  9057. * @param {Function} callback Function to run when the chart has loaded
  9058. */
  9059. function Chart() {
  9060. this.init.apply(this, arguments);
  9061. }
  9062. Chart.prototype = {
  9063. /**
  9064. * Initialize the chart
  9065. */
  9066. init: function (userOptions, callback) {
  9067. // Handle regular options
  9068. var options,
  9069. seriesOptions = userOptions.series; // skip merging data points to increase performance
  9070. userOptions.series = null;
  9071. options = merge(defaultOptions, userOptions); // do the merge
  9072. options.series = userOptions.series = seriesOptions; // set back the series data
  9073. var optionsChart = options.chart;
  9074. // Create margin & spacing array
  9075. this.margin = this.splashArray('margin', optionsChart);
  9076. this.spacing = this.splashArray('spacing', optionsChart);
  9077. var chartEvents = optionsChart.events;
  9078. //this.runChartClick = chartEvents && !!chartEvents.click;
  9079. this.bounds = { h: {}, v: {} }; // Pixel data bounds for touch zoom
  9080. this.callback = callback;
  9081. this.isResizing = 0;
  9082. this.options = options;
  9083. //chartTitleOptions = UNDEFINED;
  9084. //chartSubtitleOptions = UNDEFINED;
  9085. this.axes = [];
  9086. this.series = [];
  9087. this.hasCartesianSeries = optionsChart.showAxes;
  9088. //this.axisOffset = UNDEFINED;
  9089. //this.maxTicks = UNDEFINED; // handle the greatest amount of ticks on grouped axes
  9090. //this.inverted = UNDEFINED;
  9091. //this.loadingShown = UNDEFINED;
  9092. //this.container = UNDEFINED;
  9093. //this.chartWidth = UNDEFINED;
  9094. //this.chartHeight = UNDEFINED;
  9095. //this.marginRight = UNDEFINED;
  9096. //this.marginBottom = UNDEFINED;
  9097. //this.containerWidth = UNDEFINED;
  9098. //this.containerHeight = UNDEFINED;
  9099. //this.oldChartWidth = UNDEFINED;
  9100. //this.oldChartHeight = UNDEFINED;
  9101. //this.renderTo = UNDEFINED;
  9102. //this.renderToClone = UNDEFINED;
  9103. //this.spacingBox = UNDEFINED
  9104. //this.legend = UNDEFINED;
  9105. // Elements
  9106. //this.chartBackground = UNDEFINED;
  9107. //this.plotBackground = UNDEFINED;
  9108. //this.plotBGImage = UNDEFINED;
  9109. //this.plotBorder = UNDEFINED;
  9110. //this.loadingDiv = UNDEFINED;
  9111. //this.loadingSpan = UNDEFINED;
  9112. var chart = this,
  9113. eventType;
  9114. // Add the chart to the global lookup
  9115. chart.index = charts.length;
  9116. charts.push(chart);
  9117. // Set up auto resize
  9118. if (optionsChart.reflow !== false) {
  9119. addEvent(chart, 'load', function () {
  9120. chart.initReflow();
  9121. });
  9122. }
  9123. // Chart event handlers
  9124. if (chartEvents) {
  9125. for (eventType in chartEvents) {
  9126. addEvent(chart, eventType, chartEvents[eventType]);
  9127. }
  9128. }
  9129. chart.xAxis = [];
  9130. chart.yAxis = [];
  9131. // Expose methods and variables
  9132. chart.animation = useCanVG ? false : pick(optionsChart.animation, true);
  9133. chart.pointCount = 0;
  9134. chart.counters = new ChartCounters();
  9135. chart.firstRender();
  9136. },
  9137. /**
  9138. * Initialize an individual series, called internally before render time
  9139. */
  9140. initSeries: function (options) {
  9141. var chart = this,
  9142. optionsChart = chart.options.chart,
  9143. type = options.type || optionsChart.type || optionsChart.defaultSeriesType,
  9144. series,
  9145. constr = seriesTypes[type];
  9146. // No such series type
  9147. if (!constr) {
  9148. error(17, true);
  9149. }
  9150. series = new constr();
  9151. series.init(this, options);
  9152. return series;
  9153. },
  9154. /**
  9155. * Add a series dynamically after time
  9156. *
  9157. * @param {Object} options The config options
  9158. * @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true.
  9159. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  9160. * configuration
  9161. *
  9162. * @return {Object} series The newly created series object
  9163. */
  9164. addSeries: function (options, redraw, animation) {
  9165. var series,
  9166. chart = this;
  9167. if (options) {
  9168. redraw = pick(redraw, true); // defaults to true
  9169. fireEvent(chart, 'addSeries', { options: options }, function () {
  9170. series = chart.initSeries(options);
  9171. chart.isDirtyLegend = true; // the series array is out of sync with the display
  9172. chart.linkSeries();
  9173. if (redraw) {
  9174. chart.redraw(animation);
  9175. }
  9176. });
  9177. }
  9178. return series;
  9179. },
  9180. /**
  9181. * Add an axis to the chart
  9182. * @param {Object} options The axis option
  9183. * @param {Boolean} isX Whether it is an X axis or a value axis
  9184. */
  9185. addAxis: function (options, isX, redraw, animation) {
  9186. var key = isX ? 'xAxis' : 'yAxis',
  9187. chartOptions = this.options,
  9188. axis;
  9189. /*jslint unused: false*/
  9190. axis = new Axis(this, merge(options, {
  9191. index: this[key].length,
  9192. isX: isX
  9193. }));
  9194. /*jslint unused: true*/
  9195. // Push the new axis options to the chart options
  9196. chartOptions[key] = splat(chartOptions[key] || {});
  9197. chartOptions[key].push(options);
  9198. if (pick(redraw, true)) {
  9199. this.redraw(animation);
  9200. }
  9201. },
  9202. /**
  9203. * Check whether a given point is within the plot area
  9204. *
  9205. * @param {Number} plotX Pixel x relative to the plot area
  9206. * @param {Number} plotY Pixel y relative to the plot area
  9207. * @param {Boolean} inverted Whether the chart is inverted
  9208. */
  9209. isInsidePlot: function (plotX, plotY, inverted) {
  9210. var x = inverted ? plotY : plotX,
  9211. y = inverted ? plotX : plotY;
  9212. return x >= 0 &&
  9213. x <= this.plotWidth &&
  9214. y >= 0 &&
  9215. y <= this.plotHeight;
  9216. },
  9217. /**
  9218. * Adjust all axes tick amounts
  9219. */
  9220. adjustTickAmounts: function () {
  9221. if (this.options.chart.alignTicks !== false) {
  9222. each(this.axes, function (axis) {
  9223. axis.adjustTickAmount();
  9224. });
  9225. }
  9226. this.maxTicks = null;
  9227. },
  9228. /**
  9229. * Redraw legend, axes or series based on updated data
  9230. *
  9231. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  9232. * configuration
  9233. */
  9234. redraw: function (animation) {
  9235. var chart = this,
  9236. axes = chart.axes,
  9237. series = chart.series,
  9238. pointer = chart.pointer,
  9239. legend = chart.legend,
  9240. redrawLegend = chart.isDirtyLegend,
  9241. hasStackedSeries,
  9242. hasDirtyStacks,
  9243. isDirtyBox = chart.isDirtyBox, // todo: check if it has actually changed?
  9244. seriesLength = series.length,
  9245. i = seriesLength,
  9246. serie,
  9247. renderer = chart.renderer,
  9248. isHiddenChart = renderer.isHidden(),
  9249. afterRedraw = [];
  9250. setAnimation(animation, chart);
  9251. if (isHiddenChart) {
  9252. chart.cloneRenderTo();
  9253. }
  9254. // Adjust title layout (reflow multiline text)
  9255. chart.layOutTitles();
  9256. // link stacked series
  9257. while (i--) {
  9258. serie = series[i];
  9259. if (serie.options.stacking) {
  9260. hasStackedSeries = true;
  9261. if (serie.isDirty) {
  9262. hasDirtyStacks = true;
  9263. break;
  9264. }
  9265. }
  9266. }
  9267. if (hasDirtyStacks) { // mark others as dirty
  9268. i = seriesLength;
  9269. while (i--) {
  9270. serie = series[i];
  9271. if (serie.options.stacking) {
  9272. serie.isDirty = true;
  9273. }
  9274. }
  9275. }
  9276. // handle updated data in the series
  9277. each(series, function (serie) {
  9278. if (serie.isDirty) { // prepare the data so axis can read it
  9279. if (serie.options.legendType === 'point') {
  9280. redrawLegend = true;
  9281. }
  9282. }
  9283. });
  9284. // handle added or removed series
  9285. if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed
  9286. // draw legend graphics
  9287. legend.render();
  9288. chart.isDirtyLegend = false;
  9289. }
  9290. // reset stacks
  9291. if (hasStackedSeries) {
  9292. chart.getStacks();
  9293. }
  9294. if (chart.hasCartesianSeries) {
  9295. if (!chart.isResizing) {
  9296. // reset maxTicks
  9297. chart.maxTicks = null;
  9298. // set axes scales
  9299. each(axes, function (axis) {
  9300. axis.setScale();
  9301. });
  9302. }
  9303. chart.adjustTickAmounts();
  9304. chart.getMargins();
  9305. // If one axis is dirty, all axes must be redrawn (#792, #2169)
  9306. each(axes, function (axis) {
  9307. if (axis.isDirty) {
  9308. isDirtyBox = true;
  9309. }
  9310. });
  9311. // redraw axes
  9312. each(axes, function (axis) {
  9313. // Fire 'afterSetExtremes' only if extremes are set
  9314. if (axis.isDirtyExtremes) { // #821
  9315. axis.isDirtyExtremes = false;
  9316. afterRedraw.push(function () { // prevent a recursive call to chart.redraw() (#1119)
  9317. fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751
  9318. delete axis.eventArgs;
  9319. });
  9320. }
  9321. if (isDirtyBox || hasStackedSeries) {
  9322. axis.redraw();
  9323. }
  9324. });
  9325. }
  9326. // the plot areas size has changed
  9327. if (isDirtyBox) {
  9328. chart.drawChartBox();
  9329. }
  9330. // redraw affected series
  9331. each(series, function (serie) {
  9332. if (serie.isDirty && serie.visible &&
  9333. (!serie.isCartesian || serie.xAxis)) { // issue #153
  9334. serie.redraw();
  9335. }
  9336. });
  9337. // move tooltip or reset
  9338. if (pointer && pointer.reset) {
  9339. pointer.reset(true);
  9340. }
  9341. // redraw if canvas
  9342. renderer.draw();
  9343. // fire the event
  9344. fireEvent(chart, 'redraw'); // jQuery breaks this when calling it from addEvent. Overwrites chart.redraw
  9345. if (isHiddenChart) {
  9346. chart.cloneRenderTo(true);
  9347. }
  9348. // Fire callbacks that are put on hold until after the redraw
  9349. each(afterRedraw, function (callback) {
  9350. callback.call();
  9351. });
  9352. },
  9353. /**
  9354. * Dim the chart and show a loading text or symbol
  9355. * @param {String} str An optional text to show in the loading label instead of the default one
  9356. */
  9357. showLoading: function (str) {
  9358. var chart = this,
  9359. options = chart.options,
  9360. loadingDiv = chart.loadingDiv;
  9361. var loadingOptions = options.loading;
  9362. // create the layer at the first call
  9363. if (!loadingDiv) {
  9364. chart.loadingDiv = loadingDiv = createElement(DIV, {
  9365. className: PREFIX + 'loading'
  9366. }, extend(loadingOptions.style, {
  9367. zIndex: 10,
  9368. display: NONE
  9369. }), chart.container);
  9370. chart.loadingSpan = createElement(
  9371. 'span',
  9372. null,
  9373. loadingOptions.labelStyle,
  9374. loadingDiv
  9375. );
  9376. }
  9377. // update text
  9378. chart.loadingSpan.innerHTML = str || options.lang.loading;
  9379. // show it
  9380. if (!chart.loadingShown) {
  9381. css(loadingDiv, {
  9382. opacity: 0,
  9383. display: '',
  9384. left: chart.plotLeft + PX,
  9385. top: chart.plotTop + PX,
  9386. width: chart.plotWidth + PX,
  9387. height: chart.plotHeight + PX
  9388. });
  9389. animate(loadingDiv, {
  9390. opacity: loadingOptions.style.opacity
  9391. }, {
  9392. duration: loadingOptions.showDuration || 0
  9393. });
  9394. chart.loadingShown = true;
  9395. }
  9396. },
  9397. /**
  9398. * Hide the loading layer
  9399. */
  9400. hideLoading: function () {
  9401. var options = this.options,
  9402. loadingDiv = this.loadingDiv;
  9403. if (loadingDiv) {
  9404. animate(loadingDiv, {
  9405. opacity: 0
  9406. }, {
  9407. duration: options.loading.hideDuration || 100,
  9408. complete: function () {
  9409. css(loadingDiv, { display: NONE });
  9410. }
  9411. });
  9412. }
  9413. this.loadingShown = false;
  9414. },
  9415. /**
  9416. * Get an axis, series or point object by id.
  9417. * @param id {String} The id as given in the configuration options
  9418. */
  9419. get: function (id) {
  9420. var chart = this,
  9421. axes = chart.axes,
  9422. series = chart.series;
  9423. var i,
  9424. j,
  9425. points;
  9426. // search axes
  9427. for (i = 0; i < axes.length; i++) {
  9428. if (axes[i].options.id === id) {
  9429. return axes[i];
  9430. }
  9431. }
  9432. // search series
  9433. for (i = 0; i < series.length; i++) {
  9434. if (series[i].options.id === id) {
  9435. return series[i];
  9436. }
  9437. }
  9438. // search points
  9439. for (i = 0; i < series.length; i++) {
  9440. points = series[i].points || [];
  9441. for (j = 0; j < points.length; j++) {
  9442. if (points[j].id === id) {
  9443. return points[j];
  9444. }
  9445. }
  9446. }
  9447. return null;
  9448. },
  9449. /**
  9450. * Create the Axis instances based on the config options
  9451. */
  9452. getAxes: function () {
  9453. var chart = this,
  9454. options = this.options,
  9455. xAxisOptions = options.xAxis = splat(options.xAxis || {}),
  9456. yAxisOptions = options.yAxis = splat(options.yAxis || {}),
  9457. optionsArray,
  9458. axis;
  9459. // make sure the options are arrays and add some members
  9460. each(xAxisOptions, function (axis, i) {
  9461. axis.index = i;
  9462. axis.isX = true;
  9463. });
  9464. each(yAxisOptions, function (axis, i) {
  9465. axis.index = i;
  9466. });
  9467. // concatenate all axis options into one array
  9468. optionsArray = xAxisOptions.concat(yAxisOptions);
  9469. each(optionsArray, function (axisOptions) {
  9470. axis = new Axis(chart, axisOptions);
  9471. });
  9472. chart.adjustTickAmounts();
  9473. },
  9474. /**
  9475. * Get the currently selected points from all series
  9476. */
  9477. getSelectedPoints: function () {
  9478. var points = [];
  9479. each(this.series, function (serie) {
  9480. points = points.concat(grep(serie.points || [], function (point) {
  9481. return point.selected;
  9482. }));
  9483. });
  9484. return points;
  9485. },
  9486. /**
  9487. * Get the currently selected series
  9488. */
  9489. getSelectedSeries: function () {
  9490. return grep(this.series, function (serie) {
  9491. return serie.selected;
  9492. });
  9493. },
  9494. /**
  9495. * Generate stacks for each series and calculate stacks total values
  9496. */
  9497. getStacks: function () {
  9498. var chart = this;
  9499. // reset stacks for each yAxis
  9500. each(chart.yAxis, function (axis) {
  9501. if (axis.stacks && axis.hasVisibleSeries) {
  9502. axis.oldStacks = axis.stacks;
  9503. }
  9504. });
  9505. each(chart.series, function (series) {
  9506. if (series.options.stacking && (series.visible === true || chart.options.chart.ignoreHiddenSeries === false)) {
  9507. series.stackKey = series.type + pick(series.options.stack, '');
  9508. }
  9509. });
  9510. },
  9511. /**
  9512. * Display the zoom button
  9513. */
  9514. showResetZoom: function () {
  9515. var chart = this,
  9516. lang = defaultOptions.lang,
  9517. btnOptions = chart.options.chart.resetZoomButton,
  9518. theme = btnOptions.theme,
  9519. states = theme.states,
  9520. alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox';
  9521. this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, function () { chart.zoomOut(); }, theme, states && states.hover)
  9522. .attr({
  9523. align: btnOptions.position.align,
  9524. title: lang.resetZoomTitle
  9525. })
  9526. .add()
  9527. .align(btnOptions.position, false, alignTo);
  9528. },
  9529. /**
  9530. * Zoom out to 1:1
  9531. */
  9532. zoomOut: function () {
  9533. var chart = this;
  9534. fireEvent(chart, 'selection', { resetSelection: true }, function () {
  9535. chart.zoom();
  9536. });
  9537. },
  9538. /**
  9539. * Zoom into a given portion of the chart given by axis coordinates
  9540. * @param {Object} event
  9541. */
  9542. zoom: function (event) {
  9543. var chart = this,
  9544. hasZoomed,
  9545. pointer = chart.pointer,
  9546. displayButton = false,
  9547. resetZoomButton;
  9548. // If zoom is called with no arguments, reset the axes
  9549. if (!event || event.resetSelection) {
  9550. each(chart.axes, function (axis) {
  9551. hasZoomed = axis.zoom();
  9552. });
  9553. } else { // else, zoom in on all axes
  9554. each(event.xAxis.concat(event.yAxis), function (axisData) {
  9555. var axis = axisData.axis,
  9556. isXAxis = axis.isXAxis;
  9557. // don't zoom more than minRange
  9558. if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) {
  9559. hasZoomed = axis.zoom(axisData.min, axisData.max);
  9560. if (axis.displayBtn) {
  9561. displayButton = true;
  9562. }
  9563. }
  9564. });
  9565. }
  9566. // Show or hide the Reset zoom button
  9567. resetZoomButton = chart.resetZoomButton;
  9568. if (displayButton && !resetZoomButton) {
  9569. chart.showResetZoom();
  9570. } else if (!displayButton && isObject(resetZoomButton)) {
  9571. chart.resetZoomButton = resetZoomButton.destroy();
  9572. }
  9573. // Redraw
  9574. if (hasZoomed) {
  9575. chart.redraw(
  9576. pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation
  9577. );
  9578. }
  9579. },
  9580. /**
  9581. * Pan the chart by dragging the mouse across the pane. This function is called
  9582. * on mouse move, and the distance to pan is computed from chartX compared to
  9583. * the first chartX position in the dragging operation.
  9584. */
  9585. pan: function (e, panning) {
  9586. var chart = this,
  9587. hoverPoints = chart.hoverPoints,
  9588. doRedraw;
  9589. // remove active points for shared tooltip
  9590. if (hoverPoints) {
  9591. each(hoverPoints, function (point) {
  9592. point.setState();
  9593. });
  9594. }
  9595. each(panning === 'xy' ? [1, 0] : [1], function (isX) { // xy is used in maps
  9596. var mousePos = e[isX ? 'chartX' : 'chartY'],
  9597. axis = chart[isX ? 'xAxis' : 'yAxis'][0],
  9598. startPos = chart[isX ? 'mouseDownX' : 'mouseDownY'],
  9599. halfPointRange = (axis.pointRange || 0) / 2,
  9600. extremes = axis.getExtremes(),
  9601. newMin = axis.toValue(startPos - mousePos, true) + halfPointRange,
  9602. newMax = axis.toValue(startPos + chart[isX ? 'plotWidth' : 'plotHeight'] - mousePos, true) - halfPointRange;
  9603. if (axis.series.length && newMin > mathMin(extremes.dataMin, extremes.min) && newMax < mathMax(extremes.dataMax, extremes.max)) {
  9604. axis.setExtremes(newMin, newMax, false, false, { trigger: 'pan' });
  9605. doRedraw = true;
  9606. }
  9607. chart[isX ? 'mouseDownX' : 'mouseDownY'] = mousePos; // set new reference for next run
  9608. });
  9609. if (doRedraw) {
  9610. chart.redraw(false);
  9611. }
  9612. css(chart.container, { cursor: 'move' });
  9613. },
  9614. /**
  9615. * Show the title and subtitle of the chart
  9616. *
  9617. * @param titleOptions {Object} New title options
  9618. * @param subtitleOptions {Object} New subtitle options
  9619. *
  9620. */
  9621. setTitle: function (titleOptions, subtitleOptions) {
  9622. var chart = this,
  9623. options = chart.options,
  9624. chartTitleOptions,
  9625. chartSubtitleOptions;
  9626. chartTitleOptions = options.title = merge(options.title, titleOptions);
  9627. chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions);
  9628. // add title and subtitle
  9629. each([
  9630. ['title', titleOptions, chartTitleOptions],
  9631. ['subtitle', subtitleOptions, chartSubtitleOptions]
  9632. ], function (arr) {
  9633. var name = arr[0],
  9634. title = chart[name],
  9635. titleOptions = arr[1],
  9636. chartTitleOptions = arr[2];
  9637. if (title && titleOptions) {
  9638. chart[name] = title = title.destroy(); // remove old
  9639. }
  9640. if (chartTitleOptions && chartTitleOptions.text && !title) {
  9641. chart[name] = chart.renderer.text(
  9642. chartTitleOptions.text,
  9643. 0,
  9644. 0,
  9645. chartTitleOptions.useHTML
  9646. )
  9647. .attr({
  9648. align: chartTitleOptions.align,
  9649. 'class': PREFIX + name,
  9650. zIndex: chartTitleOptions.zIndex || 4
  9651. })
  9652. .css(chartTitleOptions.style)
  9653. .add();
  9654. }
  9655. });
  9656. chart.layOutTitles();
  9657. },
  9658. /**
  9659. * Lay out the chart titles and cache the full offset height for use in getMargins
  9660. */
  9661. layOutTitles: function () {
  9662. var titleOffset = 0,
  9663. title = this.title,
  9664. subtitle = this.subtitle,
  9665. options = this.options,
  9666. titleOptions = options.title,
  9667. subtitleOptions = options.subtitle,
  9668. autoWidth = this.spacingBox.width - 44; // 44 makes room for default context button
  9669. if (title) {
  9670. title
  9671. .css({ width: (titleOptions.width || autoWidth) + PX })
  9672. .align(extend({ y: 15 }, titleOptions), false, 'spacingBox');
  9673. if (!titleOptions.floating && !titleOptions.verticalAlign) {
  9674. titleOffset = title.getBBox().height;
  9675. // Adjust for browser consistency + backwards compat after #776 fix
  9676. if (titleOffset >= 18 && titleOffset <= 25) {
  9677. titleOffset = 15;
  9678. }
  9679. }
  9680. }
  9681. if (subtitle) {
  9682. subtitle
  9683. .css({ width: (subtitleOptions.width || autoWidth) + PX })
  9684. .align(extend({ y: titleOffset + titleOptions.margin }, subtitleOptions), false, 'spacingBox');
  9685. if (!subtitleOptions.floating && !subtitleOptions.verticalAlign) {
  9686. titleOffset = mathCeil(titleOffset + subtitle.getBBox().height);
  9687. }
  9688. }
  9689. this.titleOffset = titleOffset; // used in getMargins
  9690. },
  9691. /**
  9692. * Get chart width and height according to options and container size
  9693. */
  9694. getChartSize: function () {
  9695. var chart = this,
  9696. optionsChart = chart.options.chart,
  9697. renderTo = chart.renderToClone || chart.renderTo;
  9698. // get inner width and height from jQuery (#824)
  9699. chart.containerWidth = adapterRun(renderTo, 'width');
  9700. chart.containerHeight = adapterRun(renderTo, 'height');
  9701. chart.chartWidth = mathMax(0, optionsChart.width || chart.containerWidth || 600); // #1393, 1460
  9702. chart.chartHeight = mathMax(0, pick(optionsChart.height,
  9703. // the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7:
  9704. chart.containerHeight > 19 ? chart.containerHeight : 400));
  9705. },
  9706. /**
  9707. * Create a clone of the chart's renderTo div and place it outside the viewport to allow
  9708. * size computation on chart.render and chart.redraw
  9709. */
  9710. cloneRenderTo: function (revert) {
  9711. var clone = this.renderToClone,
  9712. container = this.container;
  9713. // Destroy the clone and bring the container back to the real renderTo div
  9714. if (revert) {
  9715. if (clone) {
  9716. this.renderTo.appendChild(container);
  9717. discardElement(clone);
  9718. delete this.renderToClone;
  9719. }
  9720. // Set up the clone
  9721. } else {
  9722. if (container && container.parentNode === this.renderTo) {
  9723. this.renderTo.removeChild(container); // do not clone this
  9724. }
  9725. this.renderToClone = clone = this.renderTo.cloneNode(0);
  9726. css(clone, {
  9727. position: ABSOLUTE,
  9728. top: '-9999px',
  9729. display: 'block' // #833
  9730. });
  9731. doc.body.appendChild(clone);
  9732. if (container) {
  9733. clone.appendChild(container);
  9734. }
  9735. }
  9736. },
  9737. /**
  9738. * Get the containing element, determine the size and create the inner container
  9739. * div to hold the chart
  9740. */
  9741. getContainer: function () {
  9742. var chart = this,
  9743. container,
  9744. optionsChart = chart.options.chart,
  9745. chartWidth,
  9746. chartHeight,
  9747. renderTo,
  9748. indexAttrName = 'data-highcharts-chart',
  9749. oldChartIndex,
  9750. containerId;
  9751. chart.renderTo = renderTo = optionsChart.renderTo;
  9752. containerId = PREFIX + idCounter++;
  9753. if (isString(renderTo)) {
  9754. chart.renderTo = renderTo = doc.getElementById(renderTo);
  9755. }
  9756. // Display an error if the renderTo is wrong
  9757. if (!renderTo) {
  9758. error(13, true);
  9759. }
  9760. // If the container already holds a chart, destroy it
  9761. oldChartIndex = pInt(attr(renderTo, indexAttrName));
  9762. if (!isNaN(oldChartIndex) && charts[oldChartIndex]) {
  9763. charts[oldChartIndex].destroy();
  9764. }
  9765. // Make a reference to the chart from the div
  9766. attr(renderTo, indexAttrName, chart.index);
  9767. // remove previous chart
  9768. renderTo.innerHTML = '';
  9769. // If the container doesn't have an offsetWidth, it has or is a child of a node
  9770. // that has display:none. We need to temporarily move it out to a visible
  9771. // state to determine the size, else the legend and tooltips won't render
  9772. // properly
  9773. if (!renderTo.offsetWidth) {
  9774. chart.cloneRenderTo();
  9775. }
  9776. // get the width and height
  9777. chart.getChartSize();
  9778. chartWidth = chart.chartWidth;
  9779. chartHeight = chart.chartHeight;
  9780. // create the inner container
  9781. chart.container = container = createElement(DIV, {
  9782. className: PREFIX + 'container' +
  9783. (optionsChart.className ? ' ' + optionsChart.className : ''),
  9784. id: containerId
  9785. }, extend({
  9786. position: RELATIVE,
  9787. overflow: HIDDEN, // needed for context menu (avoid scrollbars) and
  9788. // content overflow in IE
  9789. width: chartWidth + PX,
  9790. height: chartHeight + PX,
  9791. textAlign: 'left',
  9792. lineHeight: 'normal', // #427
  9793. zIndex: 0, // #1072
  9794. '-webkit-tap-highlight-color': 'rgba(0,0,0,0)'
  9795. }, optionsChart.style),
  9796. chart.renderToClone || renderTo
  9797. );
  9798. // cache the cursor (#1650)
  9799. chart._cursor = container.style.cursor;
  9800. chart.renderer =
  9801. optionsChart.forExport ? // force SVG, used for SVG export
  9802. new SVGRenderer(container, chartWidth, chartHeight, true) :
  9803. new Renderer(container, chartWidth, chartHeight);
  9804. if (useCanVG) {
  9805. // If we need canvg library, extend and configure the renderer
  9806. // to get the tracker for translating mouse events
  9807. chart.renderer.create(chart, container, chartWidth, chartHeight);
  9808. }
  9809. },
  9810. /**
  9811. * Calculate margins by rendering axis labels in a preliminary position. Title,
  9812. * subtitle and legend have already been rendered at this stage, but will be
  9813. * moved into their final positions
  9814. */
  9815. getMargins: function () {
  9816. var chart = this,
  9817. spacing = chart.spacing,
  9818. axisOffset,
  9819. legend = chart.legend,
  9820. margin = chart.margin,
  9821. legendOptions = chart.options.legend,
  9822. legendMargin = pick(legendOptions.margin, 10),
  9823. legendX = legendOptions.x,
  9824. legendY = legendOptions.y,
  9825. align = legendOptions.align,
  9826. verticalAlign = legendOptions.verticalAlign,
  9827. titleOffset = chart.titleOffset;
  9828. chart.resetMargins();
  9829. axisOffset = chart.axisOffset;
  9830. // Adjust for title and subtitle
  9831. if (titleOffset && !defined(margin[0])) {
  9832. chart.plotTop = mathMax(chart.plotTop, titleOffset + chart.options.title.margin + spacing[0]);
  9833. }
  9834. // Adjust for legend
  9835. if (legend.display && !legendOptions.floating) {
  9836. if (align === 'right') { // horizontal alignment handled first
  9837. if (!defined(margin[1])) {
  9838. chart.marginRight = mathMax(
  9839. chart.marginRight,
  9840. legend.legendWidth - legendX + legendMargin + spacing[1]
  9841. );
  9842. }
  9843. } else if (align === 'left') {
  9844. if (!defined(margin[3])) {
  9845. chart.plotLeft = mathMax(
  9846. chart.plotLeft,
  9847. legend.legendWidth + legendX + legendMargin + spacing[3]
  9848. );
  9849. }
  9850. } else if (verticalAlign === 'top') {
  9851. if (!defined(margin[0])) {
  9852. chart.plotTop = mathMax(
  9853. chart.plotTop,
  9854. legend.legendHeight + legendY + legendMargin + spacing[0]
  9855. );
  9856. }
  9857. } else if (verticalAlign === 'bottom') {
  9858. if (!defined(margin[2])) {
  9859. chart.marginBottom = mathMax(
  9860. chart.marginBottom,
  9861. legend.legendHeight - legendY + legendMargin + spacing[2]
  9862. );
  9863. }
  9864. }
  9865. }
  9866. // adjust for scroller
  9867. if (chart.extraBottomMargin) {
  9868. chart.marginBottom += chart.extraBottomMargin;
  9869. }
  9870. if (chart.extraTopMargin) {
  9871. chart.plotTop += chart.extraTopMargin;
  9872. }
  9873. // pre-render axes to get labels offset width
  9874. if (chart.hasCartesianSeries) {
  9875. each(chart.axes, function (axis) {
  9876. axis.getOffset();
  9877. });
  9878. }
  9879. if (!defined(margin[3])) {
  9880. chart.plotLeft += axisOffset[3];
  9881. }
  9882. if (!defined(margin[0])) {
  9883. chart.plotTop += axisOffset[0];
  9884. }
  9885. if (!defined(margin[2])) {
  9886. chart.marginBottom += axisOffset[2];
  9887. }
  9888. if (!defined(margin[1])) {
  9889. chart.marginRight += axisOffset[1];
  9890. }
  9891. chart.setChartSize();
  9892. },
  9893. /**
  9894. * Add the event handlers necessary for auto resizing
  9895. *
  9896. */
  9897. initReflow: function () {
  9898. var chart = this,
  9899. optionsChart = chart.options.chart,
  9900. renderTo = chart.renderTo,
  9901. reflowTimeout;
  9902. function reflow(e) {
  9903. var width = optionsChart.width || adapterRun(renderTo, 'width'),
  9904. height = optionsChart.height || adapterRun(renderTo, 'height'),
  9905. target = e ? e.target : win; // #805 - MooTools doesn't supply e
  9906. // Width and height checks for display:none. Target is doc in IE8 and Opera,
  9907. // win in Firefox, Chrome and IE9.
  9908. if (!chart.hasUserSize && width && height && (target === win || target === doc)) {
  9909. if (width !== chart.containerWidth || height !== chart.containerHeight) {
  9910. clearTimeout(reflowTimeout);
  9911. chart.reflowTimeout = reflowTimeout = setTimeout(function () {
  9912. if (chart.container) { // It may have been destroyed in the meantime (#1257)
  9913. chart.setSize(width, height, false);
  9914. chart.hasUserSize = null;
  9915. }
  9916. }, 100);
  9917. }
  9918. chart.containerWidth = width;
  9919. chart.containerHeight = height;
  9920. }
  9921. }
  9922. chart.reflow = reflow;
  9923. addEvent(win, 'resize', reflow);
  9924. addEvent(chart, 'destroy', function () {
  9925. removeEvent(win, 'resize', reflow);
  9926. });
  9927. },
  9928. /**
  9929. * Resize the chart to a given width and height
  9930. * @param {Number} width
  9931. * @param {Number} height
  9932. * @param {Object|Boolean} animation
  9933. */
  9934. setSize: function (width, height, animation) {
  9935. var chart = this,
  9936. chartWidth,
  9937. chartHeight,
  9938. fireEndResize;
  9939. // Handle the isResizing counter
  9940. chart.isResizing += 1;
  9941. fireEndResize = function () {
  9942. if (chart) {
  9943. fireEvent(chart, 'endResize', null, function () {
  9944. chart.isResizing -= 1;
  9945. });
  9946. }
  9947. };
  9948. // set the animation for the current process
  9949. setAnimation(animation, chart);
  9950. chart.oldChartHeight = chart.chartHeight;
  9951. chart.oldChartWidth = chart.chartWidth;
  9952. if (defined(width)) {
  9953. chart.chartWidth = chartWidth = mathMax(0, mathRound(width));
  9954. chart.hasUserSize = !!chartWidth;
  9955. }
  9956. if (defined(height)) {
  9957. chart.chartHeight = chartHeight = mathMax(0, mathRound(height));
  9958. }
  9959. css(chart.container, {
  9960. width: chartWidth + PX,
  9961. height: chartHeight + PX
  9962. });
  9963. chart.setChartSize(true);
  9964. chart.renderer.setSize(chartWidth, chartHeight, animation);
  9965. // handle axes
  9966. chart.maxTicks = null;
  9967. each(chart.axes, function (axis) {
  9968. axis.isDirty = true;
  9969. axis.setScale();
  9970. });
  9971. // make sure non-cartesian series are also handled
  9972. each(chart.series, function (serie) {
  9973. serie.isDirty = true;
  9974. });
  9975. chart.isDirtyLegend = true; // force legend redraw
  9976. chart.isDirtyBox = true; // force redraw of plot and chart border
  9977. chart.getMargins();
  9978. chart.redraw(animation);
  9979. chart.oldChartHeight = null;
  9980. fireEvent(chart, 'resize');
  9981. // fire endResize and set isResizing back
  9982. // If animation is disabled, fire without delay
  9983. if (globalAnimation === false) {
  9984. fireEndResize();
  9985. } else { // else set a timeout with the animation duration
  9986. setTimeout(fireEndResize, (globalAnimation && globalAnimation.duration) || 500);
  9987. }
  9988. },
  9989. /**
  9990. * Set the public chart properties. This is done before and after the pre-render
  9991. * to determine margin sizes
  9992. */
  9993. setChartSize: function (skipAxes) {
  9994. var chart = this,
  9995. inverted = chart.inverted,
  9996. renderer = chart.renderer,
  9997. chartWidth = chart.chartWidth,
  9998. chartHeight = chart.chartHeight,
  9999. optionsChart = chart.options.chart,
  10000. spacing = chart.spacing,
  10001. clipOffset = chart.clipOffset,
  10002. clipX,
  10003. clipY,
  10004. plotLeft,
  10005. plotTop,
  10006. plotWidth,
  10007. plotHeight,
  10008. plotBorderWidth;
  10009. chart.plotLeft = plotLeft = mathRound(chart.plotLeft);
  10010. chart.plotTop = plotTop = mathRound(chart.plotTop);
  10011. chart.plotWidth = plotWidth = mathMax(0, mathRound(chartWidth - plotLeft - chart.marginRight));
  10012. chart.plotHeight = plotHeight = mathMax(0, mathRound(chartHeight - plotTop - chart.marginBottom));
  10013. chart.plotSizeX = inverted ? plotHeight : plotWidth;
  10014. chart.plotSizeY = inverted ? plotWidth : plotHeight;
  10015. chart.plotBorderWidth = optionsChart.plotBorderWidth || 0;
  10016. // Set boxes used for alignment
  10017. chart.spacingBox = renderer.spacingBox = {
  10018. x: spacing[3],
  10019. y: spacing[0],
  10020. width: chartWidth - spacing[3] - spacing[1],
  10021. height: chartHeight - spacing[0] - spacing[2]
  10022. };
  10023. chart.plotBox = renderer.plotBox = {
  10024. x: plotLeft,
  10025. y: plotTop,
  10026. width: plotWidth,
  10027. height: plotHeight
  10028. };
  10029. plotBorderWidth = 2 * mathFloor(chart.plotBorderWidth / 2);
  10030. clipX = mathCeil(mathMax(plotBorderWidth, clipOffset[3]) / 2);
  10031. clipY = mathCeil(mathMax(plotBorderWidth, clipOffset[0]) / 2);
  10032. chart.clipBox = {
  10033. x: clipX,
  10034. y: clipY,
  10035. width: mathFloor(chart.plotSizeX - mathMax(plotBorderWidth, clipOffset[1]) / 2 - clipX),
  10036. height: mathFloor(chart.plotSizeY - mathMax(plotBorderWidth, clipOffset[2]) / 2 - clipY)
  10037. };
  10038. if (!skipAxes) {
  10039. each(chart.axes, function (axis) {
  10040. axis.setAxisSize();
  10041. axis.setAxisTranslation();
  10042. });
  10043. }
  10044. },
  10045. /**
  10046. * Initial margins before auto size margins are applied
  10047. */
  10048. resetMargins: function () {
  10049. var chart = this,
  10050. spacing = chart.spacing,
  10051. margin = chart.margin;
  10052. chart.plotTop = pick(margin[0], spacing[0]);
  10053. chart.marginRight = pick(margin[1], spacing[1]);
  10054. chart.marginBottom = pick(margin[2], spacing[2]);
  10055. chart.plotLeft = pick(margin[3], spacing[3]);
  10056. chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left
  10057. chart.clipOffset = [0, 0, 0, 0];
  10058. },
  10059. /**
  10060. * Draw the borders and backgrounds for chart and plot area
  10061. */
  10062. drawChartBox: function () {
  10063. var chart = this,
  10064. optionsChart = chart.options.chart,
  10065. renderer = chart.renderer,
  10066. chartWidth = chart.chartWidth,
  10067. chartHeight = chart.chartHeight,
  10068. chartBackground = chart.chartBackground,
  10069. plotBackground = chart.plotBackground,
  10070. plotBorder = chart.plotBorder,
  10071. plotBGImage = chart.plotBGImage,
  10072. chartBorderWidth = optionsChart.borderWidth || 0,
  10073. chartBackgroundColor = optionsChart.backgroundColor,
  10074. plotBackgroundColor = optionsChart.plotBackgroundColor,
  10075. plotBackgroundImage = optionsChart.plotBackgroundImage,
  10076. plotBorderWidth = optionsChart.plotBorderWidth || 0,
  10077. mgn,
  10078. bgAttr,
  10079. plotLeft = chart.plotLeft,
  10080. plotTop = chart.plotTop,
  10081. plotWidth = chart.plotWidth,
  10082. plotHeight = chart.plotHeight,
  10083. plotBox = chart.plotBox,
  10084. clipRect = chart.clipRect,
  10085. clipBox = chart.clipBox;
  10086. // Chart area
  10087. mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0);
  10088. if (chartBorderWidth || chartBackgroundColor) {
  10089. if (!chartBackground) {
  10090. bgAttr = {
  10091. fill: chartBackgroundColor || NONE
  10092. };
  10093. if (chartBorderWidth) { // #980
  10094. bgAttr.stroke = optionsChart.borderColor;
  10095. bgAttr['stroke-width'] = chartBorderWidth;
  10096. }
  10097. chart.chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn,
  10098. optionsChart.borderRadius, chartBorderWidth)
  10099. .attr(bgAttr)
  10100. .add()
  10101. .shadow(optionsChart.shadow);
  10102. } else { // resize
  10103. chartBackground.animate(
  10104. chartBackground.crisp(null, null, null, chartWidth - mgn, chartHeight - mgn)
  10105. );
  10106. }
  10107. }
  10108. // Plot background
  10109. if (plotBackgroundColor) {
  10110. if (!plotBackground) {
  10111. chart.plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0)
  10112. .attr({
  10113. fill: plotBackgroundColor
  10114. })
  10115. .add()
  10116. .shadow(optionsChart.plotShadow);
  10117. } else {
  10118. plotBackground.animate(plotBox);
  10119. }
  10120. }
  10121. if (plotBackgroundImage) {
  10122. if (!plotBGImage) {
  10123. chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight)
  10124. .add();
  10125. } else {
  10126. plotBGImage.animate(plotBox);
  10127. }
  10128. }
  10129. // Plot clip
  10130. if (!clipRect) {
  10131. chart.clipRect = renderer.clipRect(clipBox);
  10132. } else {
  10133. clipRect.animate({
  10134. width: clipBox.width,
  10135. height: clipBox.height
  10136. });
  10137. }
  10138. // Plot area border
  10139. if (plotBorderWidth) {
  10140. if (!plotBorder) {
  10141. chart.plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, -plotBorderWidth)
  10142. .attr({
  10143. stroke: optionsChart.plotBorderColor,
  10144. 'stroke-width': plotBorderWidth,
  10145. zIndex: 1
  10146. })
  10147. .add();
  10148. } else {
  10149. plotBorder.animate(
  10150. plotBorder.crisp(null, plotLeft, plotTop, plotWidth, plotHeight)
  10151. );
  10152. }
  10153. }
  10154. // reset
  10155. chart.isDirtyBox = false;
  10156. },
  10157. /**
  10158. * Detect whether a certain chart property is needed based on inspecting its options
  10159. * and series. This mainly applies to the chart.invert property, and in extensions to
  10160. * the chart.angular and chart.polar properties.
  10161. */
  10162. propFromSeries: function () {
  10163. var chart = this,
  10164. optionsChart = chart.options.chart,
  10165. klass,
  10166. seriesOptions = chart.options.series,
  10167. i,
  10168. value;
  10169. each(['inverted', 'angular', 'polar'], function (key) {
  10170. // The default series type's class
  10171. klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType];
  10172. // Get the value from available chart-wide properties
  10173. value = (
  10174. chart[key] || // 1. it is set before
  10175. optionsChart[key] || // 2. it is set in the options
  10176. (klass && klass.prototype[key]) // 3. it's default series class requires it
  10177. );
  10178. // 4. Check if any the chart's series require it
  10179. i = seriesOptions && seriesOptions.length;
  10180. while (!value && i--) {
  10181. klass = seriesTypes[seriesOptions[i].type];
  10182. if (klass && klass.prototype[key]) {
  10183. value = true;
  10184. }
  10185. }
  10186. // Set the chart property
  10187. chart[key] = value;
  10188. });
  10189. },
  10190. /**
  10191. * Link two or more series together. This is done initially from Chart.render,
  10192. * and after Chart.addSeries and Series.remove.
  10193. */
  10194. linkSeries: function () {
  10195. var chart = this,
  10196. chartSeries = chart.series;
  10197. // Reset links
  10198. each(chartSeries, function (series) {
  10199. series.linkedSeries.length = 0;
  10200. });
  10201. // Apply new links
  10202. each(chartSeries, function (series) {
  10203. var linkedTo = series.options.linkedTo;
  10204. if (isString(linkedTo)) {
  10205. if (linkedTo === ':previous') {
  10206. linkedTo = chart.series[series.index - 1];
  10207. } else {
  10208. linkedTo = chart.get(linkedTo);
  10209. }
  10210. if (linkedTo) {
  10211. linkedTo.linkedSeries.push(series);
  10212. series.linkedParent = linkedTo;
  10213. }
  10214. }
  10215. });
  10216. },
  10217. /**
  10218. * Render all graphics for the chart
  10219. */
  10220. render: function () {
  10221. var chart = this,
  10222. axes = chart.axes,
  10223. renderer = chart.renderer,
  10224. options = chart.options;
  10225. var labels = options.labels,
  10226. credits = options.credits,
  10227. creditsHref;
  10228. // Title
  10229. chart.setTitle();
  10230. // Legend
  10231. chart.legend = new Legend(chart, options.legend);
  10232. chart.getStacks(); // render stacks
  10233. // Get margins by pre-rendering axes
  10234. // set axes scales
  10235. each(axes, function (axis) {
  10236. axis.setScale();
  10237. });
  10238. chart.getMargins();
  10239. chart.maxTicks = null; // reset for second pass
  10240. each(axes, function (axis) {
  10241. axis.setTickPositions(true); // update to reflect the new margins
  10242. axis.setMaxTicks();
  10243. });
  10244. chart.adjustTickAmounts();
  10245. chart.getMargins(); // second pass to check for new labels
  10246. // Draw the borders and backgrounds
  10247. chart.drawChartBox();
  10248. // Axes
  10249. if (chart.hasCartesianSeries) {
  10250. each(axes, function (axis) {
  10251. axis.render();
  10252. });
  10253. }
  10254. // The series
  10255. if (!chart.seriesGroup) {
  10256. chart.seriesGroup = renderer.g('series-group')
  10257. .attr({ zIndex: 3 })
  10258. .add();
  10259. }
  10260. each(chart.series, function (serie) {
  10261. serie.translate();
  10262. serie.setTooltipPoints();
  10263. serie.render();
  10264. });
  10265. // Labels
  10266. if (labels.items) {
  10267. each(labels.items, function (label) {
  10268. var style = extend(labels.style, label.style),
  10269. x = pInt(style.left) + chart.plotLeft,
  10270. y = pInt(style.top) + chart.plotTop + 12;
  10271. // delete to prevent rewriting in IE
  10272. delete style.left;
  10273. delete style.top;
  10274. renderer.text(
  10275. label.html,
  10276. x,
  10277. y
  10278. )
  10279. .attr({ zIndex: 2 })
  10280. .css(style)
  10281. .add();
  10282. });
  10283. }
  10284. // Credits
  10285. if (credits.enabled && !chart.credits) {
  10286. creditsHref = credits.href;
  10287. chart.credits = renderer.text(
  10288. credits.text,
  10289. 0,
  10290. 0
  10291. )
  10292. .on('click', function () {
  10293. if (creditsHref) {
  10294. location.href = creditsHref;
  10295. }
  10296. })
  10297. .attr({
  10298. align: credits.position.align,
  10299. zIndex: 8
  10300. })
  10301. .css(credits.style)
  10302. .add()
  10303. .align(credits.position);
  10304. }
  10305. // Set flag
  10306. chart.hasRendered = true;
  10307. },
  10308. /**
  10309. * Clean up memory usage
  10310. */
  10311. destroy: function () {
  10312. var chart = this,
  10313. axes = chart.axes,
  10314. series = chart.series,
  10315. container = chart.container,
  10316. i,
  10317. parentNode = container && container.parentNode;
  10318. // fire the chart.destoy event
  10319. fireEvent(chart, 'destroy');
  10320. // Delete the chart from charts lookup array
  10321. charts[chart.index] = UNDEFINED;
  10322. chart.renderTo.removeAttribute('data-highcharts-chart');
  10323. // remove events
  10324. removeEvent(chart);
  10325. // ==== Destroy collections:
  10326. // Destroy axes
  10327. i = axes.length;
  10328. while (i--) {
  10329. axes[i] = axes[i].destroy();
  10330. }
  10331. // Destroy each series
  10332. i = series.length;
  10333. while (i--) {
  10334. series[i] = series[i].destroy();
  10335. }
  10336. // ==== Destroy chart properties:
  10337. each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage',
  10338. 'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer', 'scroller',
  10339. 'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'], function (name) {
  10340. var prop = chart[name];
  10341. if (prop && prop.destroy) {
  10342. chart[name] = prop.destroy();
  10343. }
  10344. });
  10345. // remove container and all SVG
  10346. if (container) { // can break in IE when destroyed before finished loading
  10347. container.innerHTML = '';
  10348. removeEvent(container);
  10349. if (parentNode) {
  10350. discardElement(container);
  10351. }
  10352. }
  10353. // clean it all up
  10354. for (i in chart) {
  10355. delete chart[i];
  10356. }
  10357. },
  10358. /**
  10359. * VML namespaces can't be added until after complete. Listening
  10360. * for Perini's doScroll hack is not enough.
  10361. */
  10362. isReadyToRender: function () {
  10363. var chart = this;
  10364. // Note: in spite of JSLint's complaints, win == win.top is required
  10365. /*jslint eqeq: true*/
  10366. if ((!hasSVG && (win == win.top && doc.readyState !== 'complete')) || (useCanVG && !win.canvg)) {
  10367. /*jslint eqeq: false*/
  10368. if (useCanVG) {
  10369. // Delay rendering until canvg library is downloaded and ready
  10370. CanVGController.push(function () { chart.firstRender(); }, chart.options.global.canvasToolsURL);
  10371. } else {
  10372. doc.attachEvent('onreadystatechange', function () {
  10373. doc.detachEvent('onreadystatechange', chart.firstRender);
  10374. if (doc.readyState === 'complete') {
  10375. chart.firstRender();
  10376. }
  10377. });
  10378. }
  10379. return false;
  10380. }
  10381. return true;
  10382. },
  10383. /**
  10384. * Prepare for first rendering after all data are loaded
  10385. */
  10386. firstRender: function () {
  10387. var chart = this,
  10388. options = chart.options,
  10389. callback = chart.callback;
  10390. // Check whether the chart is ready to render
  10391. if (!chart.isReadyToRender()) {
  10392. return;
  10393. }
  10394. // Create the container
  10395. chart.getContainer();
  10396. // Run an early event after the container and renderer are established
  10397. fireEvent(chart, 'init');
  10398. chart.resetMargins();
  10399. chart.setChartSize();
  10400. // Set the common chart properties (mainly invert) from the given series
  10401. chart.propFromSeries();
  10402. // get axes
  10403. chart.getAxes();
  10404. // Initialize the series
  10405. each(options.series || [], function (serieOptions) {
  10406. chart.initSeries(serieOptions);
  10407. });
  10408. chart.linkSeries();
  10409. // Run an event after axes and series are initialized, but before render. At this stage,
  10410. // the series data is indexed and cached in the xData and yData arrays, so we can access
  10411. // those before rendering. Used in Highstock.
  10412. fireEvent(chart, 'beforeRender');
  10413. // depends on inverted and on margins being set
  10414. chart.pointer = new Pointer(chart, options);
  10415. chart.render();
  10416. // add canvas
  10417. chart.renderer.draw();
  10418. // run callbacks
  10419. if (callback) {
  10420. callback.apply(chart, [chart]);
  10421. }
  10422. each(chart.callbacks, function (fn) {
  10423. fn.apply(chart, [chart]);
  10424. });
  10425. // If the chart was rendered outside the top container, put it back in
  10426. chart.cloneRenderTo(true);
  10427. fireEvent(chart, 'load');
  10428. },
  10429. /**
  10430. * Creates arrays for spacing and margin from given options.
  10431. */
  10432. splashArray: function (target, options) {
  10433. var oVar = options[target],
  10434. tArray = isObject(oVar) ? oVar : [oVar, oVar, oVar, oVar];
  10435. return [pick(options[target + 'Top'], tArray[0]),
  10436. pick(options[target + 'Right'], tArray[1]),
  10437. pick(options[target + 'Bottom'], tArray[2]),
  10438. pick(options[target + 'Left'], tArray[3])];
  10439. }
  10440. }; // end Chart
  10441. // Hook for exporting module
  10442. Chart.prototype.callbacks = [];
  10443. /**
  10444. * The Point object and prototype. Inheritable and used as base for PiePoint
  10445. */
  10446. var Point = function () {};
  10447. Point.prototype = {
  10448. /**
  10449. * Initialize the point
  10450. * @param {Object} series The series object containing this point
  10451. * @param {Object} options The data in either number, array or object format
  10452. */
  10453. init: function (series, options, x) {
  10454. var point = this,
  10455. colors;
  10456. point.series = series;
  10457. point.applyOptions(options, x);
  10458. point.pointAttr = {};
  10459. if (series.options.colorByPoint) {
  10460. colors = series.options.colors || series.chart.options.colors;
  10461. point.color = point.color || colors[series.colorCounter++];
  10462. // loop back to zero
  10463. if (series.colorCounter === colors.length) {
  10464. series.colorCounter = 0;
  10465. }
  10466. }
  10467. series.chart.pointCount++;
  10468. return point;
  10469. },
  10470. /**
  10471. * Apply the options containing the x and y data and possible some extra properties.
  10472. * This is called on point init or from point.update.
  10473. *
  10474. * @param {Object} options
  10475. */
  10476. applyOptions: function (options, x) {
  10477. var point = this,
  10478. series = point.series,
  10479. pointValKey = series.pointValKey;
  10480. options = Point.prototype.optionsToObject.call(this, options);
  10481. // copy options directly to point
  10482. extend(point, options);
  10483. point.options = point.options ? extend(point.options, options) : options;
  10484. // For higher dimension series types. For instance, for ranges, point.y is mapped to point.low.
  10485. if (pointValKey) {
  10486. point.y = point[pointValKey];
  10487. }
  10488. // If no x is set by now, get auto incremented value. All points must have an
  10489. // x value, however the y value can be null to create a gap in the series
  10490. if (point.x === UNDEFINED && series) {
  10491. point.x = x === UNDEFINED ? series.autoIncrement() : x;
  10492. }
  10493. return point;
  10494. },
  10495. /**
  10496. * Transform number or array configs into objects
  10497. */
  10498. optionsToObject: function (options) {
  10499. var ret,
  10500. series = this.series,
  10501. pointArrayMap = series.pointArrayMap || ['y'],
  10502. valueCount = pointArrayMap.length,
  10503. firstItemType,
  10504. i = 0,
  10505. j = 0;
  10506. if (typeof options === 'number' || options === null) {
  10507. ret = { y: options };
  10508. } else if (isArray(options)) {
  10509. ret = {};
  10510. // with leading x value
  10511. if (options.length > valueCount) {
  10512. firstItemType = typeof options[0];
  10513. if (firstItemType === 'string') {
  10514. ret.name = options[0];
  10515. } else if (firstItemType === 'number') {
  10516. ret.x = options[0];
  10517. }
  10518. i++;
  10519. }
  10520. while (j < valueCount) {
  10521. ret[pointArrayMap[j++]] = options[i++];
  10522. }
  10523. } else if (typeof options === 'object') {
  10524. ret = options;
  10525. // This is the fastest way to detect if there are individual point dataLabels that need
  10526. // to be considered in drawDataLabels. These can only occur in object configs.
  10527. if (options.dataLabels) {
  10528. series._hasPointLabels = true;
  10529. }
  10530. // Same approach as above for markers
  10531. if (options.marker) {
  10532. series._hasPointMarkers = true;
  10533. }
  10534. }
  10535. return ret;
  10536. },
  10537. /**
  10538. * Destroy a point to clear memory. Its reference still stays in series.data.
  10539. */
  10540. destroy: function () {
  10541. var point = this,
  10542. series = point.series,
  10543. chart = series.chart,
  10544. hoverPoints = chart.hoverPoints,
  10545. prop;
  10546. chart.pointCount--;
  10547. if (hoverPoints) {
  10548. point.setState();
  10549. erase(hoverPoints, point);
  10550. if (!hoverPoints.length) {
  10551. chart.hoverPoints = null;
  10552. }
  10553. }
  10554. if (point === chart.hoverPoint) {
  10555. point.onMouseOut();
  10556. }
  10557. // remove all events
  10558. if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive
  10559. removeEvent(point);
  10560. point.destroyElements();
  10561. }
  10562. if (point.legendItem) { // pies have legend items
  10563. chart.legend.destroyItem(point);
  10564. }
  10565. for (prop in point) {
  10566. point[prop] = null;
  10567. }
  10568. },
  10569. /**
  10570. * Destroy SVG elements associated with the point
  10571. */
  10572. destroyElements: function () {
  10573. var point = this,
  10574. props = ['graphic', 'dataLabel', 'dataLabelUpper', 'group', 'connector', 'shadowGroup'],
  10575. prop,
  10576. i = 6;
  10577. while (i--) {
  10578. prop = props[i];
  10579. if (point[prop]) {
  10580. point[prop] = point[prop].destroy();
  10581. }
  10582. }
  10583. },
  10584. /**
  10585. * Return the configuration hash needed for the data label and tooltip formatters
  10586. */
  10587. getLabelConfig: function () {
  10588. var point = this;
  10589. return {
  10590. x: point.category,
  10591. y: point.y,
  10592. key: point.name || point.category,
  10593. series: point.series,
  10594. point: point,
  10595. percentage: point.percentage,
  10596. total: point.total || point.stackTotal
  10597. };
  10598. },
  10599. /**
  10600. * Toggle the selection status of a point
  10601. * @param {Boolean} selected Whether to select or unselect the point.
  10602. * @param {Boolean} accumulate Whether to add to the previous selection. By default,
  10603. * this happens if the control key (Cmd on Mac) was pressed during clicking.
  10604. */
  10605. select: function (selected, accumulate) {
  10606. var point = this,
  10607. series = point.series,
  10608. chart = series.chart;
  10609. selected = pick(selected, !point.selected);
  10610. // fire the event with the defalut handler
  10611. point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () {
  10612. point.selected = point.options.selected = selected;
  10613. series.options.data[inArray(point, series.data)] = point.options;
  10614. point.setState(selected && SELECT_STATE);
  10615. // unselect all other points unless Ctrl or Cmd + click
  10616. if (!accumulate) {
  10617. each(chart.getSelectedPoints(), function (loopPoint) {
  10618. if (loopPoint.selected && loopPoint !== point) {
  10619. loopPoint.selected = loopPoint.options.selected = false;
  10620. series.options.data[inArray(loopPoint, series.data)] = loopPoint.options;
  10621. loopPoint.setState(NORMAL_STATE);
  10622. loopPoint.firePointEvent('unselect');
  10623. }
  10624. });
  10625. }
  10626. });
  10627. },
  10628. /**
  10629. * Runs on mouse over the point
  10630. */
  10631. onMouseOver: function (e) {
  10632. var point = this,
  10633. series = point.series,
  10634. chart = series.chart,
  10635. tooltip = chart.tooltip,
  10636. hoverPoint = chart.hoverPoint;
  10637. // set normal state to previous series
  10638. if (hoverPoint && hoverPoint !== point) {
  10639. hoverPoint.onMouseOut();
  10640. }
  10641. // trigger the event
  10642. point.firePointEvent('mouseOver');
  10643. // update the tooltip
  10644. if (tooltip && (!tooltip.shared || series.noSharedTooltip)) {
  10645. tooltip.refresh(point, e);
  10646. }
  10647. // hover this
  10648. point.setState(HOVER_STATE);
  10649. chart.hoverPoint = point;
  10650. },
  10651. /**
  10652. * Runs on mouse out from the point
  10653. */
  10654. onMouseOut: function () {
  10655. var chart = this.series.chart,
  10656. hoverPoints = chart.hoverPoints;
  10657. if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887
  10658. this.firePointEvent('mouseOut');
  10659. this.setState();
  10660. chart.hoverPoint = null;
  10661. }
  10662. },
  10663. /**
  10664. * Extendable method for formatting each point's tooltip line
  10665. *
  10666. * @return {String} A string to be concatenated in to the common tooltip text
  10667. */
  10668. tooltipFormatter: function (pointFormat) {
  10669. // Insert options for valueDecimals, valuePrefix, and valueSuffix
  10670. var series = this.series,
  10671. seriesTooltipOptions = series.tooltipOptions,
  10672. valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''),
  10673. valuePrefix = seriesTooltipOptions.valuePrefix || '',
  10674. valueSuffix = seriesTooltipOptions.valueSuffix || '';
  10675. // Loop over the point array map and replace unformatted values with sprintf formatting markup
  10676. each(series.pointArrayMap || ['y'], function (key) {
  10677. key = '{point.' + key; // without the closing bracket
  10678. if (valuePrefix || valueSuffix) {
  10679. pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix);
  10680. }
  10681. pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}');
  10682. });
  10683. return format(pointFormat, {
  10684. point: this,
  10685. series: this.series
  10686. });
  10687. },
  10688. /**
  10689. * Update the point with new options (typically x/y data) and optionally redraw the series.
  10690. *
  10691. * @param {Object} options Point options as defined in the series.data array
  10692. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  10693. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  10694. * configuration
  10695. *
  10696. */
  10697. update: function (options, redraw, animation) {
  10698. var point = this,
  10699. series = point.series,
  10700. graphic = point.graphic,
  10701. i,
  10702. data = series.data,
  10703. chart = series.chart,
  10704. seriesOptions = series.options;
  10705. redraw = pick(redraw, true);
  10706. // fire the event with a default handler of doing the update
  10707. point.firePointEvent('update', { options: options }, function () {
  10708. point.applyOptions(options);
  10709. // update visuals
  10710. if (isObject(options)) {
  10711. series.getAttribs();
  10712. if (graphic) {
  10713. if (options.marker && options.marker.symbol) {
  10714. point.graphic = graphic.destroy();
  10715. } else {
  10716. graphic.attr(point.pointAttr[point.state || '']);
  10717. }
  10718. }
  10719. }
  10720. // reconciliation changes in the parallel arrays
  10721. i = inArray(point, data);
  10722. series.xData[i] = point.x;
  10723. series.yData[i] = series.toYData ? series.toYData(point) : point.y;
  10724. series.zData[i] = point.z;
  10725. seriesOptions.data[i] = point.options;
  10726. // redraw
  10727. series.isDirty = series.isDirtyData = true;
  10728. if (!series.fixedBox && series.hasCartesianSeries) { // #1906, #2320
  10729. chart.isDirtyBox = true;
  10730. }
  10731. if (seriesOptions.legendType === 'point') { // #1831, #1885
  10732. chart.legend.destroyItem(point);
  10733. }
  10734. if (redraw) {
  10735. chart.redraw(animation);
  10736. }
  10737. });
  10738. },
  10739. /**
  10740. * Remove a point and optionally redraw the series and if necessary the axes
  10741. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  10742. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  10743. * configuration
  10744. */
  10745. remove: function (redraw, animation) {
  10746. var point = this,
  10747. series = point.series,
  10748. points = series.points,
  10749. chart = series.chart,
  10750. i,
  10751. data = series.data;
  10752. setAnimation(animation, chart);
  10753. redraw = pick(redraw, true);
  10754. // fire the event with a default handler of removing the point
  10755. point.firePointEvent('remove', null, function () {
  10756. // splice all the parallel arrays
  10757. i = inArray(point, data);
  10758. if (data.length === points.length) {
  10759. points.splice(i, 1);
  10760. }
  10761. data.splice(i, 1);
  10762. series.options.data.splice(i, 1);
  10763. series.xData.splice(i, 1);
  10764. series.yData.splice(i, 1);
  10765. series.zData.splice(i, 1);
  10766. point.destroy();
  10767. // redraw
  10768. series.isDirty = true;
  10769. series.isDirtyData = true;
  10770. if (redraw) {
  10771. chart.redraw();
  10772. }
  10773. });
  10774. },
  10775. /**
  10776. * Fire an event on the Point object. Must not be renamed to fireEvent, as this
  10777. * causes a name clash in MooTools
  10778. * @param {String} eventType
  10779. * @param {Object} eventArgs Additional event arguments
  10780. * @param {Function} defaultFunction Default event handler
  10781. */
  10782. firePointEvent: function (eventType, eventArgs, defaultFunction) {
  10783. var point = this,
  10784. series = this.series,
  10785. seriesOptions = series.options;
  10786. // load event handlers on demand to save time on mouseover/out
  10787. if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) {
  10788. this.importEvents();
  10789. }
  10790. // add default handler if in selection mode
  10791. if (eventType === 'click' && seriesOptions.allowPointSelect) {
  10792. defaultFunction = function (event) {
  10793. // Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera
  10794. point.select(null, event.ctrlKey || event.metaKey || event.shiftKey);
  10795. };
  10796. }
  10797. fireEvent(this, eventType, eventArgs, defaultFunction);
  10798. },
  10799. /**
  10800. * Import events from the series' and point's options. Only do it on
  10801. * demand, to save processing time on hovering.
  10802. */
  10803. importEvents: function () {
  10804. if (!this.hasImportedEvents) {
  10805. var point = this,
  10806. options = merge(point.series.options.point, point.options),
  10807. events = options.events,
  10808. eventType;
  10809. point.events = events;
  10810. for (eventType in events) {
  10811. addEvent(point, eventType, events[eventType]);
  10812. }
  10813. this.hasImportedEvents = true;
  10814. }
  10815. },
  10816. /**
  10817. * Set the point's state
  10818. * @param {String} state
  10819. */
  10820. setState: function (state) {
  10821. var point = this,
  10822. plotX = point.plotX,
  10823. plotY = point.plotY,
  10824. series = point.series,
  10825. stateOptions = series.options.states,
  10826. markerOptions = defaultPlotOptions[series.type].marker && series.options.marker,
  10827. normalDisabled = markerOptions && !markerOptions.enabled,
  10828. markerStateOptions = markerOptions && markerOptions.states[state],
  10829. stateDisabled = markerStateOptions && markerStateOptions.enabled === false,
  10830. stateMarkerGraphic = series.stateMarkerGraphic,
  10831. pointMarker = point.marker || {},
  10832. chart = series.chart,
  10833. radius,
  10834. newSymbol,
  10835. pointAttr = point.pointAttr;
  10836. state = state || NORMAL_STATE; // empty string
  10837. if (
  10838. // already has this state
  10839. state === point.state ||
  10840. // selected points don't respond to hover
  10841. (point.selected && state !== SELECT_STATE) ||
  10842. // series' state options is disabled
  10843. (stateOptions[state] && stateOptions[state].enabled === false) ||
  10844. // point marker's state options is disabled
  10845. (state && (stateDisabled || (normalDisabled && !markerStateOptions.enabled)))
  10846. ) {
  10847. return;
  10848. }
  10849. // apply hover styles to the existing point
  10850. if (point.graphic) {
  10851. radius = markerOptions && point.graphic.symbolName && pointAttr[state].r;
  10852. point.graphic.attr(merge(
  10853. pointAttr[state],
  10854. radius ? { // new symbol attributes (#507, #612)
  10855. x: plotX - radius,
  10856. y: plotY - radius,
  10857. width: 2 * radius,
  10858. height: 2 * radius
  10859. } : {}
  10860. ));
  10861. } else {
  10862. // if a graphic is not applied to each point in the normal state, create a shared
  10863. // graphic for the hover state
  10864. if (state && markerStateOptions) {
  10865. radius = markerStateOptions.radius;
  10866. newSymbol = pointMarker.symbol || series.symbol;
  10867. // If the point has another symbol than the previous one, throw away the
  10868. // state marker graphic and force a new one (#1459)
  10869. if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) {
  10870. stateMarkerGraphic = stateMarkerGraphic.destroy();
  10871. }
  10872. // Add a new state marker graphic
  10873. if (!stateMarkerGraphic) {
  10874. series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol(
  10875. newSymbol,
  10876. plotX - radius,
  10877. plotY - radius,
  10878. 2 * radius,
  10879. 2 * radius
  10880. )
  10881. .attr(pointAttr[state])
  10882. .add(series.markerGroup);
  10883. stateMarkerGraphic.currentSymbol = newSymbol;
  10884. // Move the existing graphic
  10885. } else {
  10886. stateMarkerGraphic.attr({ // #1054
  10887. x: plotX - radius,
  10888. y: plotY - radius
  10889. });
  10890. }
  10891. }
  10892. if (stateMarkerGraphic) {
  10893. stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY) ? 'show' : 'hide']();
  10894. }
  10895. }
  10896. point.state = state;
  10897. }
  10898. };
  10899. /**
  10900. * @classDescription The base function which all other series types inherit from. The data in the series is stored
  10901. * in various arrays.
  10902. *
  10903. * - First, series.options.data contains all the original config options for
  10904. * each point whether added by options or methods like series.addPoint.
  10905. * - Next, series.data contains those values converted to points, but in case the series data length
  10906. * exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It
  10907. * only contains the points that have been created on demand.
  10908. * - Then there's series.points that contains all currently visible point objects. In case of cropping,
  10909. * the cropped-away points are not part of this array. The series.points array starts at series.cropStart
  10910. * compared to series.data and series.options.data. If however the series data is grouped, these can't
  10911. * be correlated one to one.
  10912. * - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points.
  10913. * - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points.
  10914. *
  10915. * @param {Object} chart
  10916. * @param {Object} options
  10917. */
  10918. var Series = function () {};
  10919. Series.prototype = {
  10920. isCartesian: true,
  10921. type: 'line',
  10922. pointClass: Point,
  10923. sorted: true, // requires the data to be sorted
  10924. requireSorting: true,
  10925. pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
  10926. stroke: 'lineColor',
  10927. 'stroke-width': 'lineWidth',
  10928. fill: 'fillColor',
  10929. r: 'radius'
  10930. },
  10931. colorCounter: 0,
  10932. init: function (chart, options) {
  10933. var series = this,
  10934. eventType,
  10935. events,
  10936. chartSeries = chart.series;
  10937. series.chart = chart;
  10938. series.options = options = series.setOptions(options); // merge with plotOptions
  10939. series.linkedSeries = [];
  10940. // bind the axes
  10941. series.bindAxes();
  10942. // set some variables
  10943. extend(series, {
  10944. name: options.name,
  10945. state: NORMAL_STATE,
  10946. pointAttr: {},
  10947. visible: options.visible !== false, // true by default
  10948. selected: options.selected === true // false by default
  10949. });
  10950. // special
  10951. if (useCanVG) {
  10952. options.animation = false;
  10953. }
  10954. // register event listeners
  10955. events = options.events;
  10956. for (eventType in events) {
  10957. addEvent(series, eventType, events[eventType]);
  10958. }
  10959. if (
  10960. (events && events.click) ||
  10961. (options.point && options.point.events && options.point.events.click) ||
  10962. options.allowPointSelect
  10963. ) {
  10964. chart.runTrackerClick = true;
  10965. }
  10966. series.getColor();
  10967. series.getSymbol();
  10968. // set the data
  10969. series.setData(options.data, false);
  10970. // Mark cartesian
  10971. if (series.isCartesian) {
  10972. chart.hasCartesianSeries = true;
  10973. }
  10974. // Register it in the chart
  10975. chartSeries.push(series);
  10976. series._i = chartSeries.length - 1;
  10977. // Sort series according to index option (#248, #1123)
  10978. stableSort(chartSeries, function (a, b) {
  10979. return pick(a.options.index, a._i) - pick(b.options.index, a._i);
  10980. });
  10981. each(chartSeries, function (series, i) {
  10982. series.index = i;
  10983. series.name = series.name || 'Series ' + (i + 1);
  10984. });
  10985. },
  10986. /**
  10987. * Set the xAxis and yAxis properties of cartesian series, and register the series
  10988. * in the axis.series array
  10989. */
  10990. bindAxes: function () {
  10991. var series = this,
  10992. seriesOptions = series.options,
  10993. chart = series.chart,
  10994. axisOptions;
  10995. if (series.isCartesian) {
  10996. each(['xAxis', 'yAxis'], function (AXIS) { // repeat for xAxis and yAxis
  10997. each(chart[AXIS], function (axis) { // loop through the chart's axis objects
  10998. axisOptions = axis.options;
  10999. // apply if the series xAxis or yAxis option mathches the number of the
  11000. // axis, or if undefined, use the first axis
  11001. if ((seriesOptions[AXIS] === axisOptions.index) ||
  11002. (seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) ||
  11003. (seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) {
  11004. // register this series in the axis.series lookup
  11005. axis.series.push(series);
  11006. // set this series.xAxis or series.yAxis reference
  11007. series[AXIS] = axis;
  11008. // mark dirty for redraw
  11009. axis.isDirty = true;
  11010. }
  11011. });
  11012. // The series needs an X and an Y axis
  11013. if (!series[AXIS]) {
  11014. error(18, true);
  11015. }
  11016. });
  11017. }
  11018. },
  11019. /**
  11020. * Return an auto incremented x value based on the pointStart and pointInterval options.
  11021. * This is only used if an x value is not given for the point that calls autoIncrement.
  11022. */
  11023. autoIncrement: function () {
  11024. var series = this,
  11025. options = series.options,
  11026. xIncrement = series.xIncrement;
  11027. xIncrement = pick(xIncrement, options.pointStart, 0);
  11028. series.pointInterval = pick(series.pointInterval, options.pointInterval, 1);
  11029. series.xIncrement = xIncrement + series.pointInterval;
  11030. return xIncrement;
  11031. },
  11032. /**
  11033. * Divide the series data into segments divided by null values.
  11034. */
  11035. getSegments: function () {
  11036. var series = this,
  11037. lastNull = -1,
  11038. segments = [],
  11039. i,
  11040. points = series.points,
  11041. pointsLength = points.length;
  11042. if (pointsLength) { // no action required for []
  11043. // if connect nulls, just remove null points
  11044. if (series.options.connectNulls) {
  11045. i = pointsLength;
  11046. while (i--) {
  11047. if (points[i].y === null) {
  11048. points.splice(i, 1);
  11049. }
  11050. }
  11051. if (points.length) {
  11052. segments = [points];
  11053. }
  11054. // else, split on null points
  11055. } else {
  11056. each(points, function (point, i) {
  11057. if (point.y === null) {
  11058. if (i > lastNull + 1) {
  11059. segments.push(points.slice(lastNull + 1, i));
  11060. }
  11061. lastNull = i;
  11062. } else if (i === pointsLength - 1) { // last value
  11063. segments.push(points.slice(lastNull + 1, i + 1));
  11064. }
  11065. });
  11066. }
  11067. }
  11068. // register it
  11069. series.segments = segments;
  11070. },
  11071. /**
  11072. * Set the series options by merging from the options tree
  11073. * @param {Object} itemOptions
  11074. */
  11075. setOptions: function (itemOptions) {
  11076. var chart = this.chart,
  11077. chartOptions = chart.options,
  11078. plotOptions = chartOptions.plotOptions,
  11079. typeOptions = plotOptions[this.type],
  11080. options;
  11081. this.userOptions = itemOptions;
  11082. options = merge(
  11083. typeOptions,
  11084. plotOptions.series,
  11085. itemOptions
  11086. );
  11087. // the tooltip options are merged between global and series specific options
  11088. this.tooltipOptions = merge(chartOptions.tooltip, options.tooltip);
  11089. // Delte marker object if not allowed (#1125)
  11090. if (typeOptions.marker === null) {
  11091. delete options.marker;
  11092. }
  11093. return options;
  11094. },
  11095. /**
  11096. * Get the series' color
  11097. */
  11098. getColor: function () {
  11099. var options = this.options,
  11100. userOptions = this.userOptions,
  11101. defaultColors = this.chart.options.colors,
  11102. counters = this.chart.counters,
  11103. color,
  11104. colorIndex;
  11105. color = options.color || defaultPlotOptions[this.type].color;
  11106. if (!color && !options.colorByPoint) {
  11107. if (defined(userOptions._colorIndex)) { // after Series.update()
  11108. colorIndex = userOptions._colorIndex;
  11109. } else {
  11110. userOptions._colorIndex = counters.color;
  11111. colorIndex = counters.color++;
  11112. }
  11113. color = defaultColors[colorIndex];
  11114. }
  11115. this.color = color;
  11116. counters.wrapColor(defaultColors.length);
  11117. },
  11118. /**
  11119. * Get the series' symbol
  11120. */
  11121. getSymbol: function () {
  11122. var series = this,
  11123. userOptions = series.userOptions,
  11124. seriesMarkerOption = series.options.marker,
  11125. chart = series.chart,
  11126. defaultSymbols = chart.options.symbols,
  11127. counters = chart.counters,
  11128. symbolIndex;
  11129. series.symbol = seriesMarkerOption.symbol;
  11130. if (!series.symbol) {
  11131. if (defined(userOptions._symbolIndex)) { // after Series.update()
  11132. symbolIndex = userOptions._symbolIndex;
  11133. } else {
  11134. userOptions._symbolIndex = counters.symbol;
  11135. symbolIndex = counters.symbol++;
  11136. }
  11137. series.symbol = defaultSymbols[symbolIndex];
  11138. }
  11139. // don't substract radius in image symbols (#604)
  11140. if (/^url/.test(series.symbol)) {
  11141. seriesMarkerOption.radius = 0;
  11142. }
  11143. counters.wrapSymbol(defaultSymbols.length);
  11144. },
  11145. /**
  11146. * Get the series' symbol in the legend. This method should be overridable to create custom
  11147. * symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols.
  11148. *
  11149. * @param {Object} legend The legend object
  11150. */
  11151. drawLegendSymbol: function (legend) {
  11152. var options = this.options,
  11153. markerOptions = options.marker,
  11154. radius,
  11155. legendOptions = legend.options,
  11156. legendSymbol,
  11157. symbolWidth = legendOptions.symbolWidth,
  11158. renderer = this.chart.renderer,
  11159. legendItemGroup = this.legendGroup,
  11160. verticalCenter = legend.baseline - mathRound(renderer.fontMetrics(legendOptions.itemStyle.fontSize).b * 0.3),
  11161. attr;
  11162. // Draw the line
  11163. if (options.lineWidth) {
  11164. attr = {
  11165. 'stroke-width': options.lineWidth
  11166. };
  11167. if (options.dashStyle) {
  11168. attr.dashstyle = options.dashStyle;
  11169. }
  11170. this.legendLine = renderer.path([
  11171. M,
  11172. 0,
  11173. verticalCenter,
  11174. L,
  11175. symbolWidth,
  11176. verticalCenter
  11177. ])
  11178. .attr(attr)
  11179. .add(legendItemGroup);
  11180. }
  11181. // Draw the marker
  11182. if (markerOptions && markerOptions.enabled) {
  11183. radius = markerOptions.radius;
  11184. this.legendSymbol = legendSymbol = renderer.symbol(
  11185. this.symbol,
  11186. (symbolWidth / 2) - radius,
  11187. verticalCenter - radius,
  11188. 2 * radius,
  11189. 2 * radius
  11190. )
  11191. .add(legendItemGroup);
  11192. legendSymbol.isMarker = true;
  11193. }
  11194. },
  11195. /**
  11196. * Add a point dynamically after chart load time
  11197. * @param {Object} options Point options as given in series.data
  11198. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  11199. * @param {Boolean} shift If shift is true, a point is shifted off the start
  11200. * of the series as one is appended to the end.
  11201. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  11202. * configuration
  11203. */
  11204. addPoint: function (options, redraw, shift, animation) {
  11205. var series = this,
  11206. seriesOptions = series.options,
  11207. data = series.data,
  11208. graph = series.graph,
  11209. area = series.area,
  11210. chart = series.chart,
  11211. xData = series.xData,
  11212. yData = series.yData,
  11213. zData = series.zData,
  11214. names = series.names,
  11215. currentShift = (graph && graph.shift) || 0,
  11216. dataOptions = seriesOptions.data,
  11217. point,
  11218. isInTheMiddle,
  11219. x,
  11220. i;
  11221. setAnimation(animation, chart);
  11222. // Make graph animate sideways
  11223. if (shift) {
  11224. each([graph, area, series.graphNeg, series.areaNeg], function (shape) {
  11225. if (shape) {
  11226. shape.shift = currentShift + 1;
  11227. }
  11228. });
  11229. }
  11230. if (area) {
  11231. area.isArea = true; // needed in animation, both with and without shift
  11232. }
  11233. // Optional redraw, defaults to true
  11234. redraw = pick(redraw, true);
  11235. // Get options and push the point to xData, yData and series.options. In series.generatePoints
  11236. // the Point instance will be created on demand and pushed to the series.data array.
  11237. point = { series: series };
  11238. series.pointClass.prototype.applyOptions.apply(point, [options]);
  11239. x = point.x;
  11240. // Get the insertion point
  11241. i = xData.length;
  11242. if (series.requireSorting && x < xData[i - 1]) {
  11243. isInTheMiddle = true;
  11244. while (i && xData[i - 1] > x) {
  11245. i--;
  11246. }
  11247. }
  11248. xData.splice(i, 0, x);
  11249. yData.splice(i, 0, series.toYData ? series.toYData(point) : point.y);
  11250. zData.splice(i, 0, point.z);
  11251. if (names) {
  11252. names[x] = point.name;
  11253. }
  11254. dataOptions.splice(i, 0, options);
  11255. if (isInTheMiddle) {
  11256. series.data.splice(i, 0, null);
  11257. series.processData();
  11258. }
  11259. // Generate points to be added to the legend (#1329)
  11260. if (seriesOptions.legendType === 'point') {
  11261. series.generatePoints();
  11262. }
  11263. // Shift the first point off the parallel arrays
  11264. // todo: consider series.removePoint(i) method
  11265. if (shift) {
  11266. if (data[0] && data[0].remove) {
  11267. data[0].remove(false);
  11268. } else {
  11269. data.shift();
  11270. xData.shift();
  11271. yData.shift();
  11272. zData.shift();
  11273. dataOptions.shift();
  11274. }
  11275. }
  11276. // redraw
  11277. series.isDirty = true;
  11278. series.isDirtyData = true;
  11279. if (redraw) {
  11280. series.getAttribs(); // #1937
  11281. chart.redraw();
  11282. }
  11283. },
  11284. /**
  11285. * Replace the series data with a new set of data
  11286. * @param {Object} data
  11287. * @param {Object} redraw
  11288. */
  11289. setData: function (data, redraw) {
  11290. var series = this,
  11291. oldData = series.points,
  11292. options = series.options,
  11293. chart = series.chart,
  11294. firstPoint = null,
  11295. xAxis = series.xAxis,
  11296. names = xAxis && xAxis.categories && !xAxis.categories.length ? [] : null,
  11297. i;
  11298. // reset properties
  11299. series.xIncrement = null;
  11300. series.pointRange = xAxis && xAxis.categories ? 1 : options.pointRange;
  11301. series.colorCounter = 0; // for series with colorByPoint (#1547)
  11302. // parallel arrays
  11303. var xData = [],
  11304. yData = [],
  11305. zData = [],
  11306. dataLength = data ? data.length : [],
  11307. turboThreshold = pick(options.turboThreshold, 1000),
  11308. pt,
  11309. pointArrayMap = series.pointArrayMap,
  11310. valueCount = pointArrayMap && pointArrayMap.length,
  11311. hasToYData = !!series.toYData;
  11312. // In turbo mode, only one- or twodimensional arrays of numbers are allowed. The
  11313. // first value is tested, and we assume that all the rest are defined the same
  11314. // way. Although the 'for' loops are similar, they are repeated inside each
  11315. // if-else conditional for max performance.
  11316. if (turboThreshold && dataLength > turboThreshold) {
  11317. // find the first non-null point
  11318. i = 0;
  11319. while (firstPoint === null && i < dataLength) {
  11320. firstPoint = data[i];
  11321. i++;
  11322. }
  11323. if (isNumber(firstPoint)) { // assume all points are numbers
  11324. var x = pick(options.pointStart, 0),
  11325. pointInterval = pick(options.pointInterval, 1);
  11326. for (i = 0; i < dataLength; i++) {
  11327. xData[i] = x;
  11328. yData[i] = data[i];
  11329. x += pointInterval;
  11330. }
  11331. series.xIncrement = x;
  11332. } else if (isArray(firstPoint)) { // assume all points are arrays
  11333. if (valueCount) { // [x, low, high] or [x, o, h, l, c]
  11334. for (i = 0; i < dataLength; i++) {
  11335. pt = data[i];
  11336. xData[i] = pt[0];
  11337. yData[i] = pt.slice(1, valueCount + 1);
  11338. }
  11339. } else { // [x, y]
  11340. for (i = 0; i < dataLength; i++) {
  11341. pt = data[i];
  11342. xData[i] = pt[0];
  11343. yData[i] = pt[1];
  11344. }
  11345. }
  11346. } else {
  11347. error(12); // Highcharts expects configs to be numbers or arrays in turbo mode
  11348. }
  11349. } else {
  11350. for (i = 0; i < dataLength; i++) {
  11351. if (data[i] !== UNDEFINED) { // stray commas in oldIE
  11352. pt = { series: series };
  11353. series.pointClass.prototype.applyOptions.apply(pt, [data[i]]);
  11354. xData[i] = pt.x;
  11355. yData[i] = hasToYData ? series.toYData(pt) : pt.y;
  11356. zData[i] = pt.z;
  11357. if (names && pt.name) {
  11358. names[pt.x] = pt.name; // #2046
  11359. }
  11360. }
  11361. }
  11362. }
  11363. // Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON
  11364. if (isString(yData[0])) {
  11365. error(14, true);
  11366. }
  11367. series.data = [];
  11368. series.options.data = data;
  11369. series.xData = xData;
  11370. series.yData = yData;
  11371. series.zData = zData;
  11372. series.names = names;
  11373. // destroy old points
  11374. i = (oldData && oldData.length) || 0;
  11375. while (i--) {
  11376. if (oldData[i] && oldData[i].destroy) {
  11377. oldData[i].destroy();
  11378. }
  11379. }
  11380. // reset minRange (#878)
  11381. if (xAxis) {
  11382. xAxis.minRange = xAxis.userMinRange;
  11383. }
  11384. // redraw
  11385. series.isDirty = series.isDirtyData = chart.isDirtyBox = true;
  11386. if (pick(redraw, true)) {
  11387. chart.redraw(false);
  11388. }
  11389. },
  11390. /**
  11391. * Remove a series and optionally redraw the chart
  11392. *
  11393. * @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
  11394. * @param {Boolean|Object} animation Whether to apply animation, and optionally animation
  11395. * configuration
  11396. */
  11397. remove: function (redraw, animation) {
  11398. var series = this,
  11399. chart = series.chart;
  11400. redraw = pick(redraw, true);
  11401. if (!series.isRemoving) { /* prevent triggering native event in jQuery
  11402. (calling the remove function from the remove event) */
  11403. series.isRemoving = true;
  11404. // fire the event with a default handler of removing the point
  11405. fireEvent(series, 'remove', null, function () {
  11406. // destroy elements
  11407. series.destroy();
  11408. // redraw
  11409. chart.isDirtyLegend = chart.isDirtyBox = true;
  11410. chart.linkSeries();
  11411. if (redraw) {
  11412. chart.redraw(animation);
  11413. }
  11414. });
  11415. }
  11416. series.isRemoving = false;
  11417. },
  11418. /**
  11419. * Process the data by cropping away unused data points if the series is longer
  11420. * than the crop threshold. This saves computing time for lage series.
  11421. */
  11422. processData: function (force) {
  11423. var series = this,
  11424. processedXData = series.xData, // copied during slice operation below
  11425. processedYData = series.yData,
  11426. dataLength = processedXData.length,
  11427. croppedData,
  11428. cropStart = 0,
  11429. cropped,
  11430. distance,
  11431. closestPointRange,
  11432. xAxis = series.xAxis,
  11433. i, // loop variable
  11434. options = series.options,
  11435. cropThreshold = options.cropThreshold,
  11436. isCartesian = series.isCartesian;
  11437. // If the series data or axes haven't changed, don't go through this. Return false to pass
  11438. // the message on to override methods like in data grouping.
  11439. if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) {
  11440. return false;
  11441. }
  11442. // optionally filter out points outside the plot area
  11443. if (isCartesian && series.sorted && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) {
  11444. var min = xAxis.min,
  11445. max = xAxis.max;
  11446. // it's outside current extremes
  11447. if (processedXData[dataLength - 1] < min || processedXData[0] > max) {
  11448. processedXData = [];
  11449. processedYData = [];
  11450. // only crop if it's actually spilling out
  11451. } else if (processedXData[0] < min || processedXData[dataLength - 1] > max) {
  11452. croppedData = this.cropData(series.xData, series.yData, min, max);
  11453. processedXData = croppedData.xData;
  11454. processedYData = croppedData.yData;
  11455. cropStart = croppedData.start;
  11456. cropped = true;
  11457. }
  11458. }
  11459. // Find the closest distance between processed points
  11460. for (i = processedXData.length - 1; i >= 0; i--) {
  11461. distance = processedXData[i] - processedXData[i - 1];
  11462. if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) {
  11463. closestPointRange = distance;
  11464. // Unsorted data is not supported by the line tooltip, as well as data grouping and
  11465. // navigation in Stock charts (#725) and width calculation of columns (#1900)
  11466. } else if (distance < 0 && series.requireSorting) {
  11467. error(15);
  11468. }
  11469. }
  11470. // Record the properties
  11471. series.cropped = cropped; // undefined or true
  11472. series.cropStart = cropStart;
  11473. series.processedXData = processedXData;
  11474. series.processedYData = processedYData;
  11475. if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC
  11476. series.pointRange = closestPointRange || 1;
  11477. }
  11478. series.closestPointRange = closestPointRange;
  11479. },
  11480. /**
  11481. * Iterate over xData and crop values between min and max. Returns object containing crop start/end
  11482. * cropped xData with corresponding part of yData, dataMin and dataMax within the cropped range
  11483. */
  11484. cropData: function (xData, yData, min, max) {
  11485. var dataLength = xData.length,
  11486. cropStart = 0,
  11487. cropEnd = dataLength,
  11488. cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside
  11489. i;
  11490. // iterate up to find slice start
  11491. for (i = 0; i < dataLength; i++) {
  11492. if (xData[i] >= min) {
  11493. cropStart = mathMax(0, i - cropShoulder);
  11494. break;
  11495. }
  11496. }
  11497. // proceed to find slice end
  11498. for (; i < dataLength; i++) {
  11499. if (xData[i] > max) {
  11500. cropEnd = i + cropShoulder;
  11501. break;
  11502. }
  11503. }
  11504. return {
  11505. xData: xData.slice(cropStart, cropEnd),
  11506. yData: yData.slice(cropStart, cropEnd),
  11507. start: cropStart,
  11508. end: cropEnd
  11509. };
  11510. },
  11511. /**
  11512. * Generate the data point after the data has been processed by cropping away
  11513. * unused points and optionally grouped in Highcharts Stock.
  11514. */
  11515. generatePoints: function () {
  11516. var series = this,
  11517. options = series.options,
  11518. dataOptions = options.data,
  11519. data = series.data,
  11520. dataLength,
  11521. processedXData = series.processedXData,
  11522. processedYData = series.processedYData,
  11523. pointClass = series.pointClass,
  11524. processedDataLength = processedXData.length,
  11525. cropStart = series.cropStart || 0,
  11526. cursor,
  11527. hasGroupedData = series.hasGroupedData,
  11528. point,
  11529. points = [],
  11530. i;
  11531. if (!data && !hasGroupedData) {
  11532. var arr = [];
  11533. arr.length = dataOptions.length;
  11534. data = series.data = arr;
  11535. }
  11536. for (i = 0; i < processedDataLength; i++) {
  11537. cursor = cropStart + i;
  11538. if (!hasGroupedData) {
  11539. if (data[cursor]) {
  11540. point = data[cursor];
  11541. } else if (dataOptions[cursor] !== UNDEFINED) { // #970
  11542. data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]);
  11543. }
  11544. points[i] = point;
  11545. } else {
  11546. // splat the y data in case of ohlc data array
  11547. points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i])));
  11548. }
  11549. }
  11550. // Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when
  11551. // swithching view from non-grouped data to grouped data (#637)
  11552. if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) {
  11553. for (i = 0; i < dataLength; i++) {
  11554. if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points
  11555. i += processedDataLength;
  11556. }
  11557. if (data[i]) {
  11558. data[i].destroyElements();
  11559. data[i].plotX = UNDEFINED; // #1003
  11560. }
  11561. }
  11562. }
  11563. series.data = data;
  11564. series.points = points;
  11565. },
  11566. /**
  11567. * Adds series' points value to corresponding stack
  11568. */
  11569. setStackedPoints: function () {
  11570. if (!this.options.stacking || (this.visible !== true && this.chart.options.chart.ignoreHiddenSeries !== false)) {
  11571. return;
  11572. }
  11573. var series = this,
  11574. xData = series.processedXData,
  11575. yData = series.processedYData,
  11576. stackedYData = [],
  11577. yDataLength = yData.length,
  11578. seriesOptions = series.options,
  11579. threshold = seriesOptions.threshold,
  11580. stackOption = seriesOptions.stack,
  11581. stacking = seriesOptions.stacking,
  11582. stackKey = series.stackKey,
  11583. negKey = '-' + stackKey,
  11584. negStacks = series.negStacks,
  11585. yAxis = series.yAxis,
  11586. stacks = yAxis.stacks,
  11587. oldStacks = yAxis.oldStacks,
  11588. isNegative,
  11589. stack,
  11590. other,
  11591. key,
  11592. i,
  11593. x,
  11594. y;
  11595. // loop over the non-null y values and read them into a local array
  11596. for (i = 0; i < yDataLength; i++) {
  11597. x = xData[i];
  11598. y = yData[i];
  11599. // Read stacked values into a stack based on the x value,
  11600. // the sign of y and the stack key. Stacking is also handled for null values (#739)
  11601. isNegative = negStacks && y < threshold;
  11602. key = isNegative ? negKey : stackKey;
  11603. // Create empty object for this stack if it doesn't exist yet
  11604. if (!stacks[key]) {
  11605. stacks[key] = {};
  11606. }
  11607. // Initialize StackItem for this x
  11608. if (!stacks[key][x]) {
  11609. if (oldStacks[key] && oldStacks[key][x]) {
  11610. stacks[key][x] = oldStacks[key][x];
  11611. stacks[key][x].total = null;
  11612. } else {
  11613. stacks[key][x] = new StackItem(yAxis, yAxis.options.stackLabels, isNegative, x, stackOption, stacking);
  11614. }
  11615. }
  11616. // If the StackItem doesn't exist, create it first
  11617. stack = stacks[key][x];
  11618. stack.points[series.index] = [stack.cum || 0];
  11619. // Add value to the stack total
  11620. if (stacking === 'percent') {
  11621. // Percent stacked column, totals are the same for the positive and negative stacks
  11622. other = isNegative ? stackKey : negKey;
  11623. if (negStacks && stacks[other] && stacks[other][x]) {
  11624. other = stacks[other][x];
  11625. stack.total = other.total = mathMax(other.total, stack.total) + mathAbs(y) || 0;
  11626. // Percent stacked areas
  11627. } else {
  11628. stack.total += mathAbs(y) || 0;
  11629. }
  11630. } else {
  11631. stack.total += y || 0;
  11632. }
  11633. stack.cum = (stack.cum || 0) + (y || 0);
  11634. stack.points[series.index].push(stack.cum);
  11635. stackedYData[i] = stack.cum;
  11636. }
  11637. if (stacking === 'percent') {
  11638. yAxis.usePercentage = true;
  11639. }
  11640. this.stackedYData = stackedYData; // To be used in getExtremes
  11641. // Reset old stacks
  11642. yAxis.oldStacks = {};
  11643. },
  11644. /**
  11645. * Iterate over all stacks and compute the absolute values to percent
  11646. */
  11647. setPercentStacks: function () {
  11648. var series = this,
  11649. stackKey = series.stackKey,
  11650. stacks = series.yAxis.stacks;
  11651. each([stackKey, '-' + stackKey], function (key) {
  11652. var i = series.xData.length,
  11653. x,
  11654. stack,
  11655. pointExtremes,
  11656. totalFactor;
  11657. while (i--) {
  11658. x = series.xData[i];
  11659. stack = stacks[key] && stacks[key][x];
  11660. pointExtremes = stack && stack.points[series.index];
  11661. if (pointExtremes) {
  11662. totalFactor = stack.total ? 100 / stack.total : 0;
  11663. pointExtremes[0] = correctFloat(pointExtremes[0] * totalFactor); // Y bottom value
  11664. pointExtremes[1] = correctFloat(pointExtremes[1] * totalFactor); // Y value
  11665. series.stackedYData[i] = pointExtremes[1];
  11666. }
  11667. }
  11668. });
  11669. },
  11670. /**
  11671. * Calculate Y extremes for visible data
  11672. */
  11673. getExtremes: function () {
  11674. var xAxis = this.xAxis,
  11675. yAxis = this.yAxis,
  11676. xData = this.processedXData,
  11677. yData = this.stackedYData || this.processedYData,
  11678. yDataLength = yData.length,
  11679. activeYData = [],
  11680. activeCounter = 0,
  11681. xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis
  11682. xMin = xExtremes.min,
  11683. xMax = xExtremes.max,
  11684. validValue,
  11685. withinRange,
  11686. dataMin,
  11687. dataMax,
  11688. x,
  11689. y,
  11690. i,
  11691. j;
  11692. for (i = 0; i < yDataLength; i++) {
  11693. x = xData[i];
  11694. y = yData[i];
  11695. // For points within the visible range, including the first point outside the
  11696. // visible range, consider y extremes
  11697. validValue = y !== null && y !== UNDEFINED && (!yAxis.isLog || (y.length || y > 0));
  11698. withinRange = this.getExtremesFromAll || this.cropped || ((xData[i + 1] || x) >= xMin &&
  11699. (xData[i - 1] || x) <= xMax);
  11700. if (validValue && withinRange) {
  11701. j = y.length;
  11702. if (j) { // array, like ohlc or range data
  11703. while (j--) {
  11704. if (y[j] !== null) {
  11705. activeYData[activeCounter++] = y[j];
  11706. }
  11707. }
  11708. } else {
  11709. activeYData[activeCounter++] = y;
  11710. }
  11711. }
  11712. }
  11713. this.dataMin = pick(dataMin, arrayMin(activeYData));
  11714. this.dataMax = pick(dataMax, arrayMax(activeYData));
  11715. },
  11716. /**
  11717. * Translate data points from raw data values to chart specific positioning data
  11718. * needed later in drawPoints, drawGraph and drawTracker.
  11719. */
  11720. translate: function () {
  11721. if (!this.processedXData) { // hidden series
  11722. this.processData();
  11723. }
  11724. this.generatePoints();
  11725. var series = this,
  11726. options = series.options,
  11727. stacking = options.stacking,
  11728. xAxis = series.xAxis,
  11729. categories = xAxis.categories,
  11730. yAxis = series.yAxis,
  11731. points = series.points,
  11732. dataLength = points.length,
  11733. hasModifyValue = !!series.modifyValue,
  11734. i,
  11735. pointPlacement = options.pointPlacement,
  11736. dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement),
  11737. threshold = options.threshold;
  11738. // Translate each point
  11739. for (i = 0; i < dataLength; i++) {
  11740. var point = points[i],
  11741. xValue = point.x,
  11742. yValue = point.y,
  11743. yBottom = point.low,
  11744. stack = yAxis.stacks[(series.negStacks && yValue < threshold ? '-' : '') + series.stackKey],
  11745. pointStack,
  11746. stackValues;
  11747. // Discard disallowed y values for log axes
  11748. if (yAxis.isLog && yValue <= 0) {
  11749. point.y = yValue = null;
  11750. }
  11751. // Get the plotX translation
  11752. point.plotX = xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags'); // Math.round fixes #591
  11753. // Calculate the bottom y value for stacked series
  11754. if (stacking && series.visible && stack && stack[xValue]) {
  11755. pointStack = stack[xValue];
  11756. stackValues = pointStack.points[series.index];
  11757. yBottom = stackValues[0];
  11758. yValue = stackValues[1];
  11759. if (yBottom === 0) {
  11760. yBottom = pick(threshold, yAxis.min);
  11761. }
  11762. if (yAxis.isLog && yBottom <= 0) { // #1200, #1232
  11763. yBottom = null;
  11764. }
  11765. point.percentage = stacking === 'percent' && yValue;
  11766. point.total = point.stackTotal = pointStack.total;
  11767. point.stackY = yValue;
  11768. // Place the stack label
  11769. pointStack.setOffset(series.pointXOffset || 0, series.barW || 0);
  11770. }
  11771. // Set translated yBottom or remove it
  11772. point.yBottom = defined(yBottom) ?
  11773. yAxis.translate(yBottom, 0, 1, 0, 1) :
  11774. null;
  11775. // general hook, used for Highstock compare mode
  11776. if (hasModifyValue) {
  11777. yValue = series.modifyValue(yValue, point);
  11778. }
  11779. // Set the the plotY value, reset it for redraws
  11780. point.plotY = (typeof yValue === 'number' && yValue !== Infinity) ?
  11781. //mathRound(yAxis.translate(yValue, 0, 1, 0, 1) * 10) / 10 : // Math.round fixes #591
  11782. yAxis.translate(yValue, 0, 1, 0, 1) :
  11783. UNDEFINED;
  11784. // Set client related positions for mouse tracking
  11785. point.clientX = dynamicallyPlaced ? xAxis.translate(xValue, 0, 0, 0, 1) : point.plotX; // #1514
  11786. point.negative = point.y < (threshold || 0);
  11787. // some API data
  11788. point.category = categories && categories[point.x] !== UNDEFINED ?
  11789. categories[point.x] : point.x;
  11790. }
  11791. // now that we have the cropped data, build the segments
  11792. series.getSegments();
  11793. },
  11794. /**
  11795. * Memoize tooltip texts and positions
  11796. */
  11797. setTooltipPoints: function (renew) {
  11798. var series = this,
  11799. points = [],
  11800. pointsLength,
  11801. low,
  11802. high,
  11803. xAxis = series.xAxis,
  11804. xExtremes = xAxis && xAxis.getExtremes(),
  11805. axisLength = xAxis ? (xAxis.tooltipLen || xAxis.len) : series.chart.plotSizeX, // tooltipLen and tooltipPosName used in polar
  11806. point,
  11807. pointX,
  11808. nextPoint,
  11809. i,
  11810. tooltipPoints = []; // a lookup array for each pixel in the x dimension
  11811. // don't waste resources if tracker is disabled
  11812. if (series.options.enableMouseTracking === false) {
  11813. return;
  11814. }
  11815. // renew
  11816. if (renew) {
  11817. series.tooltipPoints = null;
  11818. }
  11819. // concat segments to overcome null values
  11820. each(series.segments || series.points, function (segment) {
  11821. points = points.concat(segment);
  11822. });
  11823. // Reverse the points in case the X axis is reversed
  11824. if (xAxis && xAxis.reversed) {
  11825. points = points.reverse();
  11826. }
  11827. // Polar needs additional shaping
  11828. if (series.orderTooltipPoints) {
  11829. series.orderTooltipPoints(points);
  11830. }
  11831. // Assign each pixel position to the nearest point
  11832. pointsLength = points.length;
  11833. for (i = 0; i < pointsLength; i++) {
  11834. point = points[i];
  11835. pointX = point.x;
  11836. if (pointX >= xExtremes.min && pointX <= xExtremes.max) { // #1149
  11837. nextPoint = points[i + 1];
  11838. // Set this range's low to the last range's high plus one
  11839. low = high === UNDEFINED ? 0 : high + 1;
  11840. // Now find the new high
  11841. high = points[i + 1] ?
  11842. mathMin(mathMax(0, mathFloor( // #2070
  11843. (point.clientX + (nextPoint ? (nextPoint.wrappedClientX || nextPoint.clientX) : axisLength)) / 2
  11844. )), axisLength) :
  11845. axisLength;
  11846. while (low >= 0 && low <= high) {
  11847. tooltipPoints[low++] = point;
  11848. }
  11849. }
  11850. }
  11851. series.tooltipPoints = tooltipPoints;
  11852. },
  11853. /**
  11854. * Format the header of the tooltip
  11855. */
  11856. tooltipHeaderFormatter: function (point) {
  11857. var series = this,
  11858. tooltipOptions = series.tooltipOptions,
  11859. xDateFormat = tooltipOptions.xDateFormat,
  11860. dateTimeLabelFormats = tooltipOptions.dateTimeLabelFormats,
  11861. xAxis = series.xAxis,
  11862. isDateTime = xAxis && xAxis.options.type === 'datetime',
  11863. headerFormat = tooltipOptions.headerFormat,
  11864. closestPointRange = xAxis && xAxis.closestPointRange,
  11865. n;
  11866. // Guess the best date format based on the closest point distance (#568)
  11867. if (isDateTime && !xDateFormat) {
  11868. if (closestPointRange) {
  11869. for (n in timeUnits) {
  11870. if (timeUnits[n] >= closestPointRange) {
  11871. xDateFormat = dateTimeLabelFormats[n];
  11872. break;
  11873. }
  11874. }
  11875. } else {
  11876. xDateFormat = dateTimeLabelFormats.day;
  11877. }
  11878. }
  11879. // Insert the header date format if any
  11880. if (isDateTime && xDateFormat && isNumber(point.key)) {
  11881. headerFormat = headerFormat.replace('{point.key}', '{point.key:' + xDateFormat + '}');
  11882. }
  11883. return format(headerFormat, {
  11884. point: point,
  11885. series: series
  11886. });
  11887. },
  11888. /**
  11889. * Series mouse over handler
  11890. */
  11891. onMouseOver: function () {
  11892. var series = this,
  11893. chart = series.chart,
  11894. hoverSeries = chart.hoverSeries;
  11895. // set normal state to previous series
  11896. if (hoverSeries && hoverSeries !== series) {
  11897. hoverSeries.onMouseOut();
  11898. }
  11899. // trigger the event, but to save processing time,
  11900. // only if defined
  11901. if (series.options.events.mouseOver) {
  11902. fireEvent(series, 'mouseOver');
  11903. }
  11904. // hover this
  11905. series.setState(HOVER_STATE);
  11906. chart.hoverSeries = series;
  11907. },
  11908. /**
  11909. * Series mouse out handler
  11910. */
  11911. onMouseOut: function () {
  11912. // trigger the event only if listeners exist
  11913. var series = this,
  11914. options = series.options,
  11915. chart = series.chart,
  11916. tooltip = chart.tooltip,
  11917. hoverPoint = chart.hoverPoint;
  11918. // trigger mouse out on the point, which must be in this series
  11919. if (hoverPoint) {
  11920. hoverPoint.onMouseOut();
  11921. }
  11922. // fire the mouse out event
  11923. if (series && options.events.mouseOut) {
  11924. fireEvent(series, 'mouseOut');
  11925. }
  11926. // hide the tooltip
  11927. if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) {
  11928. tooltip.hide();
  11929. }
  11930. // set normal state
  11931. series.setState();
  11932. chart.hoverSeries = null;
  11933. },
  11934. /**
  11935. * Animate in the series
  11936. */
  11937. animate: function (init) {
  11938. var series = this,
  11939. chart = series.chart,
  11940. renderer = chart.renderer,
  11941. clipRect,
  11942. markerClipRect,
  11943. animation = series.options.animation,
  11944. clipBox = chart.clipBox,
  11945. inverted = chart.inverted,
  11946. sharedClipKey;
  11947. // Animation option is set to true
  11948. if (animation && !isObject(animation)) {
  11949. animation = defaultPlotOptions[series.type].animation;
  11950. }
  11951. sharedClipKey = '_sharedClip' + animation.duration + animation.easing;
  11952. // Initialize the animation. Set up the clipping rectangle.
  11953. if (init) {
  11954. // If a clipping rectangle with the same properties is currently present in the chart, use that.
  11955. clipRect = chart[sharedClipKey];
  11956. markerClipRect = chart[sharedClipKey + 'm'];
  11957. if (!clipRect) {
  11958. chart[sharedClipKey] = clipRect = renderer.clipRect(
  11959. extend(clipBox, { width: 0 })
  11960. );
  11961. chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect(
  11962. -99, // include the width of the first marker
  11963. inverted ? -chart.plotLeft : -chart.plotTop,
  11964. 99,
  11965. inverted ? chart.chartWidth : chart.chartHeight
  11966. );
  11967. }
  11968. series.group.clip(clipRect);
  11969. series.markerGroup.clip(markerClipRect);
  11970. series.sharedClipKey = sharedClipKey;
  11971. // Run the animation
  11972. } else {
  11973. clipRect = chart[sharedClipKey];
  11974. if (clipRect) {
  11975. clipRect.animate({
  11976. width: chart.plotSizeX
  11977. }, animation);
  11978. chart[sharedClipKey + 'm'].animate({
  11979. width: chart.plotSizeX + 99
  11980. }, animation);
  11981. }
  11982. // Delete this function to allow it only once
  11983. series.animate = null;
  11984. // Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option
  11985. // which should be available to the user).
  11986. series.animationTimeout = setTimeout(function () {
  11987. series.afterAnimate();
  11988. }, animation.duration);
  11989. }
  11990. },
  11991. /**
  11992. * This runs after animation to land on the final plot clipping
  11993. */
  11994. afterAnimate: function () {
  11995. var chart = this.chart,
  11996. sharedClipKey = this.sharedClipKey,
  11997. group = this.group;
  11998. if (group && this.options.clip !== false) {
  11999. group.clip(chart.clipRect);
  12000. this.markerGroup.clip(); // no clip
  12001. }
  12002. // Remove the shared clipping rectancgle when all series are shown
  12003. setTimeout(function () {
  12004. if (sharedClipKey && chart[sharedClipKey]) {
  12005. chart[sharedClipKey] = chart[sharedClipKey].destroy();
  12006. chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy();
  12007. }
  12008. }, 100);
  12009. },
  12010. /**
  12011. * Draw the markers
  12012. */
  12013. drawPoints: function () {
  12014. var series = this,
  12015. pointAttr,
  12016. points = series.points,
  12017. chart = series.chart,
  12018. plotX,
  12019. plotY,
  12020. i,
  12021. point,
  12022. radius,
  12023. symbol,
  12024. isImage,
  12025. graphic,
  12026. options = series.options,
  12027. seriesMarkerOptions = options.marker,
  12028. pointMarkerOptions,
  12029. enabled,
  12030. isInside,
  12031. markerGroup = series.markerGroup;
  12032. if (seriesMarkerOptions.enabled || series._hasPointMarkers) {
  12033. i = points.length;
  12034. while (i--) {
  12035. point = points[i];
  12036. plotX = mathFloor(point.plotX); // #1843
  12037. plotY = point.plotY;
  12038. graphic = point.graphic;
  12039. pointMarkerOptions = point.marker || {};
  12040. enabled = (seriesMarkerOptions.enabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled;
  12041. isInside = chart.isInsidePlot(mathRound(plotX), plotY, chart.inverted); // #1858
  12042. // only draw the point if y is defined
  12043. if (enabled && plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) {
  12044. // shortcuts
  12045. pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE];
  12046. radius = pointAttr.r;
  12047. symbol = pick(pointMarkerOptions.symbol, series.symbol);
  12048. isImage = symbol.indexOf('url') === 0;
  12049. if (graphic) { // update
  12050. graphic
  12051. .attr({ // Since the marker group isn't clipped, each individual marker must be toggled
  12052. visibility: isInside ? (hasSVG ? 'inherit' : VISIBLE) : HIDDEN
  12053. })
  12054. .animate(extend({
  12055. x: plotX - radius,
  12056. y: plotY - radius
  12057. }, graphic.symbolName ? { // don't apply to image symbols #507
  12058. width: 2 * radius,
  12059. height: 2 * radius
  12060. } : {}));
  12061. } else if (isInside && (radius > 0 || isImage)) {
  12062. point.graphic = graphic = chart.renderer.symbol(
  12063. symbol,
  12064. plotX - radius,
  12065. plotY - radius,
  12066. 2 * radius,
  12067. 2 * radius
  12068. )
  12069. .attr(pointAttr)
  12070. .add(markerGroup);
  12071. }
  12072. } else if (graphic) {
  12073. point.graphic = graphic.destroy(); // #1269
  12074. }
  12075. }
  12076. }
  12077. },
  12078. /**
  12079. * Convert state properties from API naming conventions to SVG attributes
  12080. *
  12081. * @param {Object} options API options object
  12082. * @param {Object} base1 SVG attribute object to inherit from
  12083. * @param {Object} base2 Second level SVG attribute object to inherit from
  12084. */
  12085. convertAttribs: function (options, base1, base2, base3) {
  12086. var conversion = this.pointAttrToOptions,
  12087. attr,
  12088. option,
  12089. obj = {};
  12090. options = options || {};
  12091. base1 = base1 || {};
  12092. base2 = base2 || {};
  12093. base3 = base3 || {};
  12094. for (attr in conversion) {
  12095. option = conversion[attr];
  12096. obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]);
  12097. }
  12098. return obj;
  12099. },
  12100. /**
  12101. * Get the state attributes. Each series type has its own set of attributes
  12102. * that are allowed to change on a point's state change. Series wide attributes are stored for
  12103. * all series, and additionally point specific attributes are stored for all
  12104. * points with individual marker options. If such options are not defined for the point,
  12105. * a reference to the series wide attributes is stored in point.pointAttr.
  12106. */
  12107. getAttribs: function () {
  12108. var series = this,
  12109. seriesOptions = series.options,
  12110. normalOptions = defaultPlotOptions[series.type].marker ? seriesOptions.marker : seriesOptions,
  12111. stateOptions = normalOptions.states,
  12112. stateOptionsHover = stateOptions[HOVER_STATE],
  12113. pointStateOptionsHover,
  12114. seriesColor = series.color,
  12115. normalDefaults = {
  12116. stroke: seriesColor,
  12117. fill: seriesColor
  12118. },
  12119. points = series.points || [], // #927
  12120. i,
  12121. point,
  12122. seriesPointAttr = [],
  12123. pointAttr,
  12124. pointAttrToOptions = series.pointAttrToOptions,
  12125. hasPointSpecificOptions,
  12126. negativeColor = seriesOptions.negativeColor,
  12127. defaultLineColor = normalOptions.lineColor,
  12128. key;
  12129. // series type specific modifications
  12130. if (seriesOptions.marker) { // line, spline, area, areaspline, scatter
  12131. // if no hover radius is given, default to normal radius + 2
  12132. stateOptionsHover.radius = stateOptionsHover.radius || normalOptions.radius + 2;
  12133. stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + 1;
  12134. } else { // column, bar, pie
  12135. // if no hover color is given, brighten the normal color
  12136. stateOptionsHover.color = stateOptionsHover.color ||
  12137. Color(stateOptionsHover.color || seriesColor)
  12138. .brighten(stateOptionsHover.brightness).get();
  12139. }
  12140. // general point attributes for the series normal state
  12141. seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults);
  12142. // HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius
  12143. each([HOVER_STATE, SELECT_STATE], function (state) {
  12144. seriesPointAttr[state] =
  12145. series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]);
  12146. });
  12147. // set it
  12148. series.pointAttr = seriesPointAttr;
  12149. // Generate the point-specific attribute collections if specific point
  12150. // options are given. If not, create a referance to the series wide point
  12151. // attributes
  12152. i = points.length;
  12153. while (i--) {
  12154. point = points[i];
  12155. normalOptions = (point.options && point.options.marker) || point.options;
  12156. if (normalOptions && normalOptions.enabled === false) {
  12157. normalOptions.radius = 0;
  12158. }
  12159. if (point.negative && negativeColor) {
  12160. point.color = point.fillColor = negativeColor;
  12161. }
  12162. hasPointSpecificOptions = seriesOptions.colorByPoint || point.color; // #868
  12163. // check if the point has specific visual options
  12164. if (point.options) {
  12165. for (key in pointAttrToOptions) {
  12166. if (defined(normalOptions[pointAttrToOptions[key]])) {
  12167. hasPointSpecificOptions = true;
  12168. }
  12169. }
  12170. }
  12171. // a specific marker config object is defined for the individual point:
  12172. // create it's own attribute collection
  12173. if (hasPointSpecificOptions) {
  12174. normalOptions = normalOptions || {};
  12175. pointAttr = [];
  12176. stateOptions = normalOptions.states || {}; // reassign for individual point
  12177. pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {};
  12178. // Handle colors for column and pies
  12179. if (!seriesOptions.marker) { // column, bar, point
  12180. // if no hover color is given, brighten the normal color
  12181. pointStateOptionsHover.color =
  12182. Color(pointStateOptionsHover.color || point.color)
  12183. .brighten(pointStateOptionsHover.brightness ||
  12184. stateOptionsHover.brightness).get();
  12185. }
  12186. // normal point state inherits series wide normal state
  12187. pointAttr[NORMAL_STATE] = series.convertAttribs(extend({
  12188. color: point.color, // #868
  12189. fillColor: point.color, // Individual point color or negative color markers (#2219)
  12190. lineColor: defaultLineColor === null ? point.color : UNDEFINED // Bubbles take point color, line markers use white
  12191. }, normalOptions), seriesPointAttr[NORMAL_STATE]);
  12192. // inherit from point normal and series hover
  12193. pointAttr[HOVER_STATE] = series.convertAttribs(
  12194. stateOptions[HOVER_STATE],
  12195. seriesPointAttr[HOVER_STATE],
  12196. pointAttr[NORMAL_STATE]
  12197. );
  12198. // inherit from point normal and series hover
  12199. pointAttr[SELECT_STATE] = series.convertAttribs(
  12200. stateOptions[SELECT_STATE],
  12201. seriesPointAttr[SELECT_STATE],
  12202. pointAttr[NORMAL_STATE]
  12203. );
  12204. // no marker config object is created: copy a reference to the series-wide
  12205. // attribute collection
  12206. } else {
  12207. pointAttr = seriesPointAttr;
  12208. }
  12209. point.pointAttr = pointAttr;
  12210. }
  12211. },
  12212. /**
  12213. * Update the series with a new set of options
  12214. */
  12215. update: function (newOptions, redraw) {
  12216. var chart = this.chart,
  12217. // must use user options when changing type because this.options is merged
  12218. // in with type specific plotOptions
  12219. oldOptions = this.userOptions,
  12220. oldType = this.type,
  12221. proto = seriesTypes[oldType].prototype,
  12222. n;
  12223. // Do the merge, with some forced options
  12224. newOptions = merge(oldOptions, {
  12225. animation: false,
  12226. index: this.index,
  12227. pointStart: this.xData[0] // when updating after addPoint
  12228. }, { data: this.options.data }, newOptions);
  12229. // Destroy the series and reinsert methods from the type prototype
  12230. this.remove(false);
  12231. for (n in proto) { // Overwrite series-type specific methods (#2270)
  12232. if (proto.hasOwnProperty(n)) {
  12233. this[n] = UNDEFINED;
  12234. }
  12235. }
  12236. extend(this, seriesTypes[newOptions.type || oldType].prototype);
  12237. this.init(chart, newOptions);
  12238. if (pick(redraw, true)) {
  12239. chart.redraw(false);
  12240. }
  12241. },
  12242. /**
  12243. * Clear DOM objects and free up memory
  12244. */
  12245. destroy: function () {
  12246. var series = this,
  12247. chart = series.chart,
  12248. issue134 = /AppleWebKit\/533/.test(userAgent),
  12249. destroy,
  12250. i,
  12251. data = series.data || [],
  12252. point,
  12253. prop,
  12254. axis;
  12255. // add event hook
  12256. fireEvent(series, 'destroy');
  12257. // remove all events
  12258. removeEvent(series);
  12259. // erase from axes
  12260. each(['xAxis', 'yAxis'], function (AXIS) {
  12261. axis = series[AXIS];
  12262. if (axis) {
  12263. erase(axis.series, series);
  12264. axis.isDirty = axis.forceRedraw = true;
  12265. axis.stacks = {}; // Rebuild stacks when updating (#2229)
  12266. }
  12267. });
  12268. // remove legend items
  12269. if (series.legendItem) {
  12270. series.chart.legend.destroyItem(series);
  12271. }
  12272. // destroy all points with their elements
  12273. i = data.length;
  12274. while (i--) {
  12275. point = data[i];
  12276. if (point && point.destroy) {
  12277. point.destroy();
  12278. }
  12279. }
  12280. series.points = null;
  12281. // Clear the animation timeout if we are destroying the series during initial animation
  12282. clearTimeout(series.animationTimeout);
  12283. // destroy all SVGElements associated to the series
  12284. each(['area', 'graph', 'dataLabelsGroup', 'group', 'markerGroup', 'tracker',
  12285. 'graphNeg', 'areaNeg', 'posClip', 'negClip'], function (prop) {
  12286. if (series[prop]) {
  12287. // issue 134 workaround
  12288. destroy = issue134 && prop === 'group' ?
  12289. 'hide' :
  12290. 'destroy';
  12291. series[prop][destroy]();
  12292. }
  12293. });
  12294. // remove from hoverSeries
  12295. if (chart.hoverSeries === series) {
  12296. chart.hoverSeries = null;
  12297. }
  12298. erase(chart.series, series);
  12299. // clear all members
  12300. for (prop in series) {
  12301. delete series[prop];
  12302. }
  12303. },
  12304. /**
  12305. * Draw the data labels
  12306. */
  12307. drawDataLabels: function () {
  12308. var series = this,
  12309. seriesOptions = series.options,
  12310. options = seriesOptions.dataLabels,
  12311. points = series.points,
  12312. pointOptions,
  12313. generalOptions,
  12314. str,
  12315. dataLabelsGroup;
  12316. if (options.enabled || series._hasPointLabels) {
  12317. // Process default alignment of data labels for columns
  12318. if (series.dlProcessOptions) {
  12319. series.dlProcessOptions(options);
  12320. }
  12321. // Create a separate group for the data labels to avoid rotation
  12322. dataLabelsGroup = series.plotGroup(
  12323. 'dataLabelsGroup',
  12324. 'data-labels',
  12325. series.visible ? VISIBLE : HIDDEN,
  12326. options.zIndex || 6
  12327. );
  12328. // Make the labels for each point
  12329. generalOptions = options;
  12330. each(points, function (point) {
  12331. var enabled,
  12332. dataLabel = point.dataLabel,
  12333. labelConfig,
  12334. attr,
  12335. name,
  12336. rotation,
  12337. connector = point.connector,
  12338. isNew = true;
  12339. // Determine if each data label is enabled
  12340. pointOptions = point.options && point.options.dataLabels;
  12341. enabled = pick(pointOptions && pointOptions.enabled, generalOptions.enabled); // #2282
  12342. // If the point is outside the plot area, destroy it. #678, #820
  12343. if (dataLabel && !enabled) {
  12344. point.dataLabel = dataLabel.destroy();
  12345. // Individual labels are disabled if the are explicitly disabled
  12346. // in the point options, or if they fall outside the plot area.
  12347. } else if (enabled) {
  12348. // Create individual options structure that can be extended without
  12349. // affecting others
  12350. options = merge(generalOptions, pointOptions);
  12351. rotation = options.rotation;
  12352. // Get the string
  12353. labelConfig = point.getLabelConfig();
  12354. str = options.format ?
  12355. format(options.format, labelConfig) :
  12356. options.formatter.call(labelConfig, options);
  12357. // Determine the color
  12358. options.style.color = pick(options.color, options.style.color, series.color, 'black');
  12359. // update existing label
  12360. if (dataLabel) {
  12361. if (defined(str)) {
  12362. dataLabel
  12363. .attr({
  12364. text: str
  12365. });
  12366. isNew = false;
  12367. } else { // #1437 - the label is shown conditionally
  12368. point.dataLabel = dataLabel = dataLabel.destroy();
  12369. if (connector) {
  12370. point.connector = connector.destroy();
  12371. }
  12372. }
  12373. // create new label
  12374. } else if (defined(str)) {
  12375. attr = {
  12376. //align: align,
  12377. fill: options.backgroundColor,
  12378. stroke: options.borderColor,
  12379. 'stroke-width': options.borderWidth,
  12380. r: options.borderRadius || 0,
  12381. rotation: rotation,
  12382. padding: options.padding,
  12383. zIndex: 1
  12384. };
  12385. // Remove unused attributes (#947)
  12386. for (name in attr) {
  12387. if (attr[name] === UNDEFINED) {
  12388. delete attr[name];
  12389. }
  12390. }
  12391. dataLabel = point.dataLabel = series.chart.renderer[rotation ? 'text' : 'label']( // labels don't support rotation
  12392. str,
  12393. 0,
  12394. -999,
  12395. null,
  12396. null,
  12397. null,
  12398. options.useHTML
  12399. )
  12400. .attr(attr)
  12401. .css(options.style)
  12402. .add(dataLabelsGroup)
  12403. .shadow(options.shadow);
  12404. }
  12405. if (dataLabel) {
  12406. // Now the data label is created and placed at 0,0, so we need to align it
  12407. series.alignDataLabel(point, dataLabel, options, null, isNew);
  12408. }
  12409. }
  12410. });
  12411. }
  12412. },
  12413. /**
  12414. * Align each individual data label
  12415. */
  12416. alignDataLabel: function (point, dataLabel, options, alignTo, isNew) {
  12417. var chart = this.chart,
  12418. inverted = chart.inverted,
  12419. plotX = pick(point.plotX, -999),
  12420. plotY = pick(point.plotY, -999),
  12421. bBox = dataLabel.getBBox(),
  12422. visible = this.visible && chart.isInsidePlot(point.plotX, point.plotY, inverted),
  12423. alignAttr; // the final position;
  12424. if (visible) {
  12425. // The alignment box is a singular point
  12426. alignTo = extend({
  12427. x: inverted ? chart.plotWidth - plotY : plotX,
  12428. y: mathRound(inverted ? chart.plotHeight - plotX : plotY),
  12429. width: 0,
  12430. height: 0
  12431. }, alignTo);
  12432. // Add the text size for alignment calculation
  12433. extend(options, {
  12434. width: bBox.width,
  12435. height: bBox.height
  12436. });
  12437. // Allow a hook for changing alignment in the last moment, then do the alignment
  12438. if (options.rotation) { // Fancy box alignment isn't supported for rotated text
  12439. alignAttr = {
  12440. align: options.align,
  12441. x: alignTo.x + options.x + alignTo.width / 2,
  12442. y: alignTo.y + options.y + alignTo.height / 2
  12443. };
  12444. dataLabel[isNew ? 'attr' : 'animate'](alignAttr);
  12445. } else {
  12446. dataLabel.align(options, null, alignTo);
  12447. alignAttr = dataLabel.alignAttr;
  12448. // Handle justify or crop
  12449. if (pick(options.overflow, 'justify') === 'justify') { // docs: overflow: justify, also crop only applies when not justify
  12450. this.justifyDataLabel(dataLabel, options, alignAttr, bBox, alignTo, isNew);
  12451. } else if (pick(options.crop, true)) {
  12452. // Now check that the data label is within the plot area
  12453. visible = chart.isInsidePlot(alignAttr.x, alignAttr.y) && chart.isInsidePlot(alignAttr.x + bBox.width, alignAttr.y + bBox.height);
  12454. }
  12455. }
  12456. }
  12457. // Show or hide based on the final aligned position
  12458. if (!visible) {
  12459. dataLabel.attr({ y: -999 });
  12460. }
  12461. },
  12462. /**
  12463. * If data labels fall partly outside the plot area, align them back in, in a way that
  12464. * doesn't hide the point.
  12465. */
  12466. justifyDataLabel: function (dataLabel, options, alignAttr, bBox, alignTo, isNew) {
  12467. var chart = this.chart,
  12468. align = options.align,
  12469. verticalAlign = options.verticalAlign,
  12470. off,
  12471. justified;
  12472. // Off left
  12473. off = alignAttr.x;
  12474. if (off < 0) {
  12475. if (align === 'right') {
  12476. options.align = 'left';
  12477. } else {
  12478. options.x = -off;
  12479. }
  12480. justified = true;
  12481. }
  12482. // Off right
  12483. off = alignAttr.x + bBox.width;
  12484. if (off > chart.plotWidth) {
  12485. if (align === 'left') {
  12486. options.align = 'right';
  12487. } else {
  12488. options.x = chart.plotWidth - off;
  12489. }
  12490. justified = true;
  12491. }
  12492. // Off top
  12493. off = alignAttr.y;
  12494. if (off < 0) {
  12495. if (verticalAlign === 'bottom') {
  12496. options.verticalAlign = 'top';
  12497. } else {
  12498. options.y = -off;
  12499. }
  12500. justified = true;
  12501. }
  12502. // Off bottom
  12503. off = alignAttr.y + bBox.height;
  12504. if (off > chart.plotHeight) {
  12505. if (verticalAlign === 'top') {
  12506. options.verticalAlign = 'bottom';
  12507. } else {
  12508. options.y = chart.plotHeight - off;
  12509. }
  12510. justified = true;
  12511. }
  12512. if (justified) {
  12513. dataLabel.placed = !isNew;
  12514. dataLabel.align(options, null, alignTo);
  12515. }
  12516. },
  12517. /**
  12518. * Return the graph path of a segment
  12519. */
  12520. getSegmentPath: function (segment) {
  12521. var series = this,
  12522. segmentPath = [],
  12523. step = series.options.step;
  12524. // build the segment line
  12525. each(segment, function (point, i) {
  12526. var plotX = point.plotX,
  12527. plotY = point.plotY,
  12528. lastPoint;
  12529. if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object
  12530. segmentPath.push.apply(segmentPath, series.getPointSpline(segment, point, i));
  12531. } else {
  12532. // moveTo or lineTo
  12533. segmentPath.push(i ? L : M);
  12534. // step line?
  12535. if (step && i) {
  12536. lastPoint = segment[i - 1];
  12537. if (step === 'right') {
  12538. segmentPath.push(
  12539. lastPoint.plotX,
  12540. plotY
  12541. );
  12542. } else if (step === 'center') {
  12543. segmentPath.push(
  12544. (lastPoint.plotX + plotX) / 2,
  12545. lastPoint.plotY,
  12546. (lastPoint.plotX + plotX) / 2,
  12547. plotY
  12548. );
  12549. } else {
  12550. segmentPath.push(
  12551. plotX,
  12552. lastPoint.plotY
  12553. );
  12554. }
  12555. }
  12556. // normal line to next point
  12557. segmentPath.push(
  12558. point.plotX,
  12559. point.plotY
  12560. );
  12561. }
  12562. });
  12563. return segmentPath;
  12564. },
  12565. /**
  12566. * Get the graph path
  12567. */
  12568. getGraphPath: function () {
  12569. var series = this,
  12570. graphPath = [],
  12571. segmentPath,
  12572. singlePoints = []; // used in drawTracker
  12573. // Divide into segments and build graph and area paths
  12574. each(series.segments, function (segment) {
  12575. segmentPath = series.getSegmentPath(segment);
  12576. // add the segment to the graph, or a single point for tracking
  12577. if (segment.length > 1) {
  12578. graphPath = graphPath.concat(segmentPath);
  12579. } else {
  12580. singlePoints.push(segment[0]);
  12581. }
  12582. });
  12583. // Record it for use in drawGraph and drawTracker, and return graphPath
  12584. series.singlePoints = singlePoints;
  12585. series.graphPath = graphPath;
  12586. return graphPath;
  12587. },
  12588. /**
  12589. * Draw the actual graph
  12590. */
  12591. drawGraph: function () {
  12592. var series = this,
  12593. options = this.options,
  12594. props = [['graph', options.lineColor || this.color]],
  12595. lineWidth = options.lineWidth,
  12596. dashStyle = options.dashStyle,
  12597. graphPath = this.getGraphPath(),
  12598. negativeColor = options.negativeColor;
  12599. if (negativeColor) {
  12600. props.push(['graphNeg', negativeColor]);
  12601. }
  12602. // draw the graph
  12603. each(props, function (prop, i) {
  12604. var graphKey = prop[0],
  12605. graph = series[graphKey],
  12606. attribs;
  12607. if (graph) {
  12608. stop(graph); // cancel running animations, #459
  12609. graph.animate({ d: graphPath });
  12610. } else if (lineWidth && graphPath.length) { // #1487
  12611. attribs = {
  12612. stroke: prop[1],
  12613. 'stroke-width': lineWidth,
  12614. zIndex: 1 // #1069
  12615. };
  12616. if (dashStyle) {
  12617. attribs.dashstyle = dashStyle;
  12618. } else {
  12619. attribs['stroke-linecap'] = attribs['stroke-linejoin'] = 'round';
  12620. }
  12621. series[graphKey] = series.chart.renderer.path(graphPath)
  12622. .attr(attribs)
  12623. .add(series.group)
  12624. .shadow(!i && options.shadow);
  12625. }
  12626. });
  12627. },
  12628. /**
  12629. * Clip the graphs into the positive and negative coloured graphs
  12630. */
  12631. clipNeg: function () {
  12632. var options = this.options,
  12633. chart = this.chart,
  12634. renderer = chart.renderer,
  12635. negativeColor = options.negativeColor || options.negativeFillColor,
  12636. translatedThreshold,
  12637. posAttr,
  12638. negAttr,
  12639. graph = this.graph,
  12640. area = this.area,
  12641. posClip = this.posClip,
  12642. negClip = this.negClip,
  12643. chartWidth = chart.chartWidth,
  12644. chartHeight = chart.chartHeight,
  12645. chartSizeMax = mathMax(chartWidth, chartHeight),
  12646. yAxis = this.yAxis,
  12647. above,
  12648. below;
  12649. if (negativeColor && (graph || area)) {
  12650. translatedThreshold = mathRound(yAxis.toPixels(options.threshold || 0, true));
  12651. above = {
  12652. x: 0,
  12653. y: 0,
  12654. width: chartSizeMax,
  12655. height: translatedThreshold
  12656. };
  12657. below = {
  12658. x: 0,
  12659. y: translatedThreshold,
  12660. width: chartSizeMax,
  12661. height: chartSizeMax
  12662. };
  12663. if (chart.inverted) {
  12664. above.height = below.y = chart.plotWidth - translatedThreshold;
  12665. if (renderer.isVML) {
  12666. above = {
  12667. x: chart.plotWidth - translatedThreshold - chart.plotLeft,
  12668. y: 0,
  12669. width: chartWidth,
  12670. height: chartHeight
  12671. };
  12672. below = {
  12673. x: translatedThreshold + chart.plotLeft - chartWidth,
  12674. y: 0,
  12675. width: chart.plotLeft + translatedThreshold,
  12676. height: chartWidth
  12677. };
  12678. }
  12679. }
  12680. if (yAxis.reversed) {
  12681. posAttr = below;
  12682. negAttr = above;
  12683. } else {
  12684. posAttr = above;
  12685. negAttr = below;
  12686. }
  12687. if (posClip) { // update
  12688. posClip.animate(posAttr);
  12689. negClip.animate(negAttr);
  12690. } else {
  12691. this.posClip = posClip = renderer.clipRect(posAttr);
  12692. this.negClip = negClip = renderer.clipRect(negAttr);
  12693. if (graph && this.graphNeg) {
  12694. graph.clip(posClip);
  12695. this.graphNeg.clip(negClip);
  12696. }
  12697. if (area) {
  12698. area.clip(posClip);
  12699. this.areaNeg.clip(negClip);
  12700. }
  12701. }
  12702. }
  12703. },
  12704. /**
  12705. * Initialize and perform group inversion on series.group and series.markerGroup
  12706. */
  12707. invertGroups: function () {
  12708. var series = this,
  12709. chart = series.chart;
  12710. // Pie, go away (#1736)
  12711. if (!series.xAxis) {
  12712. return;
  12713. }
  12714. // A fixed size is needed for inversion to work
  12715. function setInvert() {
  12716. var size = {
  12717. width: series.yAxis.len,
  12718. height: series.xAxis.len
  12719. };
  12720. each(['group', 'markerGroup'], function (groupName) {
  12721. if (series[groupName]) {
  12722. series[groupName].attr(size).invert();
  12723. }
  12724. });
  12725. }
  12726. addEvent(chart, 'resize', setInvert); // do it on resize
  12727. addEvent(series, 'destroy', function () {
  12728. removeEvent(chart, 'resize', setInvert);
  12729. });
  12730. // Do it now
  12731. setInvert(); // do it now
  12732. // On subsequent render and redraw, just do setInvert without setting up events again
  12733. series.invertGroups = setInvert;
  12734. },
  12735. /**
  12736. * General abstraction for creating plot groups like series.group, series.dataLabelsGroup and
  12737. * series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size.
  12738. */
  12739. plotGroup: function (prop, name, visibility, zIndex, parent) {
  12740. var group = this[prop],
  12741. isNew = !group;
  12742. // Generate it on first call
  12743. if (isNew) {
  12744. this[prop] = group = this.chart.renderer.g(name)
  12745. .attr({
  12746. visibility: visibility,
  12747. zIndex: zIndex || 0.1 // IE8 needs this
  12748. })
  12749. .add(parent);
  12750. }
  12751. // Place it on first and subsequent (redraw) calls
  12752. group[isNew ? 'attr' : 'animate'](this.getPlotBox());
  12753. return group;
  12754. },
  12755. /**
  12756. * Get the translation and scale for the plot area of this series
  12757. */
  12758. getPlotBox: function () {
  12759. return {
  12760. translateX: this.xAxis ? this.xAxis.left : this.chart.plotLeft,
  12761. translateY: this.yAxis ? this.yAxis.top : this.chart.plotTop,
  12762. scaleX: 1, // #1623
  12763. scaleY: 1
  12764. };
  12765. },
  12766. /**
  12767. * Render the graph and markers
  12768. */
  12769. render: function () {
  12770. var series = this,
  12771. chart = series.chart,
  12772. group,
  12773. options = series.options,
  12774. animation = options.animation,
  12775. doAnimation = animation && !!series.animate &&
  12776. chart.renderer.isSVG, // this animation doesn't work in IE8 quirks when the group div is hidden,
  12777. // and looks bad in other oldIE
  12778. visibility = series.visible ? VISIBLE : HIDDEN,
  12779. zIndex = options.zIndex,
  12780. hasRendered = series.hasRendered,
  12781. chartSeriesGroup = chart.seriesGroup;
  12782. // the group
  12783. group = series.plotGroup(
  12784. 'group',
  12785. 'series',
  12786. visibility,
  12787. zIndex,
  12788. chartSeriesGroup
  12789. );
  12790. series.markerGroup = series.plotGroup(
  12791. 'markerGroup',
  12792. 'markers',
  12793. visibility,
  12794. zIndex,
  12795. chartSeriesGroup
  12796. );
  12797. // initiate the animation
  12798. if (doAnimation) {
  12799. series.animate(true);
  12800. }
  12801. // cache attributes for shapes
  12802. series.getAttribs();
  12803. // SVGRenderer needs to know this before drawing elements (#1089, #1795)
  12804. group.inverted = series.isCartesian ? chart.inverted : false;
  12805. // draw the graph if any
  12806. if (series.drawGraph) {
  12807. series.drawGraph();
  12808. series.clipNeg();
  12809. }
  12810. // draw the data labels (inn pies they go before the points)
  12811. series.drawDataLabels();
  12812. // draw the points
  12813. series.drawPoints();
  12814. // draw the mouse tracking area
  12815. if (series.options.enableMouseTracking !== false) {
  12816. series.drawTracker();
  12817. }
  12818. // Handle inverted series and tracker groups
  12819. if (chart.inverted) {
  12820. series.invertGroups();
  12821. }
  12822. // Initial clipping, must be defined after inverting groups for VML
  12823. if (options.clip !== false && !series.sharedClipKey && !hasRendered) {
  12824. group.clip(chart.clipRect);
  12825. }
  12826. // Run the animation
  12827. if (doAnimation) {
  12828. series.animate();
  12829. } else if (!hasRendered) {
  12830. series.afterAnimate();
  12831. }
  12832. series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
  12833. // (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
  12834. series.hasRendered = true;
  12835. },
  12836. /**
  12837. * Redraw the series after an update in the axes.
  12838. */
  12839. redraw: function () {
  12840. var series = this,
  12841. chart = series.chart,
  12842. wasDirtyData = series.isDirtyData, // cache it here as it is set to false in render, but used after
  12843. group = series.group,
  12844. xAxis = series.xAxis,
  12845. yAxis = series.yAxis;
  12846. // reposition on resize
  12847. if (group) {
  12848. if (chart.inverted) {
  12849. group.attr({
  12850. width: chart.plotWidth,
  12851. height: chart.plotHeight
  12852. });
  12853. }
  12854. group.animate({
  12855. translateX: pick(xAxis && xAxis.left, chart.plotLeft),
  12856. translateY: pick(yAxis && yAxis.top, chart.plotTop)
  12857. });
  12858. }
  12859. series.translate();
  12860. series.setTooltipPoints(true);
  12861. series.render();
  12862. if (wasDirtyData) {
  12863. fireEvent(series, 'updatedData');
  12864. }
  12865. },
  12866. /**
  12867. * Set the state of the graph
  12868. */
  12869. setState: function (state) {
  12870. var series = this,
  12871. options = series.options,
  12872. graph = series.graph,
  12873. graphNeg = series.graphNeg,
  12874. stateOptions = options.states,
  12875. lineWidth = options.lineWidth,
  12876. attribs;
  12877. state = state || NORMAL_STATE;
  12878. if (series.state !== state) {
  12879. series.state = state;
  12880. if (stateOptions[state] && stateOptions[state].enabled === false) {
  12881. return;
  12882. }
  12883. if (state) {
  12884. lineWidth = stateOptions[state].lineWidth || lineWidth + 1;
  12885. }
  12886. if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML
  12887. attribs = {
  12888. 'stroke-width': lineWidth
  12889. };
  12890. // use attr because animate will cause any other animation on the graph to stop
  12891. graph.attr(attribs);
  12892. if (graphNeg) {
  12893. graphNeg.attr(attribs);
  12894. }
  12895. }
  12896. }
  12897. },
  12898. /**
  12899. * Set the visibility of the graph
  12900. *
  12901. * @param vis {Boolean} True to show the series, false to hide. If UNDEFINED,
  12902. * the visibility is toggled.
  12903. */
  12904. setVisible: function (vis, redraw) {
  12905. var series = this,
  12906. chart = series.chart,
  12907. legendItem = series.legendItem,
  12908. showOrHide,
  12909. ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries,
  12910. oldVisibility = series.visible;
  12911. // if called without an argument, toggle visibility
  12912. series.visible = vis = series.userOptions.visible = vis === UNDEFINED ? !oldVisibility : vis;
  12913. showOrHide = vis ? 'show' : 'hide';
  12914. // show or hide elements
  12915. each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) {
  12916. if (series[key]) {
  12917. series[key][showOrHide]();
  12918. }
  12919. });
  12920. // hide tooltip (#1361)
  12921. if (chart.hoverSeries === series) {
  12922. series.onMouseOut();
  12923. }
  12924. if (legendItem) {
  12925. chart.legend.colorizeItem(series, vis);
  12926. }
  12927. // rescale or adapt to resized chart
  12928. series.isDirty = true;
  12929. // in a stack, all other series are affected
  12930. if (series.options.stacking) {
  12931. each(chart.series, function (otherSeries) {
  12932. if (otherSeries.options.stacking && otherSeries.visible) {
  12933. otherSeries.isDirty = true;
  12934. }
  12935. });
  12936. }
  12937. // show or hide linked series
  12938. each(series.linkedSeries, function (otherSeries) {
  12939. otherSeries.setVisible(vis, false);
  12940. });
  12941. if (ignoreHiddenSeries) {
  12942. chart.isDirtyBox = true;
  12943. }
  12944. if (redraw !== false) {
  12945. chart.redraw();
  12946. }
  12947. fireEvent(series, showOrHide);
  12948. },
  12949. /**
  12950. * Show the graph
  12951. */
  12952. show: function () {
  12953. this.setVisible(true);
  12954. },
  12955. /**
  12956. * Hide the graph
  12957. */
  12958. hide: function () {
  12959. this.setVisible(false);
  12960. },
  12961. /**
  12962. * Set the selected state of the graph
  12963. *
  12964. * @param selected {Boolean} True to select the series, false to unselect. If
  12965. * UNDEFINED, the selection state is toggled.
  12966. */
  12967. select: function (selected) {
  12968. var series = this;
  12969. // if called without an argument, toggle
  12970. series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected;
  12971. if (series.checkbox) {
  12972. series.checkbox.checked = selected;
  12973. }
  12974. fireEvent(series, selected ? 'select' : 'unselect');
  12975. },
  12976. /**
  12977. * Draw the tracker object that sits above all data labels and markers to
  12978. * track mouse events on the graph or points. For the line type charts
  12979. * the tracker uses the same graphPath, but with a greater stroke width
  12980. * for better control.
  12981. */
  12982. drawTracker: function () {
  12983. var series = this,
  12984. options = series.options,
  12985. trackByArea = options.trackByArea,
  12986. trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath),
  12987. trackerPathLength = trackerPath.length,
  12988. chart = series.chart,
  12989. pointer = chart.pointer,
  12990. renderer = chart.renderer,
  12991. snap = chart.options.tooltip.snap,
  12992. tracker = series.tracker,
  12993. cursor = options.cursor,
  12994. css = cursor && { cursor: cursor },
  12995. singlePoints = series.singlePoints,
  12996. singlePoint,
  12997. i,
  12998. onMouseOver = function () {
  12999. if (chart.hoverSeries !== series) {
  13000. series.onMouseOver();
  13001. }
  13002. };
  13003. // Extend end points. A better way would be to use round linecaps,
  13004. // but those are not clickable in VML.
  13005. if (trackerPathLength && !trackByArea) {
  13006. i = trackerPathLength + 1;
  13007. while (i--) {
  13008. if (trackerPath[i] === M) { // extend left side
  13009. trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L);
  13010. }
  13011. if ((i && trackerPath[i] === M) || i === trackerPathLength) { // extend right side
  13012. trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]);
  13013. }
  13014. }
  13015. }
  13016. // handle single points
  13017. for (i = 0; i < singlePoints.length; i++) {
  13018. singlePoint = singlePoints[i];
  13019. trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY,
  13020. L, singlePoint.plotX + snap, singlePoint.plotY);
  13021. }
  13022. // draw the tracker
  13023. if (tracker) {
  13024. tracker.attr({ d: trackerPath });
  13025. } else { // create
  13026. series.tracker = renderer.path(trackerPath)
  13027. .attr({
  13028. 'stroke-linejoin': 'round', // #1225
  13029. visibility: series.visible ? VISIBLE : HIDDEN,
  13030. stroke: TRACKER_FILL,
  13031. fill: trackByArea ? TRACKER_FILL : NONE,
  13032. 'stroke-width' : options.lineWidth + (trackByArea ? 0 : 2 * snap),
  13033. zIndex: 2
  13034. })
  13035. .add(series.group);
  13036. // The tracker is added to the series group, which is clipped, but is covered
  13037. // by the marker group. So the marker group also needs to capture events.
  13038. each([series.tracker, series.markerGroup], function (tracker) {
  13039. tracker.addClass(PREFIX + 'tracker')
  13040. .on('mouseover', onMouseOver)
  13041. .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); })
  13042. .css(css);
  13043. if (hasTouch) {
  13044. tracker.on('touchstart', onMouseOver);
  13045. }
  13046. });
  13047. }
  13048. }
  13049. }; // end Series prototype
  13050. /**
  13051. * LineSeries object
  13052. */
  13053. var LineSeries = extendClass(Series);
  13054. seriesTypes.line = LineSeries;
  13055. /**
  13056. * Set the default options for area
  13057. */
  13058. defaultPlotOptions.area = merge(defaultSeriesOptions, {
  13059. threshold: 0
  13060. // trackByArea: false,
  13061. // lineColor: null, // overrides color, but lets fillColor be unaltered
  13062. // fillOpacity: 0.75,
  13063. // fillColor: null
  13064. });
  13065. /**
  13066. * AreaSeries object
  13067. */
  13068. var AreaSeries = extendClass(Series, {
  13069. type: 'area',
  13070. /**
  13071. * For stacks, don't split segments on null values. Instead, draw null values with
  13072. * no marker. Also insert dummy points for any X position that exists in other series
  13073. * in the stack.
  13074. */
  13075. getSegments: function () {
  13076. var segments = [],
  13077. segment = [],
  13078. keys = [],
  13079. xAxis = this.xAxis,
  13080. yAxis = this.yAxis,
  13081. stack = yAxis.stacks[this.stackKey],
  13082. pointMap = {},
  13083. plotX,
  13084. plotY,
  13085. points = this.points,
  13086. connectNulls = this.options.connectNulls,
  13087. val,
  13088. i,
  13089. x;
  13090. if (this.options.stacking && !this.cropped) { // cropped causes artefacts in Stock, and perf issue
  13091. // Create a map where we can quickly look up the points by their X value.
  13092. for (i = 0; i < points.length; i++) {
  13093. pointMap[points[i].x] = points[i];
  13094. }
  13095. // Sort the keys (#1651)
  13096. for (x in stack) {
  13097. keys.push(+x);
  13098. }
  13099. keys.sort(function (a, b) {
  13100. return a - b;
  13101. });
  13102. each(keys, function (x) {
  13103. if (connectNulls && (!pointMap[x] || pointMap[x].y === null)) { // #1836
  13104. return;
  13105. // The point exists, push it to the segment
  13106. } else if (pointMap[x]) {
  13107. segment.push(pointMap[x]);
  13108. // There is no point for this X value in this series, so we
  13109. // insert a dummy point in order for the areas to be drawn
  13110. // correctly.
  13111. } else {
  13112. plotX = xAxis.translate(x);
  13113. val = stack[x].percent ? (stack[x].total ? stack[x].cum * 100 / stack[x].total : 0) : stack[x].cum; // #1991
  13114. plotY = yAxis.toPixels(val, true);
  13115. segment.push({
  13116. y: null,
  13117. plotX: plotX,
  13118. clientX: plotX,
  13119. plotY: plotY,
  13120. yBottom: plotY,
  13121. onMouseOver: noop
  13122. });
  13123. }
  13124. });
  13125. if (segment.length) {
  13126. segments.push(segment);
  13127. }
  13128. } else {
  13129. Series.prototype.getSegments.call(this);
  13130. segments = this.segments;
  13131. }
  13132. this.segments = segments;
  13133. },
  13134. /**
  13135. * Extend the base Series getSegmentPath method by adding the path for the area.
  13136. * This path is pushed to the series.areaPath property.
  13137. */
  13138. getSegmentPath: function (segment) {
  13139. var segmentPath = Series.prototype.getSegmentPath.call(this, segment), // call base method
  13140. areaSegmentPath = [].concat(segmentPath), // work on a copy for the area path
  13141. i,
  13142. options = this.options,
  13143. segLength = segmentPath.length,
  13144. translatedThreshold = this.yAxis.getThreshold(options.threshold), // #2181
  13145. yBottom;
  13146. if (segLength === 3) { // for animation from 1 to two points
  13147. areaSegmentPath.push(L, segmentPath[1], segmentPath[2]);
  13148. }
  13149. if (options.stacking && !this.closedStacks) {
  13150. // Follow stack back. Todo: implement areaspline. A general solution could be to
  13151. // reverse the entire graphPath of the previous series, though may be hard with
  13152. // splines and with series with different extremes
  13153. for (i = segment.length - 1; i >= 0; i--) {
  13154. yBottom = pick(segment[i].yBottom, translatedThreshold);
  13155. // step line?
  13156. if (i < segment.length - 1 && options.step) {
  13157. areaSegmentPath.push(segment[i + 1].plotX, yBottom);
  13158. }
  13159. areaSegmentPath.push(segment[i].plotX, yBottom);
  13160. }
  13161. } else { // follow zero line back
  13162. this.closeSegment(areaSegmentPath, segment, translatedThreshold);
  13163. }
  13164. this.areaPath = this.areaPath.concat(areaSegmentPath);
  13165. return segmentPath;
  13166. },
  13167. /**
  13168. * Extendable method to close the segment path of an area. This is overridden in polar
  13169. * charts.
  13170. */
  13171. closeSegment: function (path, segment, translatedThreshold) {
  13172. path.push(
  13173. L,
  13174. segment[segment.length - 1].plotX,
  13175. translatedThreshold,
  13176. L,
  13177. segment[0].plotX,
  13178. translatedThreshold
  13179. );
  13180. },
  13181. /**
  13182. * Draw the graph and the underlying area. This method calls the Series base
  13183. * function and adds the area. The areaPath is calculated in the getSegmentPath
  13184. * method called from Series.prototype.drawGraph.
  13185. */
  13186. drawGraph: function () {
  13187. // Define or reset areaPath
  13188. this.areaPath = [];
  13189. // Call the base method
  13190. Series.prototype.drawGraph.apply(this);
  13191. // Define local variables
  13192. var series = this,
  13193. areaPath = this.areaPath,
  13194. options = this.options,
  13195. negativeColor = options.negativeColor,
  13196. negativeFillColor = options.negativeFillColor,
  13197. props = [['area', this.color, options.fillColor]]; // area name, main color, fill color
  13198. if (negativeColor || negativeFillColor) {
  13199. props.push(['areaNeg', negativeColor, negativeFillColor]);
  13200. }
  13201. each(props, function (prop) {
  13202. var areaKey = prop[0],
  13203. area = series[areaKey];
  13204. // Create or update the area
  13205. if (area) { // update
  13206. area.animate({ d: areaPath });
  13207. } else { // create
  13208. series[areaKey] = series.chart.renderer.path(areaPath)
  13209. .attr({
  13210. fill: pick(
  13211. prop[2],
  13212. Color(prop[1]).setOpacity(pick(options.fillOpacity, 0.75)).get()
  13213. ),
  13214. zIndex: 0 // #1069
  13215. }).add(series.group);
  13216. }
  13217. });
  13218. },
  13219. /**
  13220. * Get the series' symbol in the legend
  13221. *
  13222. * @param {Object} legend The legend object
  13223. * @param {Object} item The series (this) or point
  13224. */
  13225. drawLegendSymbol: function (legend, item) {
  13226. item.legendSymbol = this.chart.renderer.rect(
  13227. 0,
  13228. legend.baseline - 11,
  13229. legend.options.symbolWidth,
  13230. 12,
  13231. 2
  13232. ).attr({
  13233. zIndex: 3
  13234. }).add(item.legendGroup);
  13235. }
  13236. });
  13237. seriesTypes.area = AreaSeries;/**
  13238. * Set the default options for spline
  13239. */
  13240. defaultPlotOptions.spline = merge(defaultSeriesOptions);
  13241. /**
  13242. * SplineSeries object
  13243. */
  13244. var SplineSeries = extendClass(Series, {
  13245. type: 'spline',
  13246. /**
  13247. * Get the spline segment from a given point's previous neighbour to the given point
  13248. */
  13249. getPointSpline: function (segment, point, i) {
  13250. var smoothing = 1.5, // 1 means control points midway between points, 2 means 1/3 from the point, 3 is 1/4 etc
  13251. denom = smoothing + 1,
  13252. plotX = point.plotX,
  13253. plotY = point.plotY,
  13254. lastPoint = segment[i - 1],
  13255. nextPoint = segment[i + 1],
  13256. leftContX,
  13257. leftContY,
  13258. rightContX,
  13259. rightContY,
  13260. ret;
  13261. // find control points
  13262. if (lastPoint && nextPoint) {
  13263. var lastX = lastPoint.plotX,
  13264. lastY = lastPoint.plotY,
  13265. nextX = nextPoint.plotX,
  13266. nextY = nextPoint.plotY,
  13267. correction;
  13268. leftContX = (smoothing * plotX + lastX) / denom;
  13269. leftContY = (smoothing * plotY + lastY) / denom;
  13270. rightContX = (smoothing * plotX + nextX) / denom;
  13271. rightContY = (smoothing * plotY + nextY) / denom;
  13272. // have the two control points make a straight line through main point
  13273. correction = ((rightContY - leftContY) * (rightContX - plotX)) /
  13274. (rightContX - leftContX) + plotY - rightContY;
  13275. leftContY += correction;
  13276. rightContY += correction;
  13277. // to prevent false extremes, check that control points are between
  13278. // neighbouring points' y values
  13279. if (leftContY > lastY && leftContY > plotY) {
  13280. leftContY = mathMax(lastY, plotY);
  13281. rightContY = 2 * plotY - leftContY; // mirror of left control point
  13282. } else if (leftContY < lastY && leftContY < plotY) {
  13283. leftContY = mathMin(lastY, plotY);
  13284. rightContY = 2 * plotY - leftContY;
  13285. }
  13286. if (rightContY > nextY && rightContY > plotY) {
  13287. rightContY = mathMax(nextY, plotY);
  13288. leftContY = 2 * plotY - rightContY;
  13289. } else if (rightContY < nextY && rightContY < plotY) {
  13290. rightContY = mathMin(nextY, plotY);
  13291. leftContY = 2 * plotY - rightContY;
  13292. }
  13293. // reconciliation for drawing in next point
  13294. point.rightContX = rightContX;
  13295. point.rightContY = rightContY;
  13296. }
  13297. // Visualize control points for debugging
  13298. /*
  13299. if (leftContX) {
  13300. this.chart.renderer.circle(leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop, 2)
  13301. .attr({
  13302. stroke: 'red',
  13303. 'stroke-width': 1,
  13304. fill: 'none'
  13305. })
  13306. .add();
  13307. this.chart.renderer.path(['M', leftContX + this.chart.plotLeft, leftContY + this.chart.plotTop,
  13308. 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
  13309. .attr({
  13310. stroke: 'red',
  13311. 'stroke-width': 1
  13312. })
  13313. .add();
  13314. this.chart.renderer.circle(rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop, 2)
  13315. .attr({
  13316. stroke: 'green',
  13317. 'stroke-width': 1,
  13318. fill: 'none'
  13319. })
  13320. .add();
  13321. this.chart.renderer.path(['M', rightContX + this.chart.plotLeft, rightContY + this.chart.plotTop,
  13322. 'L', plotX + this.chart.plotLeft, plotY + this.chart.plotTop])
  13323. .attr({
  13324. stroke: 'green',
  13325. 'stroke-width': 1
  13326. })
  13327. .add();
  13328. }
  13329. */
  13330. // moveTo or lineTo
  13331. if (!i) {
  13332. ret = [M, plotX, plotY];
  13333. } else { // curve from last point to this
  13334. ret = [
  13335. 'C',
  13336. lastPoint.rightContX || lastPoint.plotX,
  13337. lastPoint.rightContY || lastPoint.plotY,
  13338. leftContX || plotX,
  13339. leftContY || plotY,
  13340. plotX,
  13341. plotY
  13342. ];
  13343. lastPoint.rightContX = lastPoint.rightContY = null; // reset for updating series later
  13344. }
  13345. return ret;
  13346. }
  13347. });
  13348. seriesTypes.spline = SplineSeries;
  13349. /**
  13350. * Set the default options for areaspline
  13351. */
  13352. defaultPlotOptions.areaspline = merge(defaultPlotOptions.area);
  13353. /**
  13354. * AreaSplineSeries object
  13355. */
  13356. var areaProto = AreaSeries.prototype,
  13357. AreaSplineSeries = extendClass(SplineSeries, {
  13358. type: 'areaspline',
  13359. closedStacks: true, // instead of following the previous graph back, follow the threshold back
  13360. // Mix in methods from the area series
  13361. getSegmentPath: areaProto.getSegmentPath,
  13362. closeSegment: areaProto.closeSegment,
  13363. drawGraph: areaProto.drawGraph,
  13364. drawLegendSymbol: areaProto.drawLegendSymbol
  13365. });
  13366. seriesTypes.areaspline = AreaSplineSeries;
  13367. /**
  13368. * Set the default options for column
  13369. */
  13370. defaultPlotOptions.column = merge(defaultSeriesOptions, {
  13371. borderColor: '#FFFFFF',
  13372. borderWidth: 1,
  13373. borderRadius: 0,
  13374. //colorByPoint: undefined,
  13375. groupPadding: 0.2,
  13376. //grouping: true,
  13377. marker: null, // point options are specified in the base options
  13378. pointPadding: 0.1,
  13379. //pointWidth: null,
  13380. minPointLength: 0,
  13381. cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes
  13382. pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories
  13383. states: {
  13384. hover: {
  13385. brightness: 0.1,
  13386. shadow: false
  13387. },
  13388. select: {
  13389. color: '#C0C0C0',
  13390. borderColor: '#000000',
  13391. shadow: false
  13392. }
  13393. },
  13394. dataLabels: {
  13395. align: null, // auto
  13396. verticalAlign: null, // auto
  13397. y: null
  13398. },
  13399. stickyTracking: false,
  13400. threshold: 0
  13401. });
  13402. /**
  13403. * ColumnSeries object
  13404. */
  13405. var ColumnSeries = extendClass(Series, {
  13406. type: 'column',
  13407. pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
  13408. stroke: 'borderColor',
  13409. 'stroke-width': 'borderWidth',
  13410. fill: 'color',
  13411. r: 'borderRadius'
  13412. },
  13413. cropShoulder: 0,
  13414. trackerGroups: ['group', 'dataLabelsGroup'],
  13415. negStacks: true, // use separate negative stacks, unlike area stacks where a negative
  13416. // point is substracted from previous (#1910)
  13417. /**
  13418. * Initialize the series
  13419. */
  13420. init: function () {
  13421. Series.prototype.init.apply(this, arguments);
  13422. var series = this,
  13423. chart = series.chart;
  13424. // if the series is added dynamically, force redraw of other
  13425. // series affected by a new column
  13426. if (chart.hasRendered) {
  13427. each(chart.series, function (otherSeries) {
  13428. if (otherSeries.type === series.type) {
  13429. otherSeries.isDirty = true;
  13430. }
  13431. });
  13432. }
  13433. },
  13434. /**
  13435. * Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding,
  13436. * pointWidth etc.
  13437. */
  13438. getColumnMetrics: function () {
  13439. var series = this,
  13440. options = series.options,
  13441. xAxis = series.xAxis,
  13442. yAxis = series.yAxis,
  13443. reversedXAxis = xAxis.reversed,
  13444. stackKey,
  13445. stackGroups = {},
  13446. columnIndex,
  13447. columnCount = 0;
  13448. // Get the total number of column type series.
  13449. // This is called on every series. Consider moving this logic to a
  13450. // chart.orderStacks() function and call it on init, addSeries and removeSeries
  13451. if (options.grouping === false) {
  13452. columnCount = 1;
  13453. } else {
  13454. each(series.chart.series, function (otherSeries) {
  13455. var otherOptions = otherSeries.options,
  13456. otherYAxis = otherSeries.yAxis;
  13457. if (otherSeries.type === series.type && otherSeries.visible &&
  13458. yAxis.len === otherYAxis.len && yAxis.pos === otherYAxis.pos) { // #642, #2086
  13459. if (otherOptions.stacking) {
  13460. stackKey = otherSeries.stackKey;
  13461. if (stackGroups[stackKey] === UNDEFINED) {
  13462. stackGroups[stackKey] = columnCount++;
  13463. }
  13464. columnIndex = stackGroups[stackKey];
  13465. } else if (otherOptions.grouping !== false) { // #1162
  13466. columnIndex = columnCount++;
  13467. }
  13468. otherSeries.columnIndex = columnIndex;
  13469. }
  13470. });
  13471. }
  13472. var categoryWidth = mathMin(
  13473. mathAbs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || 1),
  13474. xAxis.len // #1535
  13475. ),
  13476. groupPadding = categoryWidth * options.groupPadding,
  13477. groupWidth = categoryWidth - 2 * groupPadding,
  13478. pointOffsetWidth = groupWidth / columnCount,
  13479. optionPointWidth = options.pointWidth,
  13480. pointPadding = defined(optionPointWidth) ? (pointOffsetWidth - optionPointWidth) / 2 :
  13481. pointOffsetWidth * options.pointPadding,
  13482. pointWidth = pick(optionPointWidth, pointOffsetWidth - 2 * pointPadding), // exact point width, used in polar charts
  13483. colIndex = (reversedXAxis ?
  13484. columnCount - (series.columnIndex || 0) : // #1251
  13485. series.columnIndex) || 0,
  13486. pointXOffset = pointPadding + (groupPadding + colIndex *
  13487. pointOffsetWidth - (categoryWidth / 2)) *
  13488. (reversedXAxis ? -1 : 1);
  13489. // Save it for reading in linked series (Error bars particularly)
  13490. return (series.columnMetrics = {
  13491. width: pointWidth,
  13492. offset: pointXOffset
  13493. });
  13494. },
  13495. /**
  13496. * Translate each point to the plot area coordinate system and find shape positions
  13497. */
  13498. translate: function () {
  13499. var series = this,
  13500. chart = series.chart,
  13501. options = series.options,
  13502. borderWidth = options.borderWidth,
  13503. yAxis = series.yAxis,
  13504. threshold = options.threshold,
  13505. translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold),
  13506. minPointLength = pick(options.minPointLength, 5),
  13507. metrics = series.getColumnMetrics(),
  13508. pointWidth = metrics.width,
  13509. seriesBarW = series.barW = mathCeil(mathMax(pointWidth, 1 + 2 * borderWidth)), // rounded and postprocessed for border width
  13510. pointXOffset = series.pointXOffset = metrics.offset,
  13511. xCrisp = -(borderWidth % 2 ? 0.5 : 0),
  13512. yCrisp = borderWidth % 2 ? 0.5 : 1;
  13513. if (chart.renderer.isVML && chart.inverted) {
  13514. yCrisp += 1;
  13515. }
  13516. Series.prototype.translate.apply(series);
  13517. // reconciliation the new values
  13518. each(series.points, function (point) {
  13519. var yBottom = pick(point.yBottom, translatedThreshold),
  13520. plotY = mathMin(mathMax(-999 - yBottom, point.plotY), yAxis.len + 999 + yBottom), // Don't draw too far outside plot area (#1303, #2241)
  13521. barX = point.plotX + pointXOffset,
  13522. barW = seriesBarW,
  13523. barY = mathMin(plotY, yBottom),
  13524. right,
  13525. bottom,
  13526. fromTop,
  13527. fromLeft,
  13528. barH = mathMax(plotY, yBottom) - barY;
  13529. // Handle options.minPointLength
  13530. if (mathAbs(barH) < minPointLength) {
  13531. if (minPointLength) {
  13532. barH = minPointLength;
  13533. barY =
  13534. mathRound(mathAbs(barY - translatedThreshold) > minPointLength ? // stacked
  13535. yBottom - minPointLength : // keep position
  13536. translatedThreshold - (yAxis.translate(point.y, 0, 1, 0, 1) <= translatedThreshold ? minPointLength : 0)); // use exact yAxis.translation (#1485)
  13537. }
  13538. }
  13539. // Cache for access in polar
  13540. point.barX = barX;
  13541. point.pointWidth = pointWidth;
  13542. // Round off to obtain crisp edges
  13543. fromLeft = mathAbs(barX) < 0.5;
  13544. right = mathRound(barX + barW) + xCrisp;
  13545. barX = mathRound(barX) + xCrisp;
  13546. barW = right - barX;
  13547. fromTop = mathAbs(barY) < 0.5;
  13548. bottom = mathRound(barY + barH) + yCrisp;
  13549. barY = mathRound(barY) + yCrisp;
  13550. barH = bottom - barY;
  13551. // Top and left edges are exceptions
  13552. if (fromLeft) {
  13553. barX += 1;
  13554. barW -= 1;
  13555. }
  13556. if (fromTop) {
  13557. barY -= 1;
  13558. barH += 1;
  13559. }
  13560. // Register shape type and arguments to be used in drawPoints
  13561. point.shapeType = 'rect';
  13562. point.shapeArgs = {
  13563. x: barX,
  13564. y: barY,
  13565. width: barW,
  13566. height: barH
  13567. };
  13568. });
  13569. },
  13570. getSymbol: noop,
  13571. /**
  13572. * Use a solid rectangle like the area series types
  13573. */
  13574. drawLegendSymbol: AreaSeries.prototype.drawLegendSymbol,
  13575. /**
  13576. * Columns have no graph
  13577. */
  13578. drawGraph: noop,
  13579. /**
  13580. * Draw the columns. For bars, the series.group is rotated, so the same coordinates
  13581. * apply for columns and bars. This method is inherited by scatter series.
  13582. *
  13583. */
  13584. drawPoints: function () {
  13585. var series = this,
  13586. options = series.options,
  13587. renderer = series.chart.renderer,
  13588. shapeArgs;
  13589. // draw the columns
  13590. each(series.points, function (point) {
  13591. var plotY = point.plotY,
  13592. graphic = point.graphic;
  13593. if (plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) {
  13594. shapeArgs = point.shapeArgs;
  13595. if (graphic) { // update
  13596. stop(graphic);
  13597. graphic.animate(merge(shapeArgs));
  13598. } else {
  13599. point.graphic = graphic = renderer[point.shapeType](shapeArgs)
  13600. .attr(point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE])
  13601. .add(series.group)
  13602. .shadow(options.shadow, null, options.stacking && !options.borderRadius);
  13603. }
  13604. } else if (graphic) {
  13605. point.graphic = graphic.destroy(); // #1269
  13606. }
  13607. });
  13608. },
  13609. /**
  13610. * Add tracking event listener to the series group, so the point graphics
  13611. * themselves act as trackers
  13612. */
  13613. drawTracker: function () {
  13614. var series = this,
  13615. chart = series.chart,
  13616. pointer = chart.pointer,
  13617. cursor = series.options.cursor,
  13618. css = cursor && { cursor: cursor },
  13619. onMouseOver = function (e) {
  13620. var target = e.target,
  13621. point;
  13622. if (chart.hoverSeries !== series) {
  13623. series.onMouseOver();
  13624. }
  13625. while (target && !point) {
  13626. point = target.point;
  13627. target = target.parentNode;
  13628. }
  13629. if (point !== UNDEFINED && point !== chart.hoverPoint) { // undefined on graph in scatterchart
  13630. point.onMouseOver(e);
  13631. }
  13632. };
  13633. // Add reference to the point
  13634. each(series.points, function (point) {
  13635. if (point.graphic) {
  13636. point.graphic.element.point = point;
  13637. }
  13638. if (point.dataLabel) {
  13639. point.dataLabel.element.point = point;
  13640. }
  13641. });
  13642. // Add the event listeners, we need to do this only once
  13643. if (!series._hasTracking) {
  13644. each(series.trackerGroups, function (key) {
  13645. if (series[key]) { // we don't always have dataLabelsGroup
  13646. series[key]
  13647. .addClass(PREFIX + 'tracker')
  13648. .on('mouseover', onMouseOver)
  13649. .on('mouseout', function (e) { pointer.onTrackerMouseOut(e); })
  13650. .css(css);
  13651. if (hasTouch) {
  13652. series[key].on('touchstart', onMouseOver);
  13653. }
  13654. }
  13655. });
  13656. series._hasTracking = true;
  13657. }
  13658. },
  13659. /**
  13660. * Override the basic data label alignment by adjusting for the position of the column
  13661. */
  13662. alignDataLabel: function (point, dataLabel, options, alignTo, isNew) {
  13663. var chart = this.chart,
  13664. inverted = chart.inverted,
  13665. dlBox = point.dlBox || point.shapeArgs, // data label box for alignment
  13666. below = point.below || (point.plotY > pick(this.translatedThreshold, chart.plotSizeY)),
  13667. inside = pick(options.inside, !!this.options.stacking); // draw it inside the box?
  13668. // Align to the column itself, or the top of it
  13669. if (dlBox) { // Area range uses this method but not alignTo
  13670. alignTo = merge(dlBox);
  13671. if (inverted) {
  13672. alignTo = {
  13673. x: chart.plotWidth - alignTo.y - alignTo.height,
  13674. y: chart.plotHeight - alignTo.x - alignTo.width,
  13675. width: alignTo.height,
  13676. height: alignTo.width
  13677. };
  13678. }
  13679. // Compute the alignment box
  13680. if (!inside) {
  13681. if (inverted) {
  13682. alignTo.x += below ? 0 : alignTo.width;
  13683. alignTo.width = 0;
  13684. } else {
  13685. alignTo.y += below ? alignTo.height : 0;
  13686. alignTo.height = 0;
  13687. }
  13688. }
  13689. }
  13690. // When alignment is undefined (typically columns and bars), display the individual
  13691. // point below or above the point depending on the threshold
  13692. options.align = pick(
  13693. options.align,
  13694. !inverted || inside ? 'center' : below ? 'right' : 'left'
  13695. );
  13696. options.verticalAlign = pick(
  13697. options.verticalAlign,
  13698. inverted || inside ? 'middle' : below ? 'top' : 'bottom'
  13699. );
  13700. // Call the parent method
  13701. Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew);
  13702. },
  13703. /**
  13704. * Animate the column heights one by one from zero
  13705. * @param {Boolean} init Whether to initialize the animation or run it
  13706. */
  13707. animate: function (init) {
  13708. var series = this,
  13709. yAxis = this.yAxis,
  13710. options = series.options,
  13711. inverted = this.chart.inverted,
  13712. attr = {},
  13713. translatedThreshold;
  13714. if (hasSVG) { // VML is too slow anyway
  13715. if (init) {
  13716. attr.scaleY = 0.001;
  13717. translatedThreshold = mathMin(yAxis.pos + yAxis.len, mathMax(yAxis.pos, yAxis.toPixels(options.threshold)));
  13718. if (inverted) {
  13719. attr.translateX = translatedThreshold - yAxis.len;
  13720. } else {
  13721. attr.translateY = translatedThreshold;
  13722. }
  13723. series.group.attr(attr);
  13724. } else { // run the animation
  13725. attr.scaleY = 1;
  13726. attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos;
  13727. series.group.animate(attr, series.options.animation);
  13728. // delete this function to allow it only once
  13729. series.animate = null;
  13730. }
  13731. }
  13732. },
  13733. /**
  13734. * Remove this series from the chart
  13735. */
  13736. remove: function () {
  13737. var series = this,
  13738. chart = series.chart;
  13739. // column and bar series affects other series of the same type
  13740. // as they are either stacked or grouped
  13741. if (chart.hasRendered) {
  13742. each(chart.series, function (otherSeries) {
  13743. if (otherSeries.type === series.type) {
  13744. otherSeries.isDirty = true;
  13745. }
  13746. });
  13747. }
  13748. Series.prototype.remove.apply(series, arguments);
  13749. }
  13750. });
  13751. seriesTypes.column = ColumnSeries;
  13752. /**
  13753. * Set the default options for bar
  13754. */
  13755. defaultPlotOptions.bar = merge(defaultPlotOptions.column);
  13756. /**
  13757. * The Bar series class
  13758. */
  13759. var BarSeries = extendClass(ColumnSeries, {
  13760. type: 'bar',
  13761. inverted: true
  13762. });
  13763. seriesTypes.bar = BarSeries;
  13764. /**
  13765. * Set the default options for scatter
  13766. */
  13767. defaultPlotOptions.scatter = merge(defaultSeriesOptions, {
  13768. lineWidth: 0,
  13769. tooltip: {
  13770. headerFormat: '<span style="font-size: 10px; color:{series.color}">{series.name}</span><br/>',
  13771. pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>',
  13772. followPointer: true
  13773. },
  13774. stickyTracking: false
  13775. });
  13776. /**
  13777. * The scatter series class
  13778. */
  13779. var ScatterSeries = extendClass(Series, {
  13780. type: 'scatter',
  13781. sorted: false,
  13782. requireSorting: false,
  13783. noSharedTooltip: true,
  13784. trackerGroups: ['markerGroup'],
  13785. drawTracker: ColumnSeries.prototype.drawTracker,
  13786. setTooltipPoints: noop
  13787. });
  13788. seriesTypes.scatter = ScatterSeries;
  13789. /**
  13790. * Set the default options for pie
  13791. */
  13792. defaultPlotOptions.pie = merge(defaultSeriesOptions, {
  13793. borderColor: '#FFFFFF',
  13794. borderWidth: 1,
  13795. center: [null, null],
  13796. clip: false,
  13797. colorByPoint: true, // always true for pies
  13798. dataLabels: {
  13799. // align: null,
  13800. // connectorWidth: 1,
  13801. // connectorColor: point.color,
  13802. // connectorPadding: 5,
  13803. distance: 30,
  13804. enabled: true,
  13805. formatter: function () {
  13806. return this.point.name;
  13807. }
  13808. // softConnector: true,
  13809. //y: 0
  13810. },
  13811. ignoreHiddenPoint: true,
  13812. //innerSize: 0,
  13813. legendType: 'point',
  13814. marker: null, // point options are specified in the base options
  13815. size: null,
  13816. showInLegend: false,
  13817. slicedOffset: 10,
  13818. states: {
  13819. hover: {
  13820. brightness: 0.1,
  13821. shadow: false
  13822. }
  13823. },
  13824. stickyTracking: false,
  13825. tooltip: {
  13826. followPointer: true
  13827. }
  13828. });
  13829. /**
  13830. * Extended point object for pies
  13831. */
  13832. var PiePoint = extendClass(Point, {
  13833. /**
  13834. * Initiate the pie slice
  13835. */
  13836. init: function () {
  13837. Point.prototype.init.apply(this, arguments);
  13838. var point = this,
  13839. toggleSlice;
  13840. // Disallow negative values (#1530)
  13841. if (point.y < 0) {
  13842. point.y = null;
  13843. }
  13844. //visible: options.visible !== false,
  13845. extend(point, {
  13846. visible: point.visible !== false,
  13847. name: pick(point.name, 'Slice')
  13848. });
  13849. // add event listener for select
  13850. toggleSlice = function (e) {
  13851. point.slice(e.type === 'select');
  13852. };
  13853. addEvent(point, 'select', toggleSlice);
  13854. addEvent(point, 'unselect', toggleSlice);
  13855. return point;
  13856. },
  13857. /**
  13858. * Toggle the visibility of the pie slice
  13859. * @param {Boolean} vis Whether to show the slice or not. If undefined, the
  13860. * visibility is toggled
  13861. */
  13862. setVisible: function (vis) {
  13863. var point = this,
  13864. series = point.series,
  13865. chart = series.chart,
  13866. method;
  13867. // if called without an argument, toggle visibility
  13868. point.visible = point.options.visible = vis = vis === UNDEFINED ? !point.visible : vis;
  13869. series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data
  13870. method = vis ? 'show' : 'hide';
  13871. // Show and hide associated elements
  13872. each(['graphic', 'dataLabel', 'connector', 'shadowGroup'], function (key) {
  13873. if (point[key]) {
  13874. point[key][method]();
  13875. }
  13876. });
  13877. if (point.legendItem) {
  13878. chart.legend.colorizeItem(point, vis);
  13879. }
  13880. // Handle ignore hidden slices
  13881. if (!series.isDirty && series.options.ignoreHiddenPoint) {
  13882. series.isDirty = true;
  13883. chart.redraw();
  13884. }
  13885. },
  13886. /**
  13887. * Set or toggle whether the slice is cut out from the pie
  13888. * @param {Boolean} sliced When undefined, the slice state is toggled
  13889. * @param {Boolean} redraw Whether to redraw the chart. True by default.
  13890. */
  13891. slice: function (sliced, redraw, animation) {
  13892. var point = this,
  13893. series = point.series,
  13894. chart = series.chart,
  13895. translation;
  13896. setAnimation(animation, chart);
  13897. // redraw is true by default
  13898. redraw = pick(redraw, true);
  13899. // if called without an argument, toggle
  13900. point.sliced = point.options.sliced = sliced = defined(sliced) ? sliced : !point.sliced;
  13901. series.options.data[inArray(point, series.data)] = point.options; // update userOptions.data
  13902. translation = sliced ? point.slicedTranslation : {
  13903. translateX: 0,
  13904. translateY: 0
  13905. };
  13906. point.graphic.animate(translation);
  13907. if (point.shadowGroup) {
  13908. point.shadowGroup.animate(translation);
  13909. }
  13910. }
  13911. });
  13912. /**
  13913. * The Pie series class
  13914. */
  13915. var PieSeries = {
  13916. type: 'pie',
  13917. isCartesian: false,
  13918. pointClass: PiePoint,
  13919. requireSorting: false,
  13920. noSharedTooltip: true,
  13921. trackerGroups: ['group', 'dataLabelsGroup'],
  13922. pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
  13923. stroke: 'borderColor',
  13924. 'stroke-width': 'borderWidth',
  13925. fill: 'color'
  13926. },
  13927. /**
  13928. * Pies have one color each point
  13929. */
  13930. getColor: noop,
  13931. /**
  13932. * Animate the pies in
  13933. */
  13934. animate: function (init) {
  13935. var series = this,
  13936. points = series.points,
  13937. startAngleRad = series.startAngleRad;
  13938. if (!init) {
  13939. each(points, function (point) {
  13940. var graphic = point.graphic,
  13941. args = point.shapeArgs;
  13942. if (graphic) {
  13943. // start values
  13944. graphic.attr({
  13945. r: series.center[3] / 2, // animate from inner radius (#779)
  13946. start: startAngleRad,
  13947. end: startAngleRad
  13948. });
  13949. // animate
  13950. graphic.animate({
  13951. r: args.r,
  13952. start: args.start,
  13953. end: args.end
  13954. }, series.options.animation);
  13955. }
  13956. });
  13957. // delete this function to allow it only once
  13958. series.animate = null;
  13959. }
  13960. },
  13961. /**
  13962. * Extend the basic setData method by running processData and generatePoints immediately,
  13963. * in order to access the points from the legend.
  13964. */
  13965. setData: function (data, redraw) {
  13966. Series.prototype.setData.call(this, data, false);
  13967. this.processData();
  13968. this.generatePoints();
  13969. if (pick(redraw, true)) {
  13970. this.chart.redraw();
  13971. }
  13972. },
  13973. /**
  13974. * Extend the generatePoints method by adding total and percentage properties to each point
  13975. */
  13976. generatePoints: function () {
  13977. var i,
  13978. total = 0,
  13979. points,
  13980. len,
  13981. point,
  13982. ignoreHiddenPoint = this.options.ignoreHiddenPoint;
  13983. Series.prototype.generatePoints.call(this);
  13984. // Populate local vars
  13985. points = this.points;
  13986. len = points.length;
  13987. // Get the total sum
  13988. for (i = 0; i < len; i++) {
  13989. point = points[i];
  13990. total += (ignoreHiddenPoint && !point.visible) ? 0 : point.y;
  13991. }
  13992. this.total = total;
  13993. // Set each point's properties
  13994. for (i = 0; i < len; i++) {
  13995. point = points[i];
  13996. point.percentage = total > 0 ? (point.y / total) * 100 : 0;
  13997. point.total = total;
  13998. }
  13999. },
  14000. /**
  14001. * Get the center of the pie based on the size and center options relative to the
  14002. * plot area. Borrowed by the polar and gauge series types.
  14003. */
  14004. getCenter: function () {
  14005. var options = this.options,
  14006. chart = this.chart,
  14007. slicingRoom = 2 * (options.slicedOffset || 0),
  14008. handleSlicingRoom,
  14009. plotWidth = chart.plotWidth - 2 * slicingRoom,
  14010. plotHeight = chart.plotHeight - 2 * slicingRoom,
  14011. centerOption = options.center,
  14012. positions = [pick(centerOption[0], '50%'), pick(centerOption[1], '50%'), options.size || '100%', options.innerSize || 0],
  14013. smallestSize = mathMin(plotWidth, plotHeight),
  14014. isPercent;
  14015. return map(positions, function (length, i) {
  14016. isPercent = /%$/.test(length);
  14017. handleSlicingRoom = i < 2 || (i === 2 && isPercent);
  14018. return (isPercent ?
  14019. // i == 0: centerX, relative to width
  14020. // i == 1: centerY, relative to height
  14021. // i == 2: size, relative to smallestSize
  14022. // i == 4: innerSize, relative to smallestSize
  14023. [plotWidth, plotHeight, smallestSize, smallestSize][i] *
  14024. pInt(length) / 100 :
  14025. length) + (handleSlicingRoom ? slicingRoom : 0);
  14026. });
  14027. },
  14028. /**
  14029. * Do translation for pie slices
  14030. */
  14031. translate: function (positions) {
  14032. this.generatePoints();
  14033. var series = this,
  14034. cumulative = 0,
  14035. precision = 1000, // issue #172
  14036. options = series.options,
  14037. slicedOffset = options.slicedOffset,
  14038. connectorOffset = slicedOffset + options.borderWidth,
  14039. start,
  14040. end,
  14041. angle,
  14042. startAngle = options.startAngle || 0,
  14043. startAngleRad = series.startAngleRad = mathPI / 180 * (startAngle - 90),
  14044. endAngleRad = series.endAngleRad = mathPI / 180 * ((options.endAngle || (startAngle + 360)) - 90), // docs
  14045. circ = endAngleRad - startAngleRad, //2 * mathPI,
  14046. points = series.points,
  14047. radiusX, // the x component of the radius vector for a given point
  14048. radiusY,
  14049. labelDistance = options.dataLabels.distance,
  14050. ignoreHiddenPoint = options.ignoreHiddenPoint,
  14051. i,
  14052. len = points.length,
  14053. point;
  14054. // Get positions - either an integer or a percentage string must be given.
  14055. // If positions are passed as a parameter, we're in a recursive loop for adjusting
  14056. // space for data labels.
  14057. if (!positions) {
  14058. series.center = positions = series.getCenter();
  14059. }
  14060. // utility for getting the x value from a given y, used for anticollision logic in data labels
  14061. series.getX = function (y, left) {
  14062. angle = math.asin((y - positions[1]) / (positions[2] / 2 + labelDistance));
  14063. return positions[0] +
  14064. (left ? -1 : 1) *
  14065. (mathCos(angle) * (positions[2] / 2 + labelDistance));
  14066. };
  14067. // Calculate the geometry for each point
  14068. for (i = 0; i < len; i++) {
  14069. point = points[i];
  14070. // set start and end angle
  14071. start = startAngleRad + (cumulative * circ);
  14072. if (!ignoreHiddenPoint || point.visible) {
  14073. cumulative += point.percentage / 100;
  14074. }
  14075. end = startAngleRad + (cumulative * circ);
  14076. // set the shape
  14077. point.shapeType = 'arc';
  14078. point.shapeArgs = {
  14079. x: positions[0],
  14080. y: positions[1],
  14081. r: positions[2] / 2,
  14082. innerR: positions[3] / 2,
  14083. start: mathRound(start * precision) / precision,
  14084. end: mathRound(end * precision) / precision
  14085. };
  14086. // center for the sliced out slice
  14087. angle = (end + start) / 2;
  14088. if (angle > 0.75 * circ) {
  14089. angle -= 2 * mathPI;
  14090. }
  14091. point.slicedTranslation = {
  14092. translateX: mathRound(mathCos(angle) * slicedOffset),
  14093. translateY: mathRound(mathSin(angle) * slicedOffset)
  14094. };
  14095. // set the anchor point for tooltips
  14096. radiusX = mathCos(angle) * positions[2] / 2;
  14097. radiusY = mathSin(angle) * positions[2] / 2;
  14098. point.tooltipPos = [
  14099. positions[0] + radiusX * 0.7,
  14100. positions[1] + radiusY * 0.7
  14101. ];
  14102. point.half = angle < -mathPI / 2 || angle > mathPI / 2 ? 1 : 0;
  14103. point.angle = angle;
  14104. // set the anchor point for data labels
  14105. connectorOffset = mathMin(connectorOffset, labelDistance / 2); // #1678
  14106. point.labelPos = [
  14107. positions[0] + radiusX + mathCos(angle) * labelDistance, // first break of connector
  14108. positions[1] + radiusY + mathSin(angle) * labelDistance, // a/a
  14109. positions[0] + radiusX + mathCos(angle) * connectorOffset, // second break, right outside pie
  14110. positions[1] + radiusY + mathSin(angle) * connectorOffset, // a/a
  14111. positions[0] + radiusX, // landing point for connector
  14112. positions[1] + radiusY, // a/a
  14113. labelDistance < 0 ? // alignment
  14114. 'center' :
  14115. point.half ? 'right' : 'left', // alignment
  14116. angle // center angle
  14117. ];
  14118. }
  14119. },
  14120. setTooltipPoints: noop,
  14121. drawGraph: null,
  14122. /**
  14123. * Draw the data points
  14124. */
  14125. drawPoints: function () {
  14126. var series = this,
  14127. chart = series.chart,
  14128. renderer = chart.renderer,
  14129. groupTranslation,
  14130. //center,
  14131. graphic,
  14132. //group,
  14133. shadow = series.options.shadow,
  14134. shadowGroup,
  14135. shapeArgs;
  14136. if (shadow && !series.shadowGroup) {
  14137. series.shadowGroup = renderer.g('shadow')
  14138. .add(series.group);
  14139. }
  14140. // draw the slices
  14141. each(series.points, function (point) {
  14142. graphic = point.graphic;
  14143. shapeArgs = point.shapeArgs;
  14144. shadowGroup = point.shadowGroup;
  14145. // put the shadow behind all points
  14146. if (shadow && !shadowGroup) {
  14147. shadowGroup = point.shadowGroup = renderer.g('shadow')
  14148. .add(series.shadowGroup);
  14149. }
  14150. // if the point is sliced, use special translation, else use plot area traslation
  14151. groupTranslation = point.sliced ? point.slicedTranslation : {
  14152. translateX: 0,
  14153. translateY: 0
  14154. };
  14155. //group.translate(groupTranslation[0], groupTranslation[1]);
  14156. if (shadowGroup) {
  14157. shadowGroup.attr(groupTranslation);
  14158. }
  14159. // draw the slice
  14160. if (graphic) {
  14161. graphic.animate(extend(shapeArgs, groupTranslation));
  14162. } else {
  14163. point.graphic = graphic = renderer.arc(shapeArgs)
  14164. .setRadialReference(series.center)
  14165. .attr(
  14166. point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE]
  14167. )
  14168. .attr({ 'stroke-linejoin': 'round' })
  14169. .attr(groupTranslation)
  14170. .add(series.group)
  14171. .shadow(shadow, shadowGroup);
  14172. }
  14173. // detect point specific visibility
  14174. if (point.visible === false) {
  14175. point.setVisible(false);
  14176. }
  14177. });
  14178. },
  14179. /**
  14180. * Utility for sorting data labels
  14181. */
  14182. sortByAngle: function (points, sign) {
  14183. points.sort(function (a, b) {
  14184. return a.angle !== undefined && (b.angle - a.angle) * sign;
  14185. });
  14186. },
  14187. /**
  14188. * Override the base drawDataLabels method by pie specific functionality
  14189. */
  14190. drawDataLabels: function () {
  14191. var series = this,
  14192. data = series.data,
  14193. point,
  14194. chart = series.chart,
  14195. options = series.options.dataLabels,
  14196. connectorPadding = pick(options.connectorPadding, 10),
  14197. connectorWidth = pick(options.connectorWidth, 1),
  14198. plotWidth = chart.plotWidth,
  14199. plotHeight = chart.plotHeight,
  14200. connector,
  14201. connectorPath,
  14202. softConnector = pick(options.softConnector, true),
  14203. distanceOption = options.distance,
  14204. seriesCenter = series.center,
  14205. radius = seriesCenter[2] / 2,
  14206. centerY = seriesCenter[1],
  14207. outside = distanceOption > 0,
  14208. dataLabel,
  14209. dataLabelWidth,
  14210. labelPos,
  14211. labelHeight,
  14212. halves = [// divide the points into right and left halves for anti collision
  14213. [], // right
  14214. [] // left
  14215. ],
  14216. x,
  14217. y,
  14218. visibility,
  14219. rankArr,
  14220. i,
  14221. j,
  14222. overflow = [0, 0, 0, 0], // top, right, bottom, left
  14223. sort = function (a, b) {
  14224. return b.y - a.y;
  14225. };
  14226. // get out if not enabled
  14227. if (!series.visible || (!options.enabled && !series._hasPointLabels)) {
  14228. return;
  14229. }
  14230. // run parent method
  14231. Series.prototype.drawDataLabels.apply(series);
  14232. // arrange points for detection collision
  14233. each(data, function (point) {
  14234. if (point.dataLabel) { // it may have been cancelled in the base method (#407)
  14235. halves[point.half].push(point);
  14236. }
  14237. });
  14238. // assume equal label heights
  14239. i = 0;
  14240. while (!labelHeight && data[i]) { // #1569
  14241. labelHeight = data[i] && data[i].dataLabel && (data[i].dataLabel.getBBox().height || 21); // 21 is for #968
  14242. i++;
  14243. }
  14244. /* Loop over the points in each half, starting from the top and bottom
  14245. * of the pie to detect overlapping labels.
  14246. */
  14247. i = 2;
  14248. while (i--) {
  14249. var slots = [],
  14250. slotsLength,
  14251. usedSlots = [],
  14252. points = halves[i],
  14253. pos,
  14254. length = points.length,
  14255. slotIndex;
  14256. // Sort by angle
  14257. series.sortByAngle(points, i - 0.5);
  14258. // Only do anti-collision when we are outside the pie and have connectors (#856)
  14259. if (distanceOption > 0) {
  14260. // build the slots
  14261. for (pos = centerY - radius - distanceOption; pos <= centerY + radius + distanceOption; pos += labelHeight) {
  14262. slots.push(pos);
  14263. // visualize the slot
  14264. /*
  14265. var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0),
  14266. slotY = pos + chart.plotTop;
  14267. if (!isNaN(slotX)) {
  14268. chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1)
  14269. .attr({
  14270. 'stroke-width': 1,
  14271. stroke: 'silver'
  14272. })
  14273. .add();
  14274. chart.renderer.text('Slot '+ (slots.length - 1), slotX, slotY + 4)
  14275. .attr({
  14276. fill: 'silver'
  14277. }).add();
  14278. }
  14279. */
  14280. }
  14281. slotsLength = slots.length;
  14282. // if there are more values than available slots, remove lowest values
  14283. if (length > slotsLength) {
  14284. // create an array for sorting and ranking the points within each quarter
  14285. rankArr = [].concat(points);
  14286. rankArr.sort(sort);
  14287. j = length;
  14288. while (j--) {
  14289. rankArr[j].rank = j;
  14290. }
  14291. j = length;
  14292. while (j--) {
  14293. if (points[j].rank >= slotsLength) {
  14294. points.splice(j, 1);
  14295. }
  14296. }
  14297. length = points.length;
  14298. }
  14299. // The label goes to the nearest open slot, but not closer to the edge than
  14300. // the label's index.
  14301. for (j = 0; j < length; j++) {
  14302. point = points[j];
  14303. labelPos = point.labelPos;
  14304. var closest = 9999,
  14305. distance,
  14306. slotI;
  14307. // find the closest slot index
  14308. for (slotI = 0; slotI < slotsLength; slotI++) {
  14309. distance = mathAbs(slots[slotI] - labelPos[1]);
  14310. if (distance < closest) {
  14311. closest = distance;
  14312. slotIndex = slotI;
  14313. }
  14314. }
  14315. // if that slot index is closer to the edges of the slots, move it
  14316. // to the closest appropriate slot
  14317. if (slotIndex < j && slots[j] !== null) { // cluster at the top
  14318. slotIndex = j;
  14319. } else if (slotsLength < length - j + slotIndex && slots[j] !== null) { // cluster at the bottom
  14320. slotIndex = slotsLength - length + j;
  14321. while (slots[slotIndex] === null) { // make sure it is not taken
  14322. slotIndex++;
  14323. }
  14324. } else {
  14325. // Slot is taken, find next free slot below. In the next run, the next slice will find the
  14326. // slot above these, because it is the closest one
  14327. while (slots[slotIndex] === null) { // make sure it is not taken
  14328. slotIndex++;
  14329. }
  14330. }
  14331. usedSlots.push({ i: slotIndex, y: slots[slotIndex] });
  14332. slots[slotIndex] = null; // mark as taken
  14333. }
  14334. // sort them in order to fill in from the top
  14335. usedSlots.sort(sort);
  14336. }
  14337. // now the used slots are sorted, fill them up sequentially
  14338. for (j = 0; j < length; j++) {
  14339. var slot, naturalY;
  14340. point = points[j];
  14341. labelPos = point.labelPos;
  14342. dataLabel = point.dataLabel;
  14343. visibility = point.visible === false ? HIDDEN : VISIBLE;
  14344. naturalY = labelPos[1];
  14345. if (distanceOption > 0) {
  14346. slot = usedSlots.pop();
  14347. slotIndex = slot.i;
  14348. // if the slot next to currrent slot is free, the y value is allowed
  14349. // to fall back to the natural position
  14350. y = slot.y;
  14351. if ((naturalY > y && slots[slotIndex + 1] !== null) ||
  14352. (naturalY < y && slots[slotIndex - 1] !== null)) {
  14353. y = naturalY;
  14354. }
  14355. } else {
  14356. y = naturalY;
  14357. }
  14358. // get the x - use the natural x position for first and last slot, to prevent the top
  14359. // and botton slice connectors from touching each other on either side
  14360. x = options.justify ?
  14361. seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption) :
  14362. series.getX(slotIndex === 0 || slotIndex === slots.length - 1 ? naturalY : y, i);
  14363. // Record the placement and visibility
  14364. dataLabel._attr = {
  14365. visibility: visibility,
  14366. align: labelPos[6]
  14367. };
  14368. dataLabel._pos = {
  14369. x: x + options.x +
  14370. ({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0),
  14371. y: y + options.y - 10 // 10 is for the baseline (label vs text)
  14372. };
  14373. dataLabel.connX = x;
  14374. dataLabel.connY = y;
  14375. // Detect overflowing data labels
  14376. if (this.options.size === null) {
  14377. dataLabelWidth = dataLabel.width;
  14378. // Overflow left
  14379. if (x - dataLabelWidth < connectorPadding) {
  14380. overflow[3] = mathMax(mathRound(dataLabelWidth - x + connectorPadding), overflow[3]);
  14381. // Overflow right
  14382. } else if (x + dataLabelWidth > plotWidth - connectorPadding) {
  14383. overflow[1] = mathMax(mathRound(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]);
  14384. }
  14385. // Overflow top
  14386. if (y - labelHeight / 2 < 0) {
  14387. overflow[0] = mathMax(mathRound(-y + labelHeight / 2), overflow[0]);
  14388. // Overflow left
  14389. } else if (y + labelHeight / 2 > plotHeight) {
  14390. overflow[2] = mathMax(mathRound(y + labelHeight / 2 - plotHeight), overflow[2]);
  14391. }
  14392. }
  14393. } // for each point
  14394. } // for each half
  14395. // Do not apply the final placement and draw the connectors until we have verified
  14396. // that labels are not spilling over.
  14397. if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) {
  14398. // Place the labels in the final position
  14399. this.placeDataLabels();
  14400. // Draw the connectors
  14401. if (outside && connectorWidth) {
  14402. each(this.points, function (point) {
  14403. connector = point.connector;
  14404. labelPos = point.labelPos;
  14405. dataLabel = point.dataLabel;
  14406. if (dataLabel && dataLabel._pos) {
  14407. visibility = dataLabel._attr.visibility;
  14408. x = dataLabel.connX;
  14409. y = dataLabel.connY;
  14410. connectorPath = softConnector ? [
  14411. M,
  14412. x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
  14413. 'C',
  14414. x, y, // first break, next to the label
  14415. 2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5],
  14416. labelPos[2], labelPos[3], // second break
  14417. L,
  14418. labelPos[4], labelPos[5] // base
  14419. ] : [
  14420. M,
  14421. x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
  14422. L,
  14423. labelPos[2], labelPos[3], // second break
  14424. L,
  14425. labelPos[4], labelPos[5] // base
  14426. ];
  14427. if (connector) {
  14428. connector.animate({ d: connectorPath });
  14429. connector.attr('visibility', visibility);
  14430. } else {
  14431. point.connector = connector = series.chart.renderer.path(connectorPath).attr({
  14432. 'stroke-width': connectorWidth,
  14433. stroke: options.connectorColor || point.color || '#606060',
  14434. visibility: visibility
  14435. })
  14436. .add(series.group);
  14437. }
  14438. } else if (connector) {
  14439. point.connector = connector.destroy();
  14440. }
  14441. });
  14442. }
  14443. }
  14444. },
  14445. /**
  14446. * Verify whether the data labels are allowed to draw, or we should run more translation and data
  14447. * label positioning to keep them inside the plot area. Returns true when data labels are ready
  14448. * to draw.
  14449. */
  14450. verifyDataLabelOverflow: function (overflow) {
  14451. var center = this.center,
  14452. options = this.options,
  14453. centerOption = options.center,
  14454. minSize = options.minSize || 80,
  14455. newSize = minSize,
  14456. ret;
  14457. // Handle horizontal size and center
  14458. if (centerOption[0] !== null) { // Fixed center
  14459. newSize = mathMax(center[2] - mathMax(overflow[1], overflow[3]), minSize);
  14460. } else { // Auto center
  14461. newSize = mathMax(
  14462. center[2] - overflow[1] - overflow[3], // horizontal overflow
  14463. minSize
  14464. );
  14465. center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center
  14466. }
  14467. // Handle vertical size and center
  14468. if (centerOption[1] !== null) { // Fixed center
  14469. newSize = mathMax(mathMin(newSize, center[2] - mathMax(overflow[0], overflow[2])), minSize);
  14470. } else { // Auto center
  14471. newSize = mathMax(
  14472. mathMin(
  14473. newSize,
  14474. center[2] - overflow[0] - overflow[2] // vertical overflow
  14475. ),
  14476. minSize
  14477. );
  14478. center[1] += (overflow[0] - overflow[2]) / 2; // vertical center
  14479. }
  14480. // If the size must be decreased, we need to run translate and drawDataLabels again
  14481. if (newSize < center[2]) {
  14482. center[2] = newSize;
  14483. this.translate(center);
  14484. each(this.points, function (point) {
  14485. if (point.dataLabel) {
  14486. point.dataLabel._pos = null; // reset
  14487. }
  14488. });
  14489. this.drawDataLabels();
  14490. // Else, return true to indicate that the pie and its labels is within the plot area
  14491. } else {
  14492. ret = true;
  14493. }
  14494. return ret;
  14495. },
  14496. /**
  14497. * Perform the final placement of the data labels after we have verified that they
  14498. * fall within the plot area.
  14499. */
  14500. placeDataLabels: function () {
  14501. each(this.points, function (point) {
  14502. var dataLabel = point.dataLabel,
  14503. _pos;
  14504. if (dataLabel) {
  14505. _pos = dataLabel._pos;
  14506. if (_pos) {
  14507. dataLabel.attr(dataLabel._attr);
  14508. dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos);
  14509. dataLabel.moved = true;
  14510. } else if (dataLabel) {
  14511. dataLabel.attr({ y: -999 });
  14512. }
  14513. }
  14514. });
  14515. },
  14516. alignDataLabel: noop,
  14517. /**
  14518. * Draw point specific tracker objects. Inherit directly from column series.
  14519. */
  14520. drawTracker: ColumnSeries.prototype.drawTracker,
  14521. /**
  14522. * Use a simple symbol from column prototype
  14523. */
  14524. drawLegendSymbol: AreaSeries.prototype.drawLegendSymbol,
  14525. /**
  14526. * Pies don't have point marker symbols
  14527. */
  14528. getSymbol: noop
  14529. };
  14530. PieSeries = extendClass(Series, PieSeries);
  14531. seriesTypes.pie = PieSeries;
  14532. // global variables
  14533. extend(Highcharts, {
  14534. // Constructors
  14535. Axis: Axis,
  14536. Chart: Chart,
  14537. Color: Color,
  14538. Legend: Legend,
  14539. Pointer: Pointer,
  14540. Point: Point,
  14541. Tick: Tick,
  14542. Tooltip: Tooltip,
  14543. Renderer: Renderer,
  14544. Series: Series,
  14545. SVGElement: SVGElement,
  14546. SVGRenderer: SVGRenderer,
  14547. // Various
  14548. arrayMin: arrayMin,
  14549. arrayMax: arrayMax,
  14550. charts: charts,
  14551. dateFormat: dateFormat,
  14552. format: format,
  14553. pathAnim: pathAnim,
  14554. getOptions: getOptions,
  14555. hasBidiBug: hasBidiBug,
  14556. isTouchDevice: isTouchDevice,
  14557. numberFormat: numberFormat,
  14558. seriesTypes: seriesTypes,
  14559. setOptions: setOptions,
  14560. addEvent: addEvent,
  14561. removeEvent: removeEvent,
  14562. createElement: createElement,
  14563. discardElement: discardElement,
  14564. css: css,
  14565. each: each,
  14566. extend: extend,
  14567. map: map,
  14568. merge: merge,
  14569. pick: pick,
  14570. splat: splat,
  14571. extendClass: extendClass,
  14572. pInt: pInt,
  14573. wrap: wrap,
  14574. svg: hasSVG,
  14575. canvas: useCanVG,
  14576. vml: !hasSVG && !useCanVG,
  14577. product: PRODUCT,
  14578. version: VERSION
  14579. });
  14580. }());